Re: alt.possessive.its.has.no.apostrophe
James Stroud writes: > Ben Finney wrote: > > James Stroud writes: > > > >> Yes. I think it was the British who decided that the apostrophe > >> rule for "it" would be reversed from normal usage relative to > >> just about every other noun. It also seems an indefensible claim to say that anyone “decided” it would be that way, especially “the British”. > > Remember that “it” is a pronoun. I see no reversal: > > Ok. Pronouns are reversed. Or, more generally: Pronouns, which are different in just about every other way from other nouns, are different in this way also. Is that about right? -- \ “I met my girlfriend in Macy's; she was buying clothes, and I | `\ was putting Slinkies on the escalators.” —Steven Wright | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for the best way to translate an idiom
Aahz a écrit : In article , James Stroud wrote: In case its not obvious: Ah, so that's where Bruno's extra apostrophe came from! ;-) Err... Which one exactly ? (Sorry about the spelling flame, but seeing three posts in quick succession with incorrect spelling of its/it's pushed me into making a public comment.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
On Sun, 14 Dec 2008 20:38:58 -0800, cm_gui wrote: >> By the way... I know of a very slow Python site called YouTube.com. In >> fact, it is so slow that nobody ever uses it. > > hahaha, do you know how much money they are spending on hardware to make > youtube.com fast??? Oooh, I know! ONE MILLION DOLLARS And still cheaper and easier than re-writing YouTube's infrastructure in another language. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
On Mon, Dec 15, 2008 at 5:26 PM, Andreas Kostyrka wrote: > So to summarize, Python is fast enough for even demanding stuff, and > when done correctly even number crunching or binary parsing huge files > or possible in competitive speeds. But you sometime need a developer > that can wield the tool with a certain experience, and not a stupid > rookie that whines that his tool does not make his O(n**n) algorithm > automatically blazing fast. Amen! +10 --JamesMills -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
-*ε* Admittedly a tough call. I see the attraction of the proposed syntax. Maybe somewhat more readable since the declaration syntax matches the usage syntax, which is nice. I think it would have been superior to the current syntax if it had been done that way in the first place. However, since newbies will still have to learn both syntaxes in order to read other peoples code, it does not simplify the language. The main thing I don't like about it is that it violates this principle: "There should be one-- and preferably only one --obvious way to do it." Ken Daniel Fetchinson wrote: Hi folks, The story of the explicit self in method definitions has been discussed to death and we all know it will stay. However, Guido himself acknowledged that an alternative syntax makes perfect sense and having both (old and new) in a future version of python is a possibility since it maintains backward compatibility. The alternative syntax will be syntactic sugar for the old one. This blog post of his is what I'm talking about: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value I.e. explicit self stays only the syntax is slightly different and may seem attractive to some. As pointed out by Guido classmethods would work similarly: class C: @classmethod def cls.method( arg ): cls.val = arg return cls.val The fact that Guido says, "Now, I'm not saying that I like this better than the status quo. But I like it a lot better than [...] but it has the great advantage that it is backward compatible, and can be evolved into a PEP with a reference implementation without too much effort." shows that the proposal is viable. I'd like this new way of defining methods, what do you guys think? Anyone ready for writing a PEP? Cheers, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: alt.possessive.its.has.no.apostrophe
Ben Finney wrote: James Stroud writes: Ben Finney wrote: James Stroud writes: Yes. I think it was the British who decided that the apostrophe rule for "it" would be reversed from normal usage relative to just about every other noun. It also seems an indefensible claim to say that anyone “decided” it would be that way, especially “the British”. Remember that “it” is a pronoun. I see no reversal: Ok. Pronouns are reversed. Or, more generally: Pronouns, which are different in just about every other way from other nouns, are different in this way also. Is that about right? Can we start talking about python again? -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com -- http://mail.python.org/mailman/listinfo/python-list
Re: stable algorithm with complexity O(n)
On Sun, 14 Dec 2008 21:12:13 -0800, Aaron Brady wrote: > On Dec 14, 8:18 pm, Roy Smith wrote: >> Steven D'Aprano wrote: >> > All the positive thinking in the world won't help you: >> >> > * make a four-sided triangle; >> >> > * split a magnet into two individual poles; >> >> These two are fundamentally different problems. >> >> The first is impossible by definition. The definition of triangle is, >> "a three-sided polygon". Asking for a "four-sided triangle" is akin to >> asking for "a value of three which is equal to four". >> >> The second is only "impossible" because it contradicts our >> understanding (based on observation) of how the physical universe >> works. Our understanding could simply be wrong. We've certainly been >> wrong before, and we will undoubtedly be proven wrong again in the >> future. When it comes to things like electromagnetic theory, it >> doesn't take too many steps to get us to the fuzzy edge of quantum >> physics where we know there are huge questions yet to be answered. > > I agree. Most of his examples were tautologies. The magnet one was the > exception. > > Then, to beat the O( n lg n ) limit, just break an assumption. No no no, that's solving a different problem! You're welcome to solve a different problem if you like, and sometimes doing so is very valuable: sometimes the original problem turns out not to be important after all. But don't pretend that it's the same problem. >> > * or design a comparison sort which does fewer than O(n*log n) >> > two-way comparisons in the worst case, or fewer than O(n) comparisons >> > in the best case. > > Make a three-way comparison, make a non-comparison sort, or make non- > random inputs. Again no. Multi-way comparisons merely change the base of the logarithm, which in turn merely changes the constant term. It's still O(n*log n). Non-comparison sorts are a useful technique, but it's changing the problem, and they are only useful in very limited circumstances. There's a good reason that most sort routines are based on O(n*log n) comparison sorts instead of O(n) bucket sorts or radix sorts. And the quip about non-random inputs just shows you don't understand the problem you're being asked to solve. O(n*log n) is for the least number of comparisons needed for the worst possible input. It's not for the best possible input, or random input, or the average number of comparisons, or any other measurement. You've misunderstood the question if you think "give better input" is the answer. And frankly, it's *easy* to come up with a comparison sort that has O(n) behaviour for the best possible input. Bubble sort has O(n) behaviour for input that is already sorted. Even the infamous bogosort has O(n) behaviour for the best possible input: def is_sorted(alist): """Return True if alist is sorted, otherwise False.""" for i in xrange(1, len(alist)): if alist[i-1] > alist[i]: return False return True def bogosort(alist): # Shuffle alist until it happens to be sorted while not is_sorted(alist): random.shuffle(alist) I believe bogosort has behaviour O(n!), which is far worse than merely exponential O(2**n) complexity. But when given already sorted input, the version of bogosort above is O(n). Even the archtypically Awful (not just Bad) algorithm is amazingly fast if you happen to give it the best possible input. (By the way, the above code is not suitable for use in production code. Due to limitations of the standard Python random number generator, not all permutations of lists larger than a certain size can be generated. The default random number generator for Python 2.5 is the Mersenne Twister, which has a period of 2**19937-1. But the number of permutations of n items is n!, and n! is greater than 2**19937-1 for n=2081 or more. That means that for any list with 2081 or more items, there is a finite probability that the above implementation of bogosort will merely cycle repeatedly over 2**19937-1 unsorted permutations and hence never terminate.) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing None objects from a sequence
On Mon, 15 Dec 2008 05:39:45 +, Lie Ryan wrote: > I was just expressing the > preference that operators should be composed of a single word, > especially since none of the other operators are multi-words Then you should have said so, instead of introducing red-herrings about tired programmers. I must say, some years ago I probably would have agreed with you. I used to dislike "a is not b" and would go out of my way to write "not a is b". But then I decided that was just being silly, and I've never looked back. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help improving number guessing game
>Seems ok. You may want to use arguments with default values for a and b >(and possibly to use more meaningfull names): I changed it to minr and maxr. Mini is fine, but I can't name a variable maxi unless I have a good feminine hygiene joke to use with it. I don't see the aim of your changes to setup(). I can kinda understand checking to make sure that you didn't make the minimum higher than the maximum, but I think where you put minr/maxr would make it use the same minr/maxr as the end of the previous game, wouldn't it? >Minor point for a short program, but still good practice : use >constants. IE : I had done this initially, but it seemed wasteful and needlessly confusing in this situation. >I assume 'p1sc' means "player_1_score" ? >If so, you may want to use a dict for scores: I don't really understand dicts yet; actually, the tutorial I'm following (http://www.briggs.net.nz/log/writing/snake-wrangling-for- kids/ , designed for tweens, but other than the pointless anecdote and joke here and there, I've found it a very good guide) doesn't even seem to mention them, from a search of the pdf. Actually, apparently I stopped and started working on this just before the chapter on functions and modules. I'll look into that later on, but for now I'm pretty happy with how it works. >Is it really necessary to WRITE THIS IN ALL UPPERS ?-) If you didn't notice, in the original it was "CONGLATURATIONS". I could also make a "VIDEO GAME BAND. Heavy Metal's Not Dead." joke here, but I'm afraid a disappointingly small amount of people will get it. >Python has proper booleans too Yeah, I had those initially too, but "play = True" was causing trouble for some reason when I copy/pasted it into IDLE to try to troubleshoot, so I changed it to 1. I'll probably change it back later. >You should either put this in it's own function (could be named 'main'), >or at least "protect" it with an "if __name__ == '__main__':" test. Could you go into a bit more detail on this? I don't understand what should be its own function, nor do I understand what that line would do or how to use it. James, could you work that into a section of what I have to make it a bit easier to understand? -- http://mail.python.org/mailman/listinfo/python-list
كيف تخفي رقمك عن الذي تتصل به
ما هي: عندما تتصل على رقم لا يظهر لي المتصــل (أي رقم فآي دولة) طريقة الخدمة: أرسل رسالة نصية اكتب في الرسالة > TRA ZDOD أرسل إلى الرقم التالية البحرين الرمز (77127 )متوفر فقط لشركة زين البحرين الرمز (95312) متوفر فقط لشركة باتلكو مصر الرمز (95206) لبنان الرمز (1081) السعوديه الرمز (6752) متوفر فقط لشركة موبايلي السعوديه الرمز (85234) متوفر فقط لشركة الإتصالات السعودية الكويت الرمز (1489) قطر الرمز (2921) الامارات الرمزعلى (2252) من اتصالا الامارات الرمز على (2420) من دو -- http://mail.python.org/mailman/listinfo/python-list
Re: Py_GetPath() C API in python 3
On 12月13日, 上午9�r55分, "Gabriel Genellina" wrote: > En Fri, 12 Dec 2008 04:50:06 -0200, stalex escribió: > > >> I want to build a new, requires total control, python interpreter. So > >> I implement my own version of Py_GetPath(), Py_GetPrefix(), > >> Py_GetExecPrefix() and Py_GetProgramFullPath(). When compiling, I > >> always get error messages, for each API function, look like > >> followings: > > >> /opt/python-3.0/lib/python3.0/config/libpython3.0.a(getpath.o)(.text > >> +0x211c): In function `Py_GetPath': > >> ./Modules/getpath.c:739: multiple definition of `Py_GetPath' > >> myApp.o(.text+0x0):/home/alex/workspace/develop/src/myApp.c:11: first > >> defined here > >> /usr/bin/ld: Warning: size of symbol `Py_GetPath' changed from 126 in > >> system.o to 32 in /opt/python-3.0/lib/python3.0/config/libpython3.0.a > >> (getpath.o) > >> collect2: ld returned 1 exit status > > Looks like you added your own implementation of those functions > (/home/alex/...myApp.c) but forgot to remove the original one > (Modules/getpath.c) > > -- > Gabriel Genellina No, I didn't remvoe the original one. But, why do I need to do that? I just want to extend my application, based on the original python installed by administrator, not to build/install another one python interpreter. And by studing python api documentations, Py_GetPath() is a public interface python itself provides. So I could achieve my goal via implementating my own Py_GetPath() version as well as other Py_GetXXX(). By the way, my application is stable and runs well since 2 years ago. I do this just because I want to release, in the near future, a new version. And I want to migrate its kernel from python2.5 to python3. Any ideas? -- http://mail.python.org/mailman/listinfo/python-list
Re: %s place holder does not let me insert ' in an sql query with python.
sorry about that
queryString = "insert into venders
values('{0}','{1}','{2}')".format(field1,field2,field3)
On Mon, Dec 15, 2008 at 7:21 AM, Lamonte Harris wrote:
> I had this problem too. If you've upgraded to python 2.6 you need to use
> the new sytnax "format
>
> queryString = "insert into venders
> values('{0}','{1}','{2}'".format(field1,field2,field3)
>
>
> On Mon, Dec 15, 2008 at 6:46 AM, Krishnakant wrote:
>
>> hello all hackers.
>> This is some kind of an interesting situation although many of you must
>> have already gone through it.
>> I am facing a situation where I have to use psycopg2 and insert rows in
>> a postgresql table.
>> That's pritty easy and no need to say that it works well. But there are
>> some entries which have an ' in the value.
>> I have a venders table in my database and one of the values tryed was
>> "His Master's Voice "
>> now the master's word has the ' which is used for starting and ending a
>> varchar value for postgresql or almost any standard RDBMS.
>> Does any one know what is the way out of this?
>> how do you let the ' go as a part of the string?
>> I have used %s as placeholder as in
>> queryString = "insert into venders values ('%s,%s,%s" %
>> (field1,field2,field3 ) ...
>> This is not working for the ' values.
>> can any one suggest a suitable solution?
>> happy hacking.
>> Krishnakant.
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
--
http://mail.python.org/mailman/listinfo/python-list
UnicodeEncodeError
Hello!
I am using Windows XP professional version 2002 Service pack 3. AMD
Athlon(TM)XP 2400+ 2.00GHz 992MB RAM.
I have downloaded Windows x86 MSI Instaler Python 3.0 (sig) (r30:67507, Dec 3
2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32
Control Panel -> System -> Advanced -> Environment Variables. System Variables
-> Path -> edit C:\Windows\System32\Wbem;C:\Python30
start -> programs -> python 3.0 -> IDLE(Python GUI)
-> IDLE 3.0 -> File -> New Window -> i wrote "print('ğüşçöı')" without qutes->
File -> Save -> Python30 -> i gave file name "d2.py" without qutes-> and Run ->
Run Module -> it gives error "invalid character in identifier"
then i tried second method
start -> run -> cmd -> d2.py and enter it gives the error
C:\>d2.pyTraceback (most recent call last): File "C:\Python30\d2.py", line 4,
in print('\u011fü\u015fçö\u0131') File "C:\Python30\lib\io.py",
line 1491, in writeb = encoder.encode(s) File
"C:\Python30\lib\encodings\cp437.py", line 19, in encodereturn
codecs.charmap_encode(input,self.errors,encoding_map)[0]UnicodeEncodeError:
'charmap' codec can't encode character '\u011f' in position0: character maps to
C:\>
But if i write in Phyton Shell -> >>> print('ğüşçöı') and pressed enter ->
gives 'ğüşçöı' it works.
What is wrong?
all the best
_
Connect to the next generation of MSN Messenger
http://imagine-msn.com/messenger/launch80/default.aspx?locale=en-us&source=wlmailtagline--
http://mail.python.org/mailman/listinfo/python-list
Re: 1 or 1/0 doesn't raise an exception
Unfortunately,
bool('Ruby totally pwn3s Python!')
> True
Using Python is not total protection against buggy programs ;-)
--
Tim Rowe
--
http://mail.python.org/mailman/listinfo/python-list
Re: Having Issues with CMD and the 'python' command
"cmd" has _nothing_ to do with Python. --JamesMills -- -- "Problems are solved by method" On Mon, Dec 15, 2008 at 10:51 PM, Lamonte Harris wrote: > Every time I start cmd on windows it requires me to "set > path=%path%;C:\python26" why? I'm getting annoyed... > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Re: cx_Oracle issues
On Dec 15, 2:44 am, huw_at1 wrote: > On Dec 11, 5:34 pm, "[email protected]" wrote: > > > > > > > On Dec 10, 9:48 am, huw_at1 wrote: > > > > Hey all. When usingcx_Oracleto run a procedure like: > > > > cursor.execute("select (obj.function(value)) from table where > > > id=blah") > > > > I am getting the following error: > > > > ORA-06502: PL/SQL: numeric or value error: character string buffer too > > > small ORA-06512: at line 1 > > > > Looking at cursor.description I get: > > > > [('(obj.function(value))', , 4000, 4000, 0, > > > 0, 1)] > > > > Any tips - i have never seen this error before but am guessing that > > > the value being returned is too big for the buffer size set for the > > > cursor. the procedure fetches data from a LOB. > > > > Any suggestions/confirmations? > > > > Many thanks > > > This error is a problem with the PL/SQL, notcx_Oracle. You need to > > debug obj.function to see what kind of data is being accessed and then > > a data analysis of that data to understand why this error occurs. I > > can tell you the function is most likely expecting characters from a > > column that are numeric [0 .. 9] and is getting alpha characters. > > > -- > > Ron Reidy > > Sr. Oracle DBA > > Hi thanks for the responses. Unfortunately the procedure in question > is from a third party vendor so I can't really debug it so I'd say I > was fairly stumped. Just out of interest how do you increase the > output buffer size withcx_Oracle? > > Many thanks- Hide quoted text - > > - Show quoted text - Hi, Sure you can. You can see the PL/SQL source from the ditionary view ALL_SOURCE: select text from all_source where name = 'NAME_OF_FUNCTION'; >From there, reverse engineeer which table(s) and column(s) are being accesses and do the data analysis. -- Ron Reidy -- http://mail.python.org/mailman/listinfo/python-list
Re: Having Issues with CMD and the 'python' command
James Mills wrote: "cmd" has _nothing_ to do with Python. well, not quite "nothing"... http://docs.python.org/lib/module-cmd.html [grins, ducks and runs] (every time I see this module it makes me want to go write a small interactive-fiction game in the style of Zork/Adventure :) -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: %s place holder does not let me insert ' in an sql query with python.
I had this problem too. If you've upgraded to python 2.6 you need to use
the new sytnax "format
queryString = "insert into venders
values('{0}','{1}','{2}'".format(field1,field2,field3)
On Mon, Dec 15, 2008 at 6:46 AM, Krishnakant wrote:
> hello all hackers.
> This is some kind of an interesting situation although many of you must
> have already gone through it.
> I am facing a situation where I have to use psycopg2 and insert rows in
> a postgresql table.
> That's pritty easy and no need to say that it works well. But there are
> some entries which have an ' in the value.
> I have a venders table in my database and one of the values tryed was
> "His Master's Voice "
> now the master's word has the ' which is used for starting and ending a
> varchar value for postgresql or almost any standard RDBMS.
> Does any one know what is the way out of this?
> how do you let the ' go as a part of the string?
> I have used %s as placeholder as in
> queryString = "insert into venders values ('%s,%s,%s" %
> (field1,field2,field3 ) ...
> This is not working for the ' values.
> can any one suggest a suitable solution?
> happy hacking.
> Krishnakant.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Thread Locking issue - Can't allocate lock (sem_init fail)
On Dec 15, 2008, at 4:56 AM, [email protected] wrote: Hi all, I have a peculiar problem with a multithreaded program of mine (actually I've sort of inherited it). Before i show you the error, here's a litle background. Its a program to check email addresses are valid, and its main task is to verify the domain names. Here's the basic functionality: * The prog has a list of domains it has seen before which is read into memory (the 'rollover'). * A new list of emails is read-in from a file (to a queue) and is checked against the rollover. * If we've seen the domain before then update the existing entry. * If we've not seen the domain before, add it. The program is multithreaded to speed up the processing...there are input and output Queues. Now, each domain entry is an class object containing various bits of info. Each domain class also has its own lock, so that only one thread can modify each domain at a time. I'm load-testing the program with a sample of 1 million email addresses and when i hit about the 500,000 mark i get a locking error... sem_init: No space left on device Exception in thread Thread-2: Traceback (most recent call last): File "/usr/local/lib/python2.4/threading.py", line 442, in __bootstrap self.run() File "/usr/local/lib/python2.4/threading.py", line 422, in run self.__target(*self.__args, **self.__kwargs) File "jess.py", line 250, in worker record.result = function( id, record.value ) File "jess.py", line 291, in action found_domain = domains.addNewDomain( domain_name ) File "jess.py", line 123, in addNewDomain self.domain_store.append( self.Domain( name = name ) ) File "jess.py", line 46, in __init__ self.lock = Lock() error: can't allocate lock Googling for this sort of error doesn't yield any results, and i can't find any information about limits to the number of locks you can have in Python. The 'No space left on device' message indicates a memory issue, however i doubt this since its running on a linux server with 4 cores and 16GB ram. It seems more like an internal Python limit has been hit (sem_init - semaphore initialisation?). Does anyone know more about threading internals and any internal limits? Hi Jamskip, I don't work with threading code but I have been working with semaphores for my IPC extensions. sem_init() is a call to create a semaphore (http://linux.die.net/man/3/sem_init). If it is failing, then I'd guess you're trying to create an awful lot of semaphores (intentionally or otherwise) and that you're hitting some internal limit. I would not be too quick to assume that the number of semaphores one can create is bounded by the amount of RAM in your system. I don't think they're simple chunks of malloc-ed memory. They're probably represented in a kernel data structure somewhere that's hardcoded to some generous but fixed value. Please note that this is all speculation on my part. I think that the Python threading implementation would use the "local" (i.e. not process-shared) semaphores which can be allocated on the process' heap. This would seem only RAM-limited, but I'll bet it isn't. You might want to start debugging by track exactly how many locks you're creating. If the number is really big, start investigating kernel semaphore limits and how they're set. Good luck Philip -- http://mail.python.org/mailman/listinfo/python-list
Problem Python 2.6.1 vs 2.6 & pyWin32
Hi, all! I have several softwares using Python+PyWin32, often as COMèserver. Ok with Python 2.5.x. I want migrate to Python 2.6. But when I install python-2.6.1.msi + pywin32-212.win32-py2.6, my softs don't run. Tried on five machines (two XP & three Vista). But... if I install python-2.6.msi , IT'S OK!!! And, if I installl 2.6.1 once again, after 2.6, ... don't run ???!!! ;-((( In reality, soft run, but COM server can not be used. I get these messages : File "C:\Python26\Lib\site-packages\win32com\server\policy.py", line 728, in resolve_func module = _import_module(mname) File "C:\Python26\Lib\site-packages\win32com\server\policy.py", line 747, in _import_module __import__(mname) File "C:\Ponx\ponx.py", line 54, in import socket File "C:\Python26\lib\socket.py", line 46, in import _socket : DLL load failed: Le module spécifié est introuvable. "Erreur non spécifiée" (with call from JScript test, or VBScript test). (These tests run OK with 2.6 or 2.5.x) I am very disappointed. Help me, please. Thanks in advance. *** and sorry for my bad english *** @-salutations -- Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Managing timing in Python calls
I'm porting some ugly javascript managed stuff to have an equivalent
behaviour in a standalone app. It uses events that arrive from a server,
and various small images. In this standalone version, the data is local
in a file and the images in a local directory.
My AJAX code managed a timely presentation of the info, and in the
Javascript that relied on the ugly:
myImage.onload = function(){dosomething_when_it's_finished}
structure. Also, I used the similarly unpretty:
var t = window.setTimeout( function () { do_when_timed_out}
structures which allows stuff to happen after a perscribed period.
In my python implementation my first guess is to use a thread to load my
image into a variable
myImage = wx.Image("aPic.gif",
wx.BITMAP_TYPE_GIF ).ConvertToBitmap()
so that it won't block processing. (Though perhaps it'll just happen so
fast without a server involved that I won't care.)
Is there a nice equivalent of a 'setTimeout' function in python? ie to
call a function after some time elapses without blocking my other
processing? I suppose just a thread with a time.sleep(x_mS) in it would
be my first guess?
Can anyone give me some feedback on whether that's a logical path
forward, or if there are some nicer constructs into which I might look?
Thanks for any suggests... Ross.
--
http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] Having Issues with CMD and the 'python' command
"bob gailer" wrote Try this: Start->Settings->Control Panel->System->Advanced->Environment Variables Highlight PATH under System Variables & Click Edit. Add ;C:\python26 And notice that Bob said ADD - DO NOT REPLACE the existing setting or you will likely break stuff and its not easy to fix it afterwards unless you have a full backup to hand!! Alan G. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help improving number guessing game
feba wrote:
I don't see the aim of your changes to setup(). I can kinda understand
checking to make sure that you didn't make the minimum higher than the
maximum, but I think where you put minr/maxr would make it use the
same minr/maxr as the end of the previous game, wouldn't it?
No. Each function call creates its own name space. The function as Bruno
has written it will have default values (mini & maxi). A call to this
function can set different values optionally:
setup(2) #==> range from 2 to 99
setup(maxi=101) #==> range from 1 to 101
setup(5, 10) #==> range from 5 to 10
setup(10, 5) #==> throws an error
Minor point for a short program, but still good practice : use
constants. IE :
I had done this initially, but it seemed wasteful and needlessly
confusing in this situation.
No. Tracking down and changing hard-coded values within a module is
wasteful and needlessly confusing. Creating well named and well
documented module level constants is good style and will make your life
easier in the long run.
I assume 'p1sc' means "player_1_score" ?
If so, you may want to use a dict for scores:
I don't really understand dicts yet; actually, the tutorial I'm
following (http://www.briggs.net.nz/log/writing/snake-wrangling-for-
kids/ , designed for tweens, but other than the pointless anecdote and
joke here and there, I've found it a very good guide) doesn't even
seem to mention them, from a search of the pdf. Actually, apparently I
stopped and started working on this just before the chapter on
functions and modules.
scores = {'player 1' : 0, 'player 2' : 0 }
scores['player 2'] = 10#==> now player 2's score is 10
scores['player 1'] += 1#==> now player 1's score is 1
print scores['player 0'] #==> prints "0"
print scores['player 2'] * 2 #==> prints "20"
If you get that, you'll have about all you need to know about dicts to
use them for keeping track of scores (and other values) in your game.
I'll look into that later on, but for now I'm pretty happy with how it
works.
Try it sooner rather than later. I didn't get this kind of advice when I
was first learning. It would have shaved months from my learning curve.
You should either put this in it's own function (could be named 'main'),
or at least "protect" it with an "if __name__ == '__main__':" test.
Could you go into a bit more detail on this? I don't understand what
should be its own function, nor do I understand what that line would
do or how to use it.
The idea is that everything you write is reusable and can be imported as
a module. Upon importing a module, it's code is executed. So, as
written, if someone imports it as a library module, they will start
playing the game. Wrapping in the "if __name__ == '__main__':" test
prevents the main loop of the game from executing on import. Only when
the module is "__main__" will that test evaluate to true and its
commands execute.
For small programs like you have here, I'd do it like this (again
combining ideas):
def num_players(game, prompt='1 or 2 Players?\n> '):
while True:
num = input(prompt)
try:
num = int(num)
except ValueError:
print "Bad Value"
else:
break
game['pnum'] = num
def main(game=None):
if game is None:
game = {}
print("WELCOME TO THE SUPER NUMBER GUESSING GAME!")
num_players(game)
game['play'] = 1
# P1 goes first
game['player'] = "P1"
#Scores, keep track of times player guessed first.
game['p1sc'], game['p2sc'] = 0, 0
setup(game)
while game['play'] == 1:
guessing(game)
if __name__ == "__main__":
main()
I just threw a little advanced stuff at you. But you would be doing
yourself a huge favor if you struggled to understand it. The idea is
that since game is a dict, you can modify game inside of the functions,
and all you do is pass the game around to functions that need the values
of its contents.
For example:
def setup(game):
game['a'], game['b'] = 1, 99
game['target'] = random.randint(a, b)
def playagain(game):
playover = input("PLAY AGAIN? Y/N: ")
if playover.strip().lower() == "y":
game['play'] = 1
setup(game)
else:
print("GOOD BYE. PLAY AGAIN SOON!")
quit()
Notice that I just made return values obsolete.
You will also notice that management of all of your values now becomes
more tractable using the mutability of dict ("game"). Long, ugly lines
now become simple function calls. See if you can understand what I'm
doing here and try to propagate the idea through your game using the
game dict.
If you can do it, you'll be at least 80% of the way to understanding
object oriented programming, by the way.
James
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
http://www.jamesstroud.com
--
http://mail.python.org/mailman/listinfo/python-list
Re: %s place holder does not let me insert ' in an sql query with python.
On Dec 15, 2008, at 6:46 AM, Krishnakant wrote:
in this case, I get a problem when there is ' in any of the values
during insert or update.
That's because ' is the SQL string literal delimiter. But any SQL-
compliant database allows you to "escape" an apostrophe within a
string literal by doubling it. So for each of your values, just do:
value = value.replace("'", "''")
before stuffing them into your INSERT or UPDATE statement. (If these
values come from the user, and especially if they come over the
network, then you probably want to do a few other replacements; google
"SQL injection" for details.)
Note that I'm not familiar with the cursor.execute binding that RDM
pointed out, so that may provide a better solution... but the above
should work.
Best,
- Joe
--
http://mail.python.org/mailman/listinfo/python-list
Re: regex problem ..
Analog Kid wrote:
Hi All:
I am new to regular expressions in general, and not just re in python.
So, apologies if you find my question stupid :) I need some help with
forming a regex. Here is my scenario ...
I have strings coming in from a list, each of which I want to check
against a regular expression and see whether or not it "qualifies". By
that I mean I have a certain set of characters that are permissible and
if the string has characters which are not permissible, I need to flag
that string ... here is a snip ...
flagged = list()
strs = ['HELLO', 'Hi%20There', '123...@#@']
p = re.compile(r"""[^a-zA-Z0-9]""", re.UNICODE)
for s in strs:
if len(p.findall(s)) > 0:
flagged.append(s)
print flagged
my question is ... if I wanted to allow '%20' but not '%', how would my
current regex (r"""[^a-zA-Z0-9]""") be modified?
You might want to normalize before checking, e.g.
from urllib import unquote
p=re.compile("[^a-zA-Z0-9 ]")
flagged=[]
for s in strs:
if p.search(unquote(s)):
flagged.append(s)
be carefull however if you want to show the
flagged ones back to the user. Best is always
quote/unquote at the boundaries as appropriate.
Regards
Tino
smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list
Re: cx_Oracle issues
On Dec 11, 5:34 pm, "[email protected]" wrote: > On Dec 10, 9:48 am, huw_at1 wrote: > > > > > Hey all. When using cx_Oracle to run a procedure like: > > > cursor.execute("select (obj.function(value)) from table where > > id=blah") > > > I am getting the following error: > > > ORA-06502: PL/SQL: numeric or value error: character string buffer too > > small ORA-06512: at line 1 > > > Looking at cursor.description I get: > > > [('(obj.function(value))', , 4000, 4000, 0, > > 0, 1)] > > > Any tips - i have never seen this error before but am guessing that > > the value being returned is too big for the buffer size set for the > > cursor. the procedure fetches data from a LOB. > > > Any suggestions/confirmations? > > > Many thanks > > This error is a problem with the PL/SQL, not cx_Oracle. You need to > debug obj.function to see what kind of data is being accessed and then > a data analysis of that data to understand why this error occurs. I > can tell you the function is most likely expecting characters from a > column that are numeric [0 .. 9] and is getting alpha characters. > > -- > Ron Reidy > Sr. Oracle DBA Hi thanks for the responses. Unfortunately the procedure in question is from a third party vendor so I can't really debug it so I'd say I was fairly stumped. Just out of interest how do you increase the output buffer size with cx_Oracle? Many thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: cx_Oracle issues
huw_at1 writes: >> > ORA-06502: PL/SQL: numeric or value error: character string buffer too >> > small ORA-06512: at line 1 >> >> This error is a problem with the PL/SQL, not cx_Oracle. You need to >> debug obj.function to see what kind of data is being accessed and then >> a data analysis of that data to understand why this error occurs. I >> can tell you the function is most likely expecting characters from a >> column that are numeric [0 .. 9] and is getting alpha characters. > > Hi thanks for the responses. Unfortunately the procedure in question > is from a third party vendor so I can't really debug it so I'd say I > was fairly stumped. Just out of interest how do you increase the > output buffer size with cx_Oracle? Ron's point was that you cannot fix this problem on the side of cx_Oracle because the exception occurs before cx_Oracle ever sees the result, during the execution of PL/SQL code. This is easy to verify: simply run the function the same way in sqlplus. If the problem persists, it's a bug in the function (or in the way you're calling it, or setting up the data, etc.) and you should complain to your vendor, or somehow work around the problem. Otherwise it's a cx_Oracle related problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
On Dec 15, 8:15 am, Luis M. González wrote: > On Dec 15, 1:38 am, cm_gui wrote: > > > hahaha, do you know how much money they are spending on hardware to > > make > > youtube.com fast??? > > > > By the way... I know of a very slow Python site called YouTube.com. In > > > fact, it is so slow that nobody ever uses it. > > Buddy, just stop whining and go with c++ if it makes you happy. > By the way, what's the blazingly fast application you need to write so > desperately? > What kind of performance problem have you find in python that makes > you so unhappy? > What are you going to do with all the extra speed provided by c++ (a > Hello World! ?)... Folks, do you *really* feel the urge to feed this troll and his 8-year- old "arguments" again and again ? Please think twice before hitting send on this pointless thread. -- http://mail.python.org/mailman/listinfo/python-list
Re: %s place holder does not let me insert ' in an sql query with python.
On 15 Des, 14:46, Krishnakant wrote: > hello all, > thanks for all of your very quick responses. > The problem is that I am using python 2.5 so the 2.6 syntax does not > apply in my case. The parameter syntax for database operations is defined by the DB-API, and this is a very different matter to that of Python string substitution (or formatting). See this document for details: http://www.python.org/dev/peps/pep-0249/ You should note that when sending the SQL command to the database system, you do not use the % operator to prepare that command. Instead, you should pass the collection of parameters as the second argument of the execute method. In other words... cursor.execute(query, parameters) Note that the query is kept as a separate argument; you do not combine these two things yourself. Paul P.S. As far as I know, Python 2.6 still has the traditional printf- style substitution syntax, so any exhortation to adopt new-style formatting is ill-advised, especially since it has only slight relevance to this particular enquiry. -- http://mail.python.org/mailman/listinfo/python-list
Re: %s place holder does not let me insert ' in an sql query with python.
On Mon, 15 Dec 2008 18:16:18 +0530, Krishnakant wrote:
hello all hackers.
This is some kind of an interesting situation although many of you must
have already gone through it.
I am facing a situation where I have to use psycopg2 and insert rows in
a postgresql table.
That's pritty easy and no need to say that it works well. But there are
some entries which have an ' in the value.
I have a venders table in my database and one of the values tryed was
"His Master's Voice "
now the master's word has the ' which is used for starting and ending a
varchar value for postgresql or almost any standard RDBMS.
Does any one know what is the way out of this?
how do you let the ' go as a part of the string?
I have used %s as placeholder as in
queryString = "insert into venders values ('%s,%s,%s" %
(field1,field2,field3 ) ...
This is not working for the ' values.
can any one suggest a suitable solution?
You got pretty close to the right approach. All you have to do is
stop doing Python string interpolation.
Don't do this:
cursor.execute("foo (%s, %s, %s)" % (f1, f2, f3))
Instead, do this:
cursor.execute("foo (%s, %s, %s)", (f1, f2, f3))
This works for all data and avoid numerous potential security issues.
Doing it this way is called using "bind parameters". You should always
use bind parameters when executing a statement with variable data. You
should never ever use Python string interpolation as in the code you
included in your original post (or in some of the other responses you
received).
Jean-Paul
--
http://mail.python.org/mailman/listinfo/python-list
Re: Thread Locking issue - Can't allocate lock (sem_init fail)
Philip Semanchuk wrote: On Dec 15, 2008, at 4:56 AM, [email protected] wrote: Hi all, I have a peculiar problem with a multithreaded program of mine (actually I've sort of inherited it). Before i show you the error, here's a litle background. Its a program to check email addresses are valid, and its main task is to verify the domain names. Here's the basic functionality: * The prog has a list of domains it has seen before which is read into memory (the 'rollover'). * A new list of emails is read-in from a file (to a queue) and is checked against the rollover. * If we've seen the domain before then update the existing entry. * If we've not seen the domain before, add it. The program is multithreaded to speed up the processing...there are input and output Queues. Now, each domain entry is an class object containing various bits of info. Each domain class also has its own lock, so that only one thread can modify each domain at a time. I'm load-testing the program with a sample of 1 million email addresses and when i hit about the 500,000 mark i get a locking error... sem_init: No space left on device Exception in thread Thread-2: Traceback (most recent call last): File "/usr/local/lib/python2.4/threading.py", line 442, in __bootstrap self.run() File "/usr/local/lib/python2.4/threading.py", line 422, in run self.__target(*self.__args, **self.__kwargs) File "jess.py", line 250, in worker record.result = function( id, record.value ) File "jess.py", line 291, in action found_domain = domains.addNewDomain( domain_name ) File "jess.py", line 123, in addNewDomain self.domain_store.append( self.Domain( name = name ) ) File "jess.py", line 46, in __init__ self.lock = Lock() error: can't allocate lock Googling for this sort of error doesn't yield any results, and i can't find any information about limits to the number of locks you can have in Python. The 'No space left on device' message indicates a memory issue, however i doubt this since its running on a linux server with 4 cores and 16GB ram. It seems more like an internal Python limit has been hit (sem_init - semaphore initialisation?). Does anyone know more about threading internals and any internal limits? Hi Jamskip, I don't work with threading code but I have been working with semaphores for my IPC extensions. sem_init() is a call to create a semaphore (http://linux.die.net/man/3/sem_init). If it is failing, then I'd guess you're trying to create an awful lot of semaphores (intentionally or otherwise) and that you're hitting some internal limit. I would not be too quick to assume that the number of semaphores one can create is bounded by the amount of RAM in your system. I don't think they're simple chunks of malloc-ed memory. They're probably represented in a kernel data structure somewhere that's hardcoded to some generous but fixed value. Please note that this is all speculation on my part. I think that the Python threading implementation would use the "local" (i.e. not process-shared) semaphores which can be allocated on the process' heap. This would seem only RAM-limited, but I'll bet it isn't. You might want to start debugging by track exactly how many locks you're creating. If the number is really big, start investigating kernel semaphore limits and how they're set. You're creating a thread and a lock for each _domain_? Sounds like overkill to me. Many domains means many threads and many locks, by the sounds of it too many for the system. -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for the best way to translate an idiom
In article <[email protected]>, Bruno Desthuilliers wrote: >Aahz a écrit : >> In article , >> James Stroud wrote: >>> >>> In case its not obvious: >> >> Ah, so that's where Bruno's extra apostrophe came from! ;-) > >Err... Which one exactly ? Don't remember, it was a post I read about five minutes earlier that had something like, "...has it's place..." -- Aahz ([email protected]) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for the best way to translate an idiom
James Stroud wrote: > Aahz wrote: >> In article , >> James Stroud wrote: >>> In case its not obvious: >> >> Ah, so that's where Bruno's extra apostrophe came from! ;-) >> >> >> (Sorry about the spelling flame, but seeing three posts in quick >> succession with incorrect spelling of its/it's pushed me into making a >> public comment.) > > Yes. I think it was the British who decided that the apostrophe rule for > "it" would be reversed from normal usage relative to just about every > other noun. I'm not sure the purpose--maybe it was to give compulsive > proofreaders a raison d'etre. In fact it applies to personal pronouns generally, though in English most personal pronouns have an irregular genitive. Imemy mine you you your yours he him hishis she her herhers it ititsits we usourours you you your yours they them their theirs regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: alt.possessive.its.has.no.apostrophe
Ben Finney wrote: > James Stroud writes: > >> Ben Finney wrote: >>> James Stroud writes: >>> Yes. I think it was the British who decided that the apostrophe rule for "it" would be reversed from normal usage relative to just about every other noun. > > It also seems an indefensible claim to say that anyone “decided” it > would be that way, especially “the British”. > It's our language, dammit! Ours, ours, ours! This decision was actually taken at a meeting of the Society of British pedants on November 23, 1786. This led to a schism between the British and the newly-independent Americans, who responded by taking the "u" out of colour, valour, and aluminium. >>> Remember that “it” is a pronoun. I see no reversal: >> Ok. Pronouns are reversed. > > Or, more generally: Pronouns, which are different in just about every > other way from other nouns, are different in this way also. Is that > about right? > Just think of them as "nounpros" and you won't go wrong. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Having Issues with CMD and the 'python' command
On Mon, 15 Dec 2008 at 23:01, James Mills wrote: On Mon, Dec 15, 2008 at 10:51 PM, Lamonte Harris wrote: Every time I start cmd on windows it requires me to "set path=%path%;C:\python26" why? I'm getting annoyed... "cmd" has _nothing_ to do with Python. (Top posting corrected.) But the answer is that you need to update your PATH string at the system level. You do that in Control Panel/System/Advanced/Environment variables (it's a button on the advanced screen, which is something that confused me the first time I went looking for it). ObPython: you know, it occurs to me that Windows follows exactly the opposite philosophy from Python when it comes to hierarchy. Python's Zen is "shallow is better than deep", whereas Windows' philosophy is "deep is better than shallow". Every release of Windows seems to bury the things one needs to do to administer the system deeper and deeper inside a nested set of windows...and every time I touch Windows I am reminded how sensible the Python Zen is :) --RDM -- http://mail.python.org/mailman/listinfo/python-list
Re: %s place holder does not let me insert ' in an sql query with python.
On Mon, 15 Dec 2008 at 18:16, Krishnakant wrote:
how do you let the ' go as a part of the string?
I have used %s as placeholder as in
queryString = "insert into venders values ('%s,%s,%s" %
(field1,field2,field3 ) ...
This is not working for the ' values.
This is untested, but I think what you want is:
cursor.execute("insert into venders values (?, ?, ?)", field1, field2,
field3)
This uses parameter binding and should properly quote the values.
It's also the "right way" to do it to avoid sql injection attacks
and for efficiency if you run the same query multiple times.
--RDM
--
http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] Having Issues with CMD and the 'python' command
Lamonte Harris wrote: Every time I start cmd on windows it requires me to "set path=%path%;C:\python26" why? I'm getting annoyed... I have never started cmd and have it require anything. I guess what you are really asking is "how to permanenly set an environment variable". In this case so you can launch Python by just typing python at the cmd prompt? Are we on the same page so far? And realize this is not a Python question but rather a Windows question? Try this: Start->Settings->Control Panel->System->Advanced->Environment Variables Highlight PATH under System Variables & Click Edit. Add ;C:\python26 -- Bob Gailer Chapel Hill NC 919-636-4239 -- http://mail.python.org/mailman/listinfo/python-list
%s place holder does not let me insert ' in an sql query with python.
hello all hackers.
This is some kind of an interesting situation although many of you must
have already gone through it.
I am facing a situation where I have to use psycopg2 and insert rows in
a postgresql table.
That's pritty easy and no need to say that it works well. But there are
some entries which have an ' in the value.
I have a venders table in my database and one of the values tryed was
"His Master's Voice "
now the master's word has the ' which is used for starting and ending a
varchar value for postgresql or almost any standard RDBMS.
Does any one know what is the way out of this?
how do you let the ' go as a part of the string?
I have used %s as placeholder as in
queryString = "insert into venders values ('%s,%s,%s" %
(field1,field2,field3 ) ...
This is not working for the ' values.
can any one suggest a suitable solution?
happy hacking.
Krishnakant.
--
http://mail.python.org/mailman/listinfo/python-list
Re: stable algorithm with complexity O(n)
> Non-comparison sorts are a useful technique, but it's changing the > problem, and they are only useful in very limited circumstances. There's > a good reason that most sort routines are based on O(n*log n) comparison > sorts instead of O(n) bucket sorts or radix sorts. > This is an assumption that I never quite understood. What most people want is to have sorted data, they don't care if I used a sorting or non-sorting comparison to do it. I think it is just that in most cases n is not very big anyway and comparison sorts make it easier on the programmer to create arbitrary types that are sortable. -- http://mail.python.org/mailman/listinfo/python-list
Re: 1 or 1/0 doesn't raise an exception
On 2008-12-14, Peter Otten <[email protected]> wrote: > Grant Edwards wrote: > >> Short circuit evaluation of booleans is very common (and has >> been for decades), so I don't know why people would expect >> something else. > > Visual Basic ;) I should have known... -- Grant Edwards grante Yow! I'm using my X-RAY at VISION to obtain a rare visi.comglimpse of the INNER WORKINGS of this POTATO!! -- http://mail.python.org/mailman/listinfo/python-list
Re: stable algorithm with complexity O(n)
On Dec 15, 11:05 am, [email protected] wrote: > > Non-comparison sorts are a useful technique, but it's changing the > > problem, and they are only useful in very limited circumstances. There's > > a good reason that most sort routines are based on O(n*log n) comparison > > sorts instead of O(n) bucket sorts or radix sorts. > > This is an assumption that I never quite understood. What most people > want is to have sorted data, they don't care if I used a sorting or > non-sorting comparison to do it. I think it is just that in most cases > n is not very big anyway and comparison sorts make it easier on the > programmer to create arbitrary types that are sortable. I meant they don't care if I use a comparison or non-comparison sort of course. -- http://mail.python.org/mailman/listinfo/python-list
Re: alt.possessive.its.has.no.apostrophe
Steve Holden wrote: This led to a schism between the British and the newly-independent Americans, who responded by taking the "u" out of colour, valour, and aluminium. Darn Americans and their alminim ;-) Next thing you know, they'll be putting an I in TEAM.[1] -tkc [1] http://www.quotedb.com/quotes/2417 -- http://mail.python.org/mailman/listinfo/python-list
Re: alt.possessive.its.has.no.apostrophe
Steve Holden wrote: Ben Finney wrote: James Stroud writes: Ben Finney wrote: James Stroud writes: Yes. I think it was the British who decided that the apostrophe rule for "it" would be reversed from normal usage relative to just about every other noun. It also seems an indefensible claim to say that anyone “decided” it would be that way, especially “the British”. It's our language, dammit! Ours, ours, ours! This decision was actually taken at a meeting of the Society of British pedants on November 23, 1786. This led to a schism between the British and the newly-independent Americans, who responded by taking the "u" out of colour, valour, and aluminium. Actually the Americans have been a bit confused about how to spell aluminium. See http://en.wikipedia.org/wiki/Aluminium_(element). Remember that “it” is a pronoun. I see no reversal: Ok. Pronouns are reversed. Or, more generally: Pronouns, which are different in just about every other way from other nouns, are different in this way also. Is that about right? Just think of them as "nounpros" and you won't go wrong. I've just remembered a pronoun that does take an apostrophe: the indefinite pronoun "one". Not that one uses it that often. :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Managing timing in Python calls
On 15 Dic, 16:21, Ross wrote:
> I'm porting some ugly javascript managed stuff to have an equivalent
> behaviour in a standalone app. It uses events that arrive from a server,
> and various small images. In this standalone version, the data is local
> in a file and the images in a local directory.
>
> My AJAX code managed a timely presentation of the info, and in the
> Javascript that relied on the ugly:
>
> myImage.onload = function(){dosomething_when_it's_finished}
>
> structure. Also, I used the similarly unpretty:
>
> var t = window.setTimeout( function () { do_when_timed_out}
>
> structures which allows stuff to happen after a perscribed period.
>
> In my python implementation my first guess is to use a thread to load my
> image into a variable
>
> myImage = wx.Image("aPic.gif",
> wx.BITMAP_TYPE_GIF ).ConvertToBitmap()
>
> so that it won't block processing. (Though perhaps it'll just happen so
> fast without a server involved that I won't care.)
>
> Is there a nice equivalent of a 'setTimeout' function in python? ie to
> call a function after some time elapses without blocking my other
> processing? I suppose just a thread with a time.sleep(x_mS) in it would
> be my first guess?
>
> Can anyone give me some feedback on whether that's a logical path
> forward, or if there are some nicer constructs into which I might look?
>
> Thanks for any suggests... Ross.
Python has in its standard library a timer class which actually is
implemented as a thread (I think) ...
however, when using a GUI package, I think it is better to use gui-
specific functions for event-driven programming,
to make sure that your code do not mess with GUI event loop and to
work around the lack of thread-safety in some GUI libraries.
This applies to timer/timeouts but also to execute code when specific
I/O events occur ( e.g. the receiving of data from a socket ).
Although I'm not an expert of pywx, a quick search pointed me to this
page:
http://wxpython.org/onlinedocs.php
from which it seams that WxTimerEvent couldbe what you need.
I agree with you that for loading images from local files a thread
should not be needed.
P.S : notice that the documentation refers to the C++ library on which
the python wrapper is built. This is often the case for
python wrapper of GUI libraries. However, the most important ones come
with a rich set of demo programs (and pywx demo suite is quite
complete) from which one can lear what he needs.
Ciao
-
FB
--
http://mail.python.org/mailman/listinfo/python-list
Re: alt.possessive.its.has.no.apostrophe
Tim Chase wrote: Steve Holden wrote: This led to a schism between the British and the newly-independent Americans, who responded by taking the "u" out of colour, valour, and aluminium. Darn Americans and their alminim ;-) Next thing you know, they'll be putting an I in TEAM.[1] -tkc [1] http://www.quotedb.com/quotes/2417 But there is ME in TEAM. -- http://mail.python.org/mailman/listinfo/python-list
Re: stable algorithm with complexity O(n)
On Mon, Dec 15, 2008 at 11:05 AM, wrote: >> Non-comparison sorts are a useful technique, but it's changing the >> problem, and they are only useful in very limited circumstances. There's >> a good reason that most sort routines are based on O(n*log n) comparison >> sorts instead of O(n) bucket sorts or radix sorts. >> > This is an assumption that I never quite understood. What most people > want is to have sorted data, they don't care if I used a sorting or > non-sorting comparison to do it. I think it is just that in most cases > n is not very big anyway and comparison sorts make it easier on the > programmer to create arbitrary types that are sortable. And if n is small and sparse (ie, k > n) , O(k*n) for radix sort could be worse than O(n^2). You could also ask why people make such a big deal about quicksort over mergesort, since mergesort has a guaranteed O(n log n) time whereas quicksort can be O(n^2) on pathological cases. I think I remember learning in my algorithms class that for small sorts (n < ~40) , bubblesort can actually be the fastest (or close to the fastest) in terms of wall-clock time because it has a relatively small constant factor in its O(n^2) complexity. -- http://mail.python.org/mailman/listinfo/python-list
Structure using whitespace vs logical whitespace
I've been trying to search through the years of Python talk to find an
answer to this, but my Googlefu is weak.
In most languages, I'll do something like this
xmlWriter.BeginElement("parent");
xmlWriter.BeginElement("child");
--xml.Writer.Characters("subtext");
xmlWriter.EndElement();
xmlWriter.EndElement();
Where the dashes are indentation (since some newsgroup handlers don't
do tabs well). XML writing is just an example.
In general, I'm using indentation to show logical flow through code.
Python's choice to give semantic meaning to whitespace prevents me
from doing such things. What was once reserved for logical use is now
used syntactically. In 90% of cases, its not needed, and whitespace
significance seems to be pretty effective. In that last 10%, however,
I've been frustrated many times.
I've been using python for a few years, and gotten around this in one
way or another, but now I want to get other who work with me to pick
up Python. All newbies to Python have trouble with the idea of
whitespace sensitivity, but how can I convince them that "it just
works better" when I have this construct which I want to use but
can't.
Has anybody found a way to emulate this behavior? I've often done it
by opening an expression for the whole thing, but there's a lot of
tasks where a single expression just isn't sufficient (such as things
with assignment).
PS. In my opinion the solution would be to have the option of entering
a "whitespace insensitive" mode which uses C style {} and ;. The
token to enter it could be as complicated as you want (in fact, it may
make sense to make it complicated to discourage use unless it's really
advantageous). I'd sugest {{ and }} or something bigger like {={ }
=}. Only two problems: 1) I'm sure it would offend Guido's sense of
language aesthetics 2) I'm sure the idea has been hashed over on this
newsgroup to death... hence prefering a workaround instead.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Need help improving number guessing game
On Mon, 15 Dec 2008 01:06:51 -0800, feba wrote:
> I don't really understand dicts yet; actually, the tutorial I'm
> following (http://www.briggs.net.nz/log/writing/snake-wrangling-for-
> kids/ , designed for tweens, but other than the pointless anecdote
> and joke here and there, I've found it a very good guide) doesn't
> even seem to mention them, from a search of the pdf. Actually,
> apparently I stopped and started working on this just before the
> chapter on functions and modules.
>
> I'll look into that later on, but for now I'm pretty happy with how
> it works.
Dicts, or dictionaries, also known as "hash tables" in some computer
languages, are a mapping from a key to a value. Think of looking up a
word in a real dictionary: the word is the key, and the definition is
the value.
Imagine a game with multiple players, each known by their name.
Because you don't know how many players there are, or what their
names are, you can't do this:
fred_score = 0 # How do I know there's a player called Fred?
barney_score = 0
...
But you can do this:
names = get_players_names()
scores = {} # start with an empty dict
for name in names:
# the player name is the key, and the score is the value
scores[name] = 0
print scores
=> {"fred": 0, "barney": 0, "wilma": 0, "betty": 0}
(or whatever names you have been given).
Later, you want to print Fred's score:
print "%s's score is %d" % ("fred", scores["fred"])
will print "fred's score is 0".
You might need to add 1 to Wilma's score:
score["wilma"] += 1
And so forth.
[...]
>>You should either put this in it's own function (could be
>>named 'main'), or at least "protect" it with an "if __name__
>>== '__main__':" test.
>
> Could you go into a bit more detail on this? I don't understand what
> should be its own function, nor do I understand what that line would
> do or how to use it.
Consider a really simple Python module:
# module.py
def hello():
print "Hello parrot!"
print "Running the module"
hello()
# end module.py
If you execute that file, from the commandline or the desktop, it
prints
Running the module
Hello parrot!
just as you expect. But when another Python module imports it, using
the command "import module", not only is the function hello() loaded,
but the two lines above are printed too -- but only the first time
you import the module. This is usually not what you want.
Generally, you want the *execution* to be separate from the
*importing*. There is a way to do this is Python:
# module.py
def hello():
print "Hello parrot!"
if __name__ == "__main__":
print "Running the module"
hello()
# end module.py
When you import the module, Python sets the special variable
"__name__" to the string "module". It's the name of the module. But
when you are executing the file from the command line, Python sets
the special variable to the magic string "__main__" instead. So the
code inside the if __name__ block is only executed when you are
actually executing the module, not when you import the module.
Hope this helps somewhat.
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Thread Locking issue - Can't allocate lock (sem_init fail)
Hi all, I have a peculiar problem with a multithreaded program of mine (actually I've sort of inherited it). Before i show you the error, here's a litle background. Its a program to check email addresses are valid, and its main task is to verify the domain names. Here's the basic functionality: * The prog has a list of domains it has seen before which is read into memory (the 'rollover'). * A new list of emails is read-in from a file (to a queue) and is checked against the rollover. * If we've seen the domain before then update the existing entry. * If we've not seen the domain before, add it. The program is multithreaded to speed up the processing...there are input and output Queues. Now, each domain entry is an class object containing various bits of info. Each domain class also has its own lock, so that only one thread can modify each domain at a time. I'm load-testing the program with a sample of 1 million email addresses and when i hit about the 500,000 mark i get a locking error... sem_init: No space left on device Exception in thread Thread-2: Traceback (most recent call last): File "/usr/local/lib/python2.4/threading.py", line 442, in __bootstrap self.run() File "/usr/local/lib/python2.4/threading.py", line 422, in run self.__target(*self.__args, **self.__kwargs) File "jess.py", line 250, in worker record.result = function( id, record.value ) File "jess.py", line 291, in action found_domain = domains.addNewDomain( domain_name ) File "jess.py", line 123, in addNewDomain self.domain_store.append( self.Domain( name = name ) ) File "jess.py", line 46, in __init__ self.lock = Lock() error: can't allocate lock Googling for this sort of error doesn't yield any results, and i can't find any information about limits to the number of locks you can have in Python. The 'No space left on device' message indicates a memory issue, however i doubt this since its running on a linux server with 4 cores and 16GB ram. It seems more like an internal Python limit has been hit (sem_init - semaphore initialisation?). Does anyone know more about threading internals and any internal limits? For the timebeing, I've implemented locking at a higher level which will reduce performance but keep the number of lock objects to a minumum. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Managing timing in Python calls
[email protected] wrote: Python has in its standard library a timer class which actually is implemented as a thread (I think) ... however, when using a GUI package, I think it is better to use gui- specific functions for event-driven programming, to make sure that your code do not mess with GUI event loop and to work around the lack of thread-safety in some GUI libraries. This applies to timer/timeouts but also to execute code when specific I/O events occur ( e.g. the receiving of data from a socket ). Although I'm not an expert of pywx, a quick search pointed me to this page: http://wxpython.org/onlinedocs.php from which it seams that WxTimerEvent couldbe what you need. I agree with you that for loading images from local files a thread should not be needed. P.S : notice that the documentation refers to the C++ library on which the python wrapper is built. This is often the case for python wrapper of GUI libraries. However, the most important ones come with a rich set of demo programs (and pywx demo suite is quite complete) from which one can lear what he needs. Ciao - FB The wxTimerEvent does sound attractive - I'll look into that. Thanks too for the opinion on loading images - gives me some guts to just give it a try without threading it and see how it goes. I appreciate the quick input :) Ross. -- http://mail.python.org/mailman/listinfo/python-list
pylab.ylabel: put label on the other side
Hey everybody,
I'm plotting graphs with 2 y-axes, which I created using
ax_left = pylab.subplot(111)
ax_right = pylab.twinx()
Then I switch the sides of the ticks:
ax_left.yaxis.tick_right()
ax_right.yaxis.tick_left()
This works, the ticks are on the opposite sides (left axis ticks are on
the right side and vice-versa).
But, when I want to label the y-axes with for example
pylab.axes(ax_left)
pylab.ylabel('Some label')
they are on the wrong side, i.e. not on the same side as the ticks of
the corresponding y-axis. For this example, the label would be on the
left side instead of the right side.
This is giving me headaches for quite a few hours now, so maybe somebody
knows a solution.
Regards,
antoine
--
http://mail.python.org/mailman/listinfo/python-list
Re: Looking for the best way to translate an idiom
James Stroud wrote: Aahz wrote: In article , James Stroud wrote: In case its not obvious: Ah, so that's where Bruno's extra apostrophe came from! ;-) (Sorry about the spelling flame, but seeing three posts in quick succession with incorrect spelling of its/it's pushed me into making a public comment.) Yes. I think it was the British who decided that the apostrophe rule for "it" would be reversed from normal usage relative to just about every other noun. I'm not sure the purpose--maybe it was to give compulsive proofreaders a raison d'etre. No possessive pronoun has an apostrophe. Contractions of "is", etc, do, whether for nouns or pronouns. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
On Dec 15, 1:38 am, cm_gui wrote: > hahaha, do you know how much money they are spending on hardware to > make > youtube.com fast??? > > > By the way... I know of a very slow Python site called YouTube.com. In > > fact, it is so slow that nobody ever uses it. > > Buddy, just stop whining and go with c++ if it makes you happy. By the way, what's the blazingly fast application you need to write so desperately? What kind of performance problem have you find in python that makes you so unhappy? What are you going to do with all the extra speed provided by c++ (a Hello World! ?)... -- http://mail.python.org/mailman/listinfo/python-list
Re: Limit traceback from most recent call
Brian Allen Vanderburg II wrote: I've looked at traceback module but I can't find how to limit traceback from the most recent call if it is possible. I see that extract_tb has a limit parameter, but it limits from the start and not the end. Currently I've made my own traceback code to do this but wonder if python already has a way to do this build in: def format_partial_exc(limit=None): (type, value, tb) = sys.exc_info() items = traceback.extract_tb(tb) if limit: items = items[-limit:] # Get last 'limit' items and not first result = 'Traceback (most recent call last):\n' items = traceback.format_list(items) for i in items: result += i # Newline already included result += type.__name__ + ': ' + str(value) return result Is this possible currently from traceback or other python module? Brian A. Vanderburg II If memory serves, you can catch the exception, then re-raise it -- this should hide all the traceback below where you caught it, but still return the actual error. Hope this helps. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: XMPP xmpppy - User Authorization
On Dec 14, 4:23 am, "James Mills" wrote: > On Sun, Dec 14, 2008 at 3:47 PM, Henson wrote: > > In my own bot, using the latestxmpppy, I've been printing everything > > going to the message handler to the screen. I've yet to see a > > 'subscribe' string. Has this changed? > > No this hasn't changed. This is the string you need > to check for. It does work :) > > cheers > James > > > > -- > -- "Problems are solved by method" Found it. To me, the 'subscribe' was coming in through the Presence handler, not the Message handler. Thanks for the heads up, - Henson -- http://mail.python.org/mailman/listinfo/python-list
Re: alt.possessive.its.has.no.apostrophe
James Stroud writes: > Ben Finney wrote: > > Or, more generally: Pronouns, which are different in just about > > every other way from other nouns, are different in this way also. > > Is that about right? > > Can we start talking about python again? Not with this thread subject :-) -- \ “We are not gonna be great; we are not gonna be amazing; we are | `\ gonna be *amazingly* amazing!” —Zaphod Beeblebrox, _The | _o__)Hitch-Hiker's Guide To The Galaxy_, Douglas Adams | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: alt.possessive.its.has.no.apostrophe
Tim Chase wrote: > Steve Holden wrote: >> This led to a schism between the British and the >> newly-independent Americans, who responded by taking the "u" >> out of colour, valour, and aluminium. > > Darn Americans and their alminim ;-) > > Next thing you know, they'll be putting an I in TEAM.[1] > It's called humour. Or humor. Or incompetence ;-) regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting in to metaprogramming
On Nov 27, 9:56 pm, "Hendrik van Rooyen" wrote: > "Steven D'Aprano" > > >GUI designer. You write a program to let the user create code by clicking > >buttons, dragging objects, drawing lines, etc. The GUI designer may use > >classes, but the purpose of those classes is to generate source code. > > Yikes, this is getting hairy- If "the problem" is to generate source code, > then you have to generate source code... > > >Testing code speed... you might have some functions with a loop, and you > >want to unroll the loop as an optimization. If you have one function, you > >can unroll it yourself. If you have a hundred such functions, you might > >want to write a program to do it. (Yes, I'm stretching...) > > Ok this one I'll buy - I can't think of a way to do this dynamically in a > class and get runnable code back. (but maybe I'm just not trying hard enough.) > > > > >Don't like that Python doesn't optimize tail-recursion? Then write a > >source-code analyzer that detects tail-recursion and re-writes the > >function using a while loop. > > This is like TJR's example (I think) > > > > > > >>> Thinking further back, when I was young and programming in Apple's > >>> Hypercard 4GL, I used to frequently use Hypercard scripts to generate > >>> new Hypercard scripts. That was to work around the limitations of the > >>> scripting language. > > >> What sort of stuff did you do, and would having had simple OO available > >> have rendered it unnecessary? > > >It's been 20-odd years, and the examples were pretty trivial... I don't > >really recall exactly, but it would have been something like this: > > >* design a GUI involving lots of buttons on screen, each one with quite > >similar but not identical code; > > >* since Hypercard didn't have a layout manager, write a script to > >generate each button, place it where needed, and set the button's code. > > >Hypercard did have a message passing hierarchy (like inheritance for > >objects), so often you could take the button's code and place it in a > >higher level of the hierarchy (the card, the background, the stack), but > >there were odd cases where that wasn't enough. > > >Another example: Hypercard had a very limited number of GUI elements > >(text fields and buttons, basically) but I designed a slider control > >using a few buttons, each button with a custom script. To avoid needing > >to create and place the buttons by hand each time I wanted a slider, I > >had a script that did it for me. The script not only created the buttons, > >but it created the scripts used by the buttons. This wasn't as difficult > >as it sounds -- it was basically taking a template and doing some text > >replacements, then telling the button to use it as a script. > > Ok I think I am beginning to get the picture - when you have to do stuff > that the language does not directly support, then you use the simple > available elements, and create source code that strings them together > to make more complex stuff. -in this case its probably not trivial to > do it at run time. > > The "make the source code" then run it, introduces a kind of compiler > stage. > > For an old assembler programmer, this is starting to sound like macros. > > So a different meta law would read like: > > One uses Code Generation Techniques when the language does not > have macros. > > *ducks* > > - Hendrik- Hide quoted text - > > - Show quoted text - I have been converting stuff like sound 100, 1 exc... and just writing like 100, 1 for a number of languages and then just loading it into a spreadsheet so that I can save little pieces of songs exc.. I can even use different compilers or libraries that way.. I have started doing that for quickbasic, qbasic, free basic, qb64, c++ All I do is use strings and '\n'.. I get to use a large number of older sounds and effects (for basic) on newer compilers that have aditional options.. It just looks like another music tracker.. I am not sure if that fits what you are trying to do though. -- http://mail.python.org/mailman/listinfo/python-list
Having Issues with CMD and the 'python' command
Every time I start cmd on windows it requires me to "set path=%path%;C:\python26" why? I'm getting annoyed... -- http://mail.python.org/mailman/listinfo/python-list
Re: Having Issues with CMD and the 'python' command
It was python3 messing me up. I forgot I had python 3 on my box uninstalled it, redid it and wallah. On Mon, Dec 15, 2008 at 7:33 AM, wrote: > On Mon, 15 Dec 2008 at 07:16, Lamonte Harris wrote: > >> Yeah I tried doing it from the environment variables yet it still fails to >> work. >> > > Well, I can't be of any more help, then. It worked for me on my XP Home > box, and at this point we've exhausted my knowledge of windows :) > > --RDM > -- http://mail.python.org/mailman/listinfo/python-list
Re: Structure using whitespace vs logical whitespace
[email protected] wrote: I've been trying to search through the years of Python talk to find an answer to this, but my Googlefu is weak. In most languages, I'll do something like this xmlWriter.BeginElement("parent"); xmlWriter.BeginElement("child"); --xml.Writer.Characters("subtext"); xmlWriter.EndElement(); xmlWriter.EndElement(); Where the dashes are indentation (since some newsgroup handlers don't do tabs well). XML writing is just an example. In general, I'm using indentation to show logical flow through code. Python's choice to give semantic meaning to whitespace prevents me from doing such things. What was once reserved for logical use is now used syntactically. In 90% of cases, its not needed, and whitespace significance seems to be pretty effective. In that last 10%, however, I've been frustrated many times. I've been using python for a few years, and gotten around this in one way or another, but now I want to get other who work with me to pick up Python. All newbies to Python have trouble with the idea of whitespace sensitivity, but how can I convince them that "it just works better" when I have this construct which I want to use but can't. Has anybody found a way to emulate this behavior? I've often done it by opening an expression for the whole thing, but there's a lot of tasks where a single expression just isn't sufficient (such as things with assignment). PS. In my opinion the solution would be to have the option of entering a "whitespace insensitive" mode which uses C style {} and ;. The token to enter it could be as complicated as you want (in fact, it may make sense to make it complicated to discourage use unless it's really advantageous). I'd sugest {{ and }} or something bigger like {={ } =}. Only two problems: 1) I'm sure it would offend Guido's sense of language aesthetics 2) I'm sure the idea has been hashed over on this newsgroup to death... hence prefering a workaround instead. You could use the "with" statement: class xml_element(object): def __init__(self, text): self.text = text def __enter__(self): xmlWriter.BeginElement(self.text) def __exit__(self, *args): xmlWriter.EndElement() with xml_element("parent"): with xml_element("child"): xmlWriter.Characters("subtext") -- http://mail.python.org/mailman/listinfo/python-list
regex problem ..
Hi All: I am new to regular expressions in general, and not just re in python. So, apologies if you find my question stupid :) I need some help with forming a regex. Here is my scenario ... I have strings coming in from a list, each of which I want to check against a regular expression and see whether or not it "qualifies". By that I mean I have a certain set of characters that are permissible and if the string has characters which are not permissible, I need to flag that string ... here is a snip ... flagged = list() strs = ['HELLO', 'Hi%20There', '123...@#@'] p = re.compile(r"""[^a-zA-Z0-9]""", re.UNICODE) for s in strs: if len(p.findall(s)) > 0: flagged.append(s) print flagged my question is ... if I wanted to allow '%20' but not '%', how would my current regex (r"""[^a-zA-Z0-9]""") be modified? TIA, AK -- http://mail.python.org/mailman/listinfo/python-list
Re: Limit traceback from most recent call
On Dec 14, 8:07 pm, Brian Allen Vanderburg II wrote: > I've looked at traceback module but I can't find how to limit traceback > from the most recent call if it is possible. I see that extract_tb has > a limit parameter, but it limits from the start and not the end. > Currently I've made my own traceback code to do this but wonder if > python already has a way to do this build in: > > def format_partial_exc(limit=None): > > (type, value, tb) = sys.exc_info() > > items = traceback.extract_tb(tb) > > if limit: > > items = items[-limit:] # Get last 'limit' items and not first > > result = 'Traceback (most recent call last):\n' > > items = traceback.format_list(items) > > for i in items: > > result += i # Newline already included > > result += type.__name__ + ': ' + str(value) > > return result > > Is this possible currently from traceback or other python module? > > Brian A. Vanderburg II Hi, The interface of extract_tb is: traceback.extract_tb(tb, limit=None) try to play with the 'limit' argument Good luck, Yinon -- http://mail.python.org/mailman/listinfo/python-list
Re: Having Issues with CMD and the 'python' command
On Mon, Dec 15, 2008 at 8:13 AM, wrote:
> On Mon, 15 Dec 2008 at 23:01, James Mills wrote:
>
>> On Mon, Dec 15, 2008 at 10:51 PM, Lamonte Harris
>> wrote:
>>
>>> Every time I start cmd on windows it requires me to "set
>>> path=%path%;C:\python26" why? I'm getting annoyed...
>>>
>>
>> "cmd" has _nothing_ to do with Python.
>>
>>
> (Top posting corrected.)
>
> But the answer is that you need to update your PATH string at the system
> level. You do that in Control Panel/System/Advanced/Environment variables
> (it's a button on the advanced screen, which is something that confused
> me the first time I went looking for it).
>
> ObPython: you know, it occurs to me that Windows follows exactly the
> opposite philosophy from Python when it comes to hierarchy. Python's
> Zen is "shallow is better than deep", whereas Windows' philosophy
> is "deep is better than shallow". Every release of Windows seems
> to bury the things one needs to do to administer the system deeper
> and deeper inside a nested set of windows...and every time I touch
> Windows I am reminded how sensible the Python Zen is :)
>
It's not a question of sensibility. It's a question of purpose. The Zen is
the philosophy of a language that tries to be easy to learn and easy to use.
Python is used by programmers who want to experiment with it, but who
usually know enough not to os.system("rm -r /") or anything similar.
Windows, on the other hand, wants to hide everything that can potentially
ruin the system as deep as possible so that many of the idiots who use that
system don't do stupid things like delete the registry, wipe the environment
settings, turn off the "Nag Screen" (UAC), and other things of that nature.
> --RDM
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: %s place holder does not let me insert ' in an sql query with python.
hello all,
thanks for all of your very quick responses.
The problem is that I am using python 2.5 so the 2.6 syntax does not
apply in my case.
secondly, My problem is very unique.
I have created a function called executeProcedure in python which calls
stored procedures in postgresql.
The fun part of this function is that it has just got 3 standard
parameters namely the name of the sp to be called, whether it returns 1
or more records as a result and the list containing the input parameters
which that sp will need for execution.
So no matter what your sp does as in insert update delete or select, no
matter there is one param or 10 all you have to do is pass one string
containing the function name, one boolean and one list of params.
The rest is taken care by this python function.
So now all hackers will understand that the query to call the stored
procedure namely cursor.execute(select * from functname ) will be built
dynamically.
So now in this situation I have to build the querystring and then pass
it to execute of the cursor.
in this case, I get a problem when there is ' in any of the values
during insert or update.
If any one wants this code, Please let me know. You all can get a lot
of utility out of the function.
This only becomes a problem when an ' comes in the value.
So I need help to fix the problem with the given context.
happy hacking.
Krishnakant.
On Mon, 2008-12-15 at 07:21 -0600, Lamonte Harris wrote:
> sorry about that
>
> queryString = "insert into venders
> values('{0}','{1}','{2}')".format(field1,field2,field3)
>
> On Mon, Dec 15, 2008 at 7:21 AM, Lamonte Harris
> wrote:
> I had this problem too. If you've upgraded to python 2.6 you
> need to use the new sytnax "format
>
> queryString = "insert into venders
> values('{0}','{1}','{2}'".format(field1,field2,field3)
>
>
>
> On Mon, Dec 15, 2008 at 6:46 AM, Krishnakant
> wrote:
> hello all hackers.
> This is some kind of an interesting situation although
> many of you must
> have already gone through it.
> I am facing a situation where I have to use psycopg2
> and insert rows in
> a postgresql table.
> That's pritty easy and no need to say that it works
> well. But there are
> some entries which have an ' in the value.
> I have a venders table in my database and one of the
> values tryed was
> "His Master's Voice "
> now the master's word has the ' which is used for
> starting and ending a
> varchar value for postgresql or almost any standard
> RDBMS.
> Does any one know what is the way out of this?
> how do you let the ' go as a part of the string?
> I have used %s as placeholder as in
> queryString = "insert into venders values ('%s,%s,%s"
> %
> (field1,field2,field3 ) ...
> This is not working for the ' values.
> can any one suggest a suitable solution?
> happy hacking.
> Krishnakant.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: regex problem ..
Analog Kid wrote: > Hi All: > I am new to regular expressions in general, and not just re in python. > So, apologies if you find my question stupid :) I need some help with > forming a regex. Here is my scenario ... > I have strings coming in from a list, each of which I want to check > against a regular expression and see whether or not it "qualifies". By > that I mean I have a certain set of characters that are permissible and > if the string has characters which are not permissible, I need to flag > that string ... here is a snip ... > > flagged = list() > strs = ['HELLO', 'Hi%20There', '123...@#@'] > p = re.compile(r"""[^a-zA-Z0-9]""", re.UNICODE) > for s in strs: > if len(p.findall(s)) > 0: > flagged.append(s) > > print flagged > > my question is ... if I wanted to allow '%20' but not '%', how would my > current regex (r"""[^a-zA-Z0-9]""") be modified? > The essence of the approach is to observe that each element is a sequence of zero or more "character", where character is "either letter/digit or escape." So you would use a pattern like "([a-zA-Z0-9]|%[0-9a-f][0-9a-f])+" regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: %s place holder does not let me insert ' in an sql query with python.
Lamonte Harris wrote:
> I had this problem too. If you've upgraded to python 2.6 you need to
> use the new sytnax "format
>
> queryString = "insert into venders
> values('{0}','{1}','{2}'".format(field1,field2,field3)
>
Will all readers of this thread kindly regard this as an example of how
*not* to generate and execute SQL queries in Python. Study the
cursor.execute() method, and provide parameterized queries and a data
tuple instead.
Please also note that the above technique explicitly continues to
generate SQL syntax errors in Krishnakan's case where the data values
themselves contain apostrophes.
regards
Steve
--
Steve Holden+1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: Structure using whitespace vs logical whitespace
On 15 Gru, 18:14, MRAB wrote: > [email protected] wrote: > > I've been trying to search through the years of Python talk to find an > > answer to this, but my Googlefu is weak. > > > In most languages, I'll do something like this > > > xmlWriter.BeginElement("parent"); > > xmlWriter.BeginElement("child"); > > --xml.Writer.Characters("subtext"); > > xmlWriter.EndElement(); > > xmlWriter.EndElement(); > > > Where the dashes are indentation (since some newsgroup handlers don't > > do tabs well). XML writing is just an example. > > > In general, I'm using indentation to show logical flow through code. > > Python's choice to give semantic meaning to whitespace prevents me > > from doing such things. What was once reserved for logical use is now > > used syntactically. In 90% of cases, its not needed, and whitespace > > significance seems to be pretty effective. In that last 10%, however, > > I've been frustrated many times. > > > I've been using python for a few years, and gotten around this in one > > way or another, but now I want to get other who work with me to pick > > up Python. All newbies to Python have trouble with the idea of > > whitespace sensitivity, but how can I convince them that "it just > > works better" when I have this construct which I want to use but > > can't. > > > Has anybody found a way to emulate this behavior? I've often done it > > by opening an expression for the whole thing, but there's a lot of > > tasks where a single expression just isn't sufficient (such as things > > with assignment). > > > PS. In my opinion the solution would be to have the option of entering > > a "whitespace insensitive" mode which uses C style {} and ;. The > > token to enter it could be as complicated as you want (in fact, it may > > make sense to make it complicated to discourage use unless it's really > > advantageous). I'd sugest {{ and }} or something bigger like {={ } > > =}. Only two problems: 1) I'm sure it would offend Guido's sense of > > language aesthetics 2) I'm sure the idea has been hashed over on this > > newsgroup to death... hence prefering a workaround instead. > > You could use the "with" statement: > > class xml_element(object): > def __init__(self, text): > self.text = text > def __enter__(self): > xmlWriter.BeginElement(self.text) > def __exit__(self, *args): > xmlWriter.EndElement() > > with xml_element("parent"): > with xml_element("child"): > xmlWriter.Characters("subtext") Yep, I think that's what Guido was thinking about while adding `with` statements. They're great at grouping code logically. Before I used `if True:` to do this but it wasn't good looking. -- http://mail.python.org/mailman/listinfo/python-list
Wing IDE 3.1.6 released
Hi, Wingware has released version 3.1.6 of Wing IDE, a bugfix release for all three product levels of Wing IDE. *Release Highlights* This release includes the following: * Added previously missing support for x64 Python on Windows * Avoid auto-starting batch searches when a project is opened * Several vi mode fixes * Added 'watch' item to editor context menu * Recognize type of 'x' in 'from x import y' * Allow debugger to start even if replacing sys.stdin fails * Store list of test files in shared project file (*.wpr) * About 16 other bug fixes: see the change log for details: http://wingware.com/pub/wingide/3.1.6/CHANGELOG.txt *Downloads* Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial license can be obtained directly from the product when launched. Wing IDE Pro 3.1.6http://wingware.com/downloads/wingide/3.1 Wing IDE Personal 3.1.6 http://wingware.com/downloads/wingide-personal/3.1 Wing IDE 101 3.1.6http://wingware.com/downloads/wingide-101/3.1 *About Wing IDE* Wing IDE is an integrated development environment for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching entry level programming courses with Python. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE 3.1 supports Python versions 2.0.x through 2.5.x. *New Features in Wing 3.1* This release adds the following features not found in Wing 3.0.x: * Support for zip archives * Support for pkg_resources name spaces and eggs * Support for doctest and nose style unit tests (*) * Scan for sys.path changes such as those used in buildout * How-To and support for Google App Engine * Inline context appropriate templates/snippets integrated with autocompleter (*) * Word list driven auto-completion in non-Python files (**) * Quick navigation to files and symbols by typing a fragment (**) * Improved support for Stackless Python * Preference to strip trailing white space on save * Display gi_running and gi_frame for generators * Improved code analysis for Python 2.5 * Other minor features and bug fixes not found in Wing 3.0.x (*)'d items are available in Wing IDE Professional only. (**)'d items are available in Wing IDE Personal or Professional only. Please see the change log for a detailed list of changes: http://wingware.com/pub/wingide/3.1.6/CHANGELOG.txt *Purchasing and Upgrading* Wing 3.1 is a free upgrade for all Wing IDE 3.0 and 3.1 users. Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. Upgrade a 2.x license: https://wingware.com/store/upgrade Purchase a 3.x license:https://wingware.com/store/purchase -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com -- http://mail.python.org/mailman/listinfo/python-list
Re: %s place holder does not let me insert ' in an sql query with python.
Hi steve.
you are right.
Thanks for all you who helped to understand how to and *not* to pass
queries through psycopg2 which is a module based on python dbapi.
the following query worked.
cursor.execute("insert into vendors values(%s,%s)", lstParams)
lstParams contained all the values and yes one had an ' in it.
thanks again for all the help.
happy hacking.
Krishnakant.
On Mon, 2008-12-15 at 12:35 -0500, Steve Holden wrote:
> Lamonte Harris wrote:
> > I had this problem too. If you've upgraded to python 2.6 you need to
> > use the new sytnax "format
> >
> > queryString = "insert into venders
> > values('{0}','{1}','{2}'".format(field1,field2,field3)
> >
> Will all readers of this thread kindly regard this as an example of how
> *not* to generate and execute SQL queries in Python. Study the
> cursor.execute() method, and provide parameterized queries and a data
> tuple instead.
>
> Please also note that the above technique explicitly continues to
> generate SQL syntax errors in Krishnakan's case where the data values
> themselves contain apostrophes.
>
> regards
> Steve
--
http://mail.python.org/mailman/listinfo/python-list
pexpect and inconsistent exit values
I don't seem to be able to figure out how to get the exit values of commands executed with pexpect reliably. Here's first with regular shell: hei...@ubuntu:~$ true; echo $? 0 Let's try with pexpect. Below is the program: ---CLIP--- import sys, pexpect cmd = "true" print 'cmd=', cmd child = pexpect.spawn(cmd, logfile=sys.stdout) child.close() print 'child exitstatus=', child.exitstatus print 'child signalstatus=', child.signalstatus print 'child status=', child.status ---CLIP--- The output: (fabexp)hei...@ubuntu:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= 1 child signalstatus= None child status= 256 (fabexp)hei...@ubuntu:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= 0 child signalstatus= None child status= 0 (fabexp)hei...@ubuntu:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= None child signalstatus= 1 child status= 1 I have tried various other commands, and I just can't seem to be able to get reliable exit codes from commands I execute. Any ideas what is going on? -- Heikki Toivonen - http://heikkitoivonen.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Structure using whitespace vs logical whitespace
[email protected] wrote: I've been trying to search through the years of Python talk to find an answer to this, but my Googlefu is weak. In most languages, I'll do something like this xmlWriter.BeginElement("parent"); xmlWriter.BeginElement("child"); --xml.Writer.Characters("subtext"); xmlWriter.EndElement(); xmlWriter.EndElement(); Where the dashes are indentation (since some newsgroup handlers don't do tabs well). XML writing is just an example. In general, I'm using indentation to show logical flow through code. That, of course, is what Python does. Python's choice to give semantic meaning to whitespace prevents me from doing such things. You, of course, also want to giving semantic meaning to whitespace, but one that happens to be different from Python's. 'Logical control flow' versus 'output text structure'. > What was once reserved for logical use is now used syntactically. False opposition. In 90% of cases, its not needed, and whitespace significance seems to be pretty effective. In that last 10%, however, I've been frustrated many times. I've been using python for a few years, and gotten around this in one way or another, but now I want to get other who work with me to pick up Python. All newbies to Python have trouble with the idea of whitespace sensitivity, Absolutely not true. Python's indentation is +/- the same as what people routinely (but usually optionally) do when writing other algorithmic languages, including most pseudocode. It also mimics standard outline mode and other structured text (as you with to do). I choose Python in part *because* it has a standard mandated indentation scheme versus the multiple optional schemes of C programmers. Enough of the endless C whitespace wars. I strongly suggest that you not project *your* troubles onto others. Let them come upon it by themselves -- or not. but how can I convince them that "it just works better" The tradeoff is between personal flexibility (a loss to you) and uniformity across programs (you can read *any* Python program and understand the meaning of the indentation). Someone who does not see the latter as a gain perhaps should not use Python. > when I have this construct which I want to use but can't. Yet Has anybody found a way to emulate this behavior? New question: this answer has perhaps been posted before. For your example, write a context manager 'Element' (possible in 2.5+, but I use 3.0). class Element(): def __init__(self, item): self.item = item def __enter__(self): print('' % self.item) def __exit__(self, t,v,tb): print('') # Then with Element('parent'): with Element('child'): print("subtext") # prints subtext Of course, the element class(es) could be in a module with global indent and delta, methods that add and subtract the delta as appropriate, and a print function that prepends the current indent to get something like subtext To me, this Python-style construct is better. You get the Element closure written 'for free'. Less need to match indent levels, no possibility of forgetting closures. If there are multiple container elements with different closures, you get the right one automatically and cannot mismatch. I've often done it by opening an expression for the whole thing, but there's a lot of tasks where a single expression just isn't sufficient (such as things with assignment). I do not understand this without a concrete example. PS. In my opinion the solution would be to have the option of entering a "whitespace insensitive" mode which uses C style {} and ;. I think the above is much better ;-). And yes, such ideas have been discussed and rejected. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help improving number guessing game
Alright! This is feeling more like it.
#!/usr/bin/python
#Py3k, UTF-8
import random
def setup(game, minr=1, maxr=99):
#minr, maxr make minimum and maximum. Can be adjusted.
game['minr'], game['maxr'] = minr, maxr
game['gcount'] = 0 #Reset guess count
game['target'] = random.randint(minr, maxr)
def playerswitch(game):
#Player Switch
#if player's a witch: burn(her)
if game['player'] == game['player1']:
game['player'] = game['player2']
else:
game['player'] = game['player1']
def youwin(game):
if game['pnum'] == 1:
print("CONGRATULATIONS! IT TOOK YOU %s GUESSES" % game
['gcount'])
else:
if game['player'] == game['player1']:
game['p1sc'] += 1
else:
game['p2sc'] += 1
end = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s"
#Can the following line be more compact?
print(end % (game['player'], game['p1sc'], game['p2sc']))
def playagain(game):
playover = input("PLAY AGAIN? Y/N: ")
if playover.strip().lower() == "y":
game['play'] = True
setup(game)
else:
print("GOOD BYE. PLAY AGAIN SOON!")
game['play'] = False
def autofinish(game):
if game['maxr'] - game['minr'] == 2:
print("...ONLY ONE OPTION LEFT!")
youwin(game)
playagain(game)
def numplayers(game, prompt="1 OR 2 PLAYERS?\n> "):
while True:
num = input(prompt)
try:
num = int(num)
except ValueError:
print("BAD VALUE")
else:
break
game['pnum'] = num
def guesses(game):
game['guess'] = int(input("[%s-%s]%s>> " \
#keeps user aware of who's turn it is, and the range
% (game['minr'], game['maxr'], game['player'])))
def guesscheck(game):
if game['guess'] == game['target']:
if game['pnum'] == 1:
game['gcount'] += 1
youwin(game)
playagain(game)
elif game['guess'] >= game['maxr']:
print("NUMBER MUST BE IN RANGE")
guesses(game)
guesscheck(game)
elif game['guess'] <= game['minr']:
print("NUMBER MUST BE IN RANGE")
guesses(game)
guesscheck(game)
elif game['guess'] > game['target']:
print("TOO HIGH")
if game['pnum'] == 1:
game['gcount'] += 1
game['maxr'] = game['guess']
else:
print("TOO LOW")
if game['pnum'] == 1:
game['gcount'] += 1
game['minr'] = game['guess']
def guessing(game):
guesses(game)
guesscheck(game)
if game['pnum'] == 2:
playerswitch(game)
autofinish(game)
def main(game=None):
if game is None:
game = {}
print("WELCOME TO THE SUPER NUMBER GUESSING GAME!")
numplayers(game)
game['play'] = True
game['player1'], game['player2'] = "P1", "P2"
game['player'] = game['player1'] # P1 goes first
#Scores start at 0
game['p1sc'], game['p2sc'], game['gcount'] = 0, 0, 0
setup(game)
while game['play'] is True:
guessing(game)
if __name__ == "__main__":
main()
first off, I want to thank all of you for your help with this. I
really don't think I could've learned all of this out nearly as
quickly by reading tutorials and documentation, let alone had anything
near the grasp I have on it now. '''This''' is why I like learning by
doing. The only things I still don't really understand are .strip
().lower(), and try/except/else, and I plan on looking them up before
I do anything else. In the past few hours I've gone from not having a
clue what the whole {'fred': 0, 'barney': 0} thing was about to being
able to fully understand what you're talking about, and put it into
practice
2; I feel like this process is going quicker and quicker every time I
refine it. It also feels like it's getting easier to solve various
bugs when I create them they pop up. It might be because I'm
getting into it and having more fun, because the refinements are less
major each time, because they're easier to pick up, or some
combination of all of those. Either way, I feel very excited about it.
3; I found some very helpful gedit plugins. While I was in
preferences, I noticed you can have it highlight the margin; so I set
that to 75 to try to keep from going over the character limit/line
recommendation. Draw Spaces, a plugin, showing spaces is also pretty
helpful. I also found a python auto complete plugin which I haven't
used so far, but which looks very promising, along with a terminal
program (Keeps me from juggling windows, anyway)
4; I readded the counter for one player games. Out of curiosity, what
do you think of:
if game['pnum'] == 1:
game['gcount'] += 1
? I'm not sure whether this is good or bad. On the one hand, it keeps
it from adding to gcount without needing to, on the other hand it
seems like it might be more wasteful to check pnum than to just add to
gcount. It also makes it harder to adjust it to show gcount in two
player mode, if you want to do that
Re: stable algorithm with complexity O(n)
Dan Upton wrote: And if n is small and sparse (ie, k > n) , O(k*n) for radix sort could be worse than O(n^2). You could also ask why people make such a big deal about quicksort over mergesort, since mergesort has a guaranteed O(n log n) time whereas quicksort can be O(n^2) on pathological cases. Python's current list.sort uses mergesort because it better exploits existing structure in a list. I think I remember learning in my algorithms class that for small sorts (n < ~40) , bubblesort can actually be the fastest (or close to the fastest) in terms of wall-clock time because it has a relatively small constant factor in its O(n^2) complexity. It uses binary insert sort for n < 64 (chosen empirically) . That also does O(n logn) comparisons and is only O(n**2) for data movement, which a decent C compiler translates into fast block-move assembly instructions. tjr -- http://mail.python.org/mailman/listinfo/python-list
os.environ.get('SSH_ORIGINAL_COMMAND') returns None
Trying to follow a technique found at bzr I did the following
added to ~/.ssh/authorized_keys the command="my_parder" parameter
which point to a python script file named 'my_parser' and located in /
usr/local/bin (file was chmoded as 777)
in that script file '/usr/local/bin/my_parser' I got the following
lines:
#!/usr/bin/env python
import os
print os.environ.get('SSH_ORIGINAL_COMMAND', None)
When trying to ssh e.g. 'ssh localhost'
I get None on the terminal and then the connection is closed.
I wonder if anyone have done such or alike in the past and can help me
with this.
Is there anything I should do in my python file in order to get that
environment variable?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Rename of .mdb file -- lock
noydb wrote: I have the code below, which unzips a zipfile containing only one file. Once it is unzipped, I want to rename the file based on a user provided name. But I get this (WindowsError: [Error 32] The process cannot access the file because it is being used by another process) error, which does not make sense to me as no other apps are open. Any suggestions? Others have told you the reason you are currently having problems. You should also be aware that Windows can at "random" times be opening the new file in order to either index it or virus scan it, and it may fail to rename during that period. So, a failure should retry in a second a couple of times before giving up. This is my understanding, but someone deeply familiar with Windows internals might reveal that I am operating on older information. --Scott David Daniels [email protected] -- http://mail.python.org/mailman/listinfo/python-list
tricky nested list unpacking problem
Hi, I have lists of the following type: [1,2,3,[5,6]] and I want to produce the following strings from this as '0-1-2-3-5' '0-1-2-3-6' That was easy enough. The problem is that these can be nested. For example: [1,2,3,[5,6],[7,8,9]] which should produce '0-1-2-3-5-7' '0-1-2-3-5-8' '0-1-2-3-5-9' '0-1-2-3-6-7' '0-1-2-3-6-8' '0-1-2-3-6-9' also, [1,2,3,[5,6],7,[9]] should produce '0-1-2-3-5-7-9' '0-1-2-3-6-7-9' obviously, these are nested loops over the lists. The problem is that I don't know ahead of time how many lists there are or how deep they go. In other words, you could have: [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] Any help appreciated. I've really been having trouble with this. I hope that made sense. -- http://mail.python.org/mailman/listinfo/python-list
Re: Rename of .mdb file -- lock
Scott David Daniels wrote: noydb wrote: I have the code below, which unzips a zipfile containing only one file. Once it is unzipped, I want to rename the file based on a user provided name. But I get this (WindowsError: [Error 32] The process cannot access the file because it is being used by another process) error, which does not make sense to me as no other apps are open. Any suggestions? Others have told you the reason you are currently having problems. You should also be aware that Windows can at "random" times be opening the new file in order to either index it or virus scan it, and it may fail to rename during that period. So, a failure should retry in a second a couple of times before giving up. This is my understanding, but someone deeply familiar with Windows internals might reveal that I am operating on older information. It's always a good idea pause and then retry a few times, just in case. Retrying is also a good idea when deleting a file, although in that case you might also want to check whether the file is read-only; if it is, then there's no point in retrying. -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing None objects from a sequence
Steven D'Aprano wrote: On Fri, 12 Dec 2008 19:02:24 -0500, Terry Reedy wrote: ... Tim Chase wrote: If you want to literally remove None objects from a list(or mutable sequence) def deNone(alist): n=len(alist) i=j=0 while i < n: if alist[i] is not None: alist[j] = alist[i] j += 1 i += 1 alist[j:i] = [] Contrast that with the alternative suggested by Tim: def deNone2(alist): alist[:] = [x for x in alist if x is not None] ... Here's another low-level algorithm, the classical delete items in place algorithm. Three lines, one index, lousy O(N**2) performance. def deNone3(alist): for i in xrange(len(alist)-1, -1, -1): if alist[i] is None: del alist[i] Now, let's do a shoot-out. Do they return the same thing? ... [good measurements generally reinforcing Tim's implementation] ... If you want to keep the original's method, but do it in a more Pythonic way, I would suggest: def deNone4(alist): j = 0 for val in alist: if val is not None: alist[j] = val j += 1 del alist[j :] This still loses to Tim's clearer code, but by nowhere near as much. --Scott David Daniels [email protected] -- http://mail.python.org/mailman/listinfo/python-list
Re: alt.possessive.its.has.no.apostrophe
On Dec 15, 1:55 am, Ben Finney wrote: > James Stroud writes: > > Ben Finney wrote: > > > James Stroud writes: > > > >> Yes. I think it was the British who decided that the apostrophe > > >> rule for "it" would be reversed from normal usage relative to > > >> just about every other noun. > > It also seems an indefensible claim to say that anyone “decided” it > would be that way, especially “the British”. > > > > Remember that “it” is a pronoun. I see no reversal: > > > Ok. Pronouns are reversed. > > Or, more generally: Pronouns, which are different in just about every > other way from other nouns, are different in this way also. Is that > about right? No. Most pronouns form their possessives the same way nouns do. E.g.: Someone's hat is over there. One does with one's hand whatever one pleases. Whoever's shoes are downstairs better get them. The computer that's power is still on is wasting energy. The seven personal pronouns and "who" are the only words to form their possessives irregularly. However "it" and "who" *pronounce* their possessives exactly as nouns do. They just spell them differently, for no really good reason. The way I see it, if the rule had been, "Use an apostrophe for any word that forms it's possessive by adding an s or z sound", it would have been less inconsistent. Sadly, that's not the rule. English spelling is the Perl of orthography. Carl Banks (...For that matter, if the rule had been, "Never augment your words spelling with an apostrophe", it would have really simplified things) -- http://mail.python.org/mailman/listinfo/python-list
Problem accessing a web page
Hi all,
My apologises if this is not the appropriate group.
I'd like to access a web site from a python script. That page, in fact,
is a form of main page. With a browser (Firefox, for instance) I can do
it without problem: I open the main web whose url is:
'http://www.mcu.es/webISBN/tituloSimpleFilter.do?cache=init&prev_layout=busquedaisbn&layout=busquedaisbn&language=es'
and then, from the same (or another tab) I open the form (it's a book
database and the ISBN is the relevant parameter) whose url is:
'http://www.mcu.es/webISBN/tituloSimpleDispatch.do?params.forzaQuery=N¶ms.cisbnExt=8484031128&action=Buscar&layout=busquedaisbn'
So I get the information about the book.
But when I try to do the same from the script, I get a time-out
error -without time elapsing at all. This is the piece of the
script relevant for the subject:
#!/usr/bin/python
# coding: latin-1
import os, sys
import types
import time
import string
import fileinput
import re
import urllib
mcup =
urllib.urlopen('http://www.mcu.es/webISBN/tituloSimpleFilter.do?cache=init&prev_layout=busquedaisbn&layout=busquedaisbn&language=es')
# open main url
jonk = mcup.read() # read no matter
mcui =
urllib.urlopen('http://www.mcu.es/webISBN/tituloSimpleDispatch.do?params.forzaQuery=N¶ms.cisbnExt=8484031128&action=Buscar&layout=busquedaisbn')
# open form for isbn
pagllibre = mcui.read() # reads it
print pagllibre # and print it
mcui.close()# close form
mcup.close()# close main page
Thanks in advance, I'd appreciate any help.
Regards,
Antoni Mont
--
http://mail.python.org/mailman/listinfo/python-list
Re: tricky nested list unpacking problem
On Mon, Dec 15, 2008 at 11:06 AM, Reckoner wrote: > Hi, > > I have lists of the following type: > > [1,2,3,[5,6]] > > and I want to produce the following strings from this as > > '0-1-2-3-5' > '0-1-2-3-6' > > That was easy enough. The problem is that these can be nested. For > example: > > [1,2,3,[5,6],[7,8,9]] > > which should produce > > '0-1-2-3-5-7' > '0-1-2-3-5-8' > '0-1-2-3-5-9' > '0-1-2-3-6-7' > '0-1-2-3-6-8' > '0-1-2-3-6-9' > > also, > > [1,2,3,[5,6],7,[9]] > > should produce > > '0-1-2-3-5-7-9' > '0-1-2-3-6-7-9' > > obviously, these are nested loops over the lists. The problem is that > I don't know ahead of time how many lists there are or how deep they > go. In other words, you could have: > > [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] > > Any help appreciated. I've really been having trouble with this. > > I hope that made sense. You just need a recursive list-flattening function. There are many recipes for these. Here's mine: def flatten(lst): if isinstance(lst, list): result = [] for item in lst: result += flatten(item) return result else: return [lst] >>> flattened = flatten([1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]) >>> flattened [1, 2, 3, 5, 6, 10, 11, 7, 9, 1, 2, 3, 4, 5] >>> '-'.join(str(num) for num in flattened) '1-2-3-5-6-10-11-7-9-1-2-3-4-5' Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Simple multithreaded profiler using decorators fails on some built-in methods
Hi all, I have written a simple multithreaded profiler using decorators. Below is how it works: 1) Iterate all modules in sys.modules and iterate each function/ class methods inside them, means all of them including built-in methods. 2) Decorate the methods and functions to a global function. 3) This global function acquires a global lock and updates callCount, timeElapsed values, the list of running threads and the function that the thread is currently executing. 4) We have a result(..) function which acquires the global lock again and iterates the above info with showing it in the console. The problem arises when following happens: - we call result(..) function from Thread 1 - result(..) acquires the global lock to read the information - Then, somehow in the result __repr__() builtin function is being called and as we also have decorated this function, this leads to a deadlock. Above took me 3 hours of debugging effort, and the worse part is __repr__() is NOT being called in the same place always. It is sometimes called in somestring processing in the top of the function sometimes in the below. So, I ended up avoiding __repr__() profiling in the profiler . However, this situation puts me in a position that there may be other built-in calls that may end up with a deadlock. I can afford to avoid profiling of all built-in functions but how to do that? Or is there any idea on this? IMPORTANT: I am not sure, but this problem may be the real cause of why we don't see realtime profile results on cProfile or Profile libraries? All of these profilers are have to be stopped before showing you the results, that way I can avoid the necessity of locking () in the result(..) function. Regards, -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem accessing a web page
On Mon, Dec 15, 2008 at 11:55 AM, Antoni Mont wrote: > Hi all, > > My apologises if this is not the appropriate group. > > I'd like to access a web site from a python script. That page, in fact, > is a form of main page. With a browser (Firefox, for instance) I can do > it without problem: I open the main web whose url is: > > 'http://www.mcu.es/webISBN/tituloSimpleFilter.do?cache=init&prev_layout=busquedaisbn&layout=busquedaisbn&language=es' > > and then, from the same (or another tab) I open the form (it's a book > database and the ISBN is the relevant parameter) whose url is: > > 'http://www.mcu.es/webISBN/tituloSimpleDispatch.do?params.forzaQuery=N¶ms.cisbnExt=8484031128&action=Buscar&layout=busquedaisbn' > > So I get the information about the book. > > But when I try to do the same from the script, I get a time-out > error -without time elapsing at all. This is the piece of the > script relevant for the subject: I'm able to grab the problem webpage via Python just fine, albeit with a bit of a delay. So, don't know what your exact problem is, maybe your connection? If you're trying to programmatically browse the web, you might want to look at mechanize: http://wwwsearch.sourceforge.net/mechanize/ Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: tricky nested list unpacking problem
At 2008-12-15T19:06:16Z, Reckoner writes: > The problem is that I don't know ahead of time how many lists there are or > how deep they go. In other words, you could have: Recursion is your friend. Write a function to unpack one "sublist" and call itself again with the new list. For instance, something like: def unpack(pattern): # Find the first subpattern to replace # [...] results = [] for number in subpattern: results.append(pattern.replace(subpattern, number)) return results Calling unpack([1,2,3,[5,6],[7,8,9]]) would look cause it to call unpack([1,2,3,5,[7,8,9]]) and unpack([1,2,3,6,[7,8,9]]), compile the results, and return them. -- Kirk Strauser The Day Companies -- http://mail.python.org/mailman/listinfo/python-list
Python plugin for Netbeans
Netbeans added a python plugin to its plugin repository. Do you tried it? What do you think about this plugin? -- http://mail.python.org/mailman/listinfo/python-list
Re: Structure using whitespace vs logical whitespace
On Dec 15, 11:10 am, Terry Reedy wrote: > > In general, I'm using indentation to show logical flow through code. > > That, of course, is what Python does. > Python does NOT use indentation to show logical flow. It uses it to show syntactical flow. The XML writer is the perfect example of a case where they are different. In most cases, syntactic flow is close enough to logical flow. There are a few cases where you can 'draw a picture' of the algorithm in code if you are whitespace insensitive. I've not used the "with" keyword before, and it does seem to handle this troublesome case quite well. I learned python before it was around, and never really studied it hard enough. I'll have to investigate what other tricks can be done with it. I'm a big fan of the rule "make the 90% easy and the remaining 10% possible." Whitespace sensitivity makes the 90% easy, and just from the looks of it, the 'with' command and whitespace insensitive expressions give the remaining 10%. And I do like the automated support for "finally" clauses when using 'with' Thanks for the help, everyone! -- http://mail.python.org/mailman/listinfo/python-list
Re: tricky nested list unpacking problem
At 2008-12-15T20:03:14Z, "Chris Rebert" writes: > You just need a recursive list-flattening function. There are many > recipes for these. Here's mine: flattened = flatten([1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]) flattened > [1, 2, 3, 5, 6, 10, 11, 7, 9, 1, 2, 3, 4, 5] '-'.join(str(num) for num in flattened) > '1-2-3-5-6-10-11-7-9-1-2-3-4-5' He doesn't want to flatten them directly. He's using [1,2,3] sort of like a regular expression, so that 1,[2,3],4 means "1,2,4" or "1,3,4", not "1,2,3,4". -- Kirk Strauser The Day Companies -- http://mail.python.org/mailman/listinfo/python-list
Re: Managing timing in Python calls
I believe WxTimerEvent is handled using the event queue, which isn't going to do what you want. An event which goes through the queue does not get processed until you return to the queue. What you want to do is actually a rather difficult task to do generically. Should the task be interrupted immediately? Or is a tiny latency acceptable? Should the function being terminated get to handle its own termination? Or should the termination be forced on it. What sort of overhead is acceptable for this "set_timeout" behavior? I would not be surprised if there isn't a built in solution, because its so hard, but rather built in tools which can be used to do it. If your timeouts are on the order of seconds, you might be able to just check time.time() at the begining, and compare it to the current time later in the function. This could be on the main thread or on a worker thread. If you need better handling, you may want to look at how condition variables and such work. Finally, thread has a function to send a Keyboard Interrupt to the main thread. I believe you could do your work on the main thread, and catch the interrupt. "Background" tasks are not easy to implement in any language (other than perhaps AJAX ;-) ). Remember, Python does not support truly simultaneous threads. It actually does timeslices of about 100 operations. Any solution you choose should work given this information. And as for a "nicer" construct, I personally just learned of how to handle the "with" command. I could see something like class Timeout: def __init__(self, t): self.t = t def __enter__(self): self.start = time.time() def __exit__(self, x, y, z): return None def __nonzero__(self): return time.time() - self.start <= self.t def doSomethingLong(timeout = True): # true guarentees bailout never occurs while timeout: doAnIteration() with Timeout(3) as t: doSomethingLong(t) and have your Timeout class have a flag which it sets when doSomethingLong needs to bail out, using whatever method is "best" for your particular application. This is, of course pseudocode - I've not run it through python msyself. Hopefully any errors are obvious enough that you can work around them. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem accessing a web page
I'm able to grab the problem webpage via Python just fine, albeit with
a bit of a delay. So, don't know what your exact problem is, maybe
your connection?
When you get the second page, are you getting the same content
back that you get if you do a search in your favorite browser?
Using just
content = urllib.urlopen(url2).read()
'Error' in content # True
'Friedrich' in content # False
However, when you browse to the page, those two should be inverted:
'Error' in content # False
'Friedrich' in content # True
I've tried adding in the parameters correctly via post
params = urllib.urlencode([
('params.forzaQuery', 'N'),
...
('layout', 'busquedaisbn'),
])
content = urllib.urlopen(url2, data).read()
However, this too fails because the underlying engine expects a
session ID in the URL. I finally got it to work with the code below:
import urllib
data = [
('params.forzaQuery', 'N'),
('params.cdispo', 'A'),
('params.cisbnExt', '8484031128'),
('params.liConceptosExt[0].texto', ''),
('params.orderByFormId', '1'),
('action', 'Buscar'),
('language', 'es'),
('prev_layout', 'busquedaisbn'),
('layout', 'busquedaisbn'),
]
params = urllib.urlencode(data)
url =
'http://www.mcu.es/webISBN/tituloSimpleDispatch.do;jsessionid=5E8D9A11E4A28BDF0BA6B254D0118262'
fp = urllib.urlopen(url, params)
content = fp.read()
fp.close()
but I had to hard-code the jsessionid parameter in the URL. This
would have to be determined from the initial call & response of
the initial URL (the initial URL returns a element with
the URL to POST to, including this magic jsessionid parameter).
Hope this helps nudge you (the OP) in the right direction to get
what you're looking for.
-tkc
--
http://mail.python.org/mailman/listinfo/python-list
Re: stable algorithm with complexity O(n)
Just because its such an interesting problem, I'll take a stab at it. It can be proven that you cannot sort an arbitrarily large set of numbers, given no extra information, faster than O(n log n). It is provable using information theory. However, if your teacher is giving you evil problems, there's no reason you can't be evil in return: Evil trick 1: Allocate an array of n^2 booleans, initialized to false (This is O(n^2)). Declare this to be "before the sort" Then iterate through the list and set each matching entry in the array to True (This is O(n)). Now you have them "sorted." To get access to the data, you need to iterate across the array O(n^2), but this is "after the sort" Evil trick 2: inserting into a set is O(1), so you could insert n items into a set. This is O(n). Then you can argue that, since the set cares not about order, it is as good as ordered! Evil trick 3: pull up your python debugger, and have your program search for the right answer in your teacher's test library. If done smart, this could even be an O(1) sort O_o (queue Nukees reference: "Welcome to my computer security course. Your grades have already been entered into the school's grading systems as Fs. You have one semester to change that, good luck") ... these are fun =) -- http://mail.python.org/mailman/listinfo/python-list
How can I return a non-zero status result from a python script?
Hi How can I return a non-zero status result from the script? Just do a return 1? at the end? -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help improving number guessing game
I added the ability to select your own range. It takes two new
modules:
def customrange(game, lowunsafe=True):
game['defrang'] = False #Keeps setup from changing range to
defaults
while lowunsafe: #makes sure that the low number is positive
picklow = int(input("PLEASE PICK THE LOW NUMBER: "))
if picklow < 0:
print("LOW NUMBER MUST BE POSTIVE")
else:
lowunsafe = False
pickhigh = int(input("PLEASE PICK THE HIGH NUMBER: "))
if pickhigh - picklow <= 2: #see setup().
print("HIGH MUST BE AT LEAST THREE GREATER THAN LOW")
else:
game['minr'], game['maxr'] = picklow, pickhigh
print("RANGE IS [%s-%s]!" % (game['minr'], game['maxr']))
def wantcustom(game, unsure=True):
#Allows user to decide their own range for guessing.
while unsure:
pickrange = input("WOULD YOU LIKE TO CREATE A CUSTOM RANGE? Y/
N: ")
if pickrange.lower() == "n":
game['minr'], game['maxr'] = 1, 99 #Default range
unsure = False
elif pickrange.lower() == "y":
customrange(game)
unsure = False
else:
print("INVALID INPUT")
A slightly updated setup (it needed it anyway):
def setup(game):
#minr, maxr make minimum and maximum. Can be adjusted.
#Make sure that maxr - minr is at least 3.
#1 or less would be impossible. 2 would only have one guess for
victory
#The first would be unplayable, the second would play itself
if game['maxr'] - game['minr'] <= 2:
raise ValueError("INVALID RANGE!")
game['gcount'] = 0 #Reset guess count
game['target'] = random.randint(game['minr'], game['maxr'])
and putting wantcustom(game) immediately before setup(game) in main().
--
http://mail.python.org/mailman/listinfo/python-list
Re: tricky nested list unpacking problem
Reckoner writes:
> Hi,
>
> I have lists of the following type:
>
> [1,2,3,[5,6]]
>
> and I want to produce the following strings from this as
>
> '0-1-2-3-5'
> '0-1-2-3-6'
>
> That was easy enough. The problem is that these can be nested. For
> example:
>
> [1,2,3,[5,6],[7,8,9]]
>
> which should produce
>
> '0-1-2-3-5-7'
> '0-1-2-3-5-8'
> '0-1-2-3-5-9'
> '0-1-2-3-6-7'
> '0-1-2-3-6-8'
> '0-1-2-3-6-9'
>
> also,
>
> [1,2,3,[5,6],7,[9]]
>
> should produce
>
> '0-1-2-3-5-7-9'
> '0-1-2-3-6-7-9'
>
> obviously, these are nested loops over the lists. The problem is that
> I don't know ahead of time how many lists there are or how deep they
> go. In other words, you could have:
>
> [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]
IMHO the second level of nested lists is unnecessary as the same can be
achieved with just one sublevel of list (unless they are to be
interpreted in a way you have not explained). If you avoid this double
nesting then the 'flatten()' function below is not necessary anymore.
>
> Any help appreciated. I've really been having trouble with this.
>
> I hope that made sense.
Here is a not thought out solution:
def flatten(lst):
for x in lst:
if isinstance(x, list):
for y in flatten(x):
yield y
else:
yield x
def unpack(lst):
stack, strings = [], []
def rec():
i = len(stack)
if i == len(lst):
strings.append('-'.join(map(str, stack)))
elif isinstance(lst[i], list):
for x in flatten(lst[i]):
stack.append(x)
rec()
stack.pop()
else:
stack.append(lst[i])
rec()
rec()
return strings
l1 = [1,2,3,[5,6]]
l2 = [1,2,3,[5,6],[7,8,9]]
l3 = [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]
Then:
>>> unpack(l1)
['1-2-3-5', '1-2-3-6']
>>> unpack(l2)
['1-2-3-5-7', '1-2-3-5-8', '1-2-3-5-9', '1-2-3-6-7', '1-2-3-6-8', '1-2-3-6-9']
>>> unpack(l3)
['1-2-3-5-7-9', '1-2-3-5-7-1', '1-2-3-5-7-2', '1-2-3-5-7-3',
'1-2-3-5-7-4', '1-2-3-5-7-5', '1-2-3-5-6-9', '1-2-3-5-6-1',
'1-2-3-5-6-2', '1-2-3-5-6-3', '1-2-3-5-6-4', '1-2-3-5-6-5',
'1-2-3-5-10-9', '1-2-3-5-10-1', '1-2-3-5-10-2', '1-2-3-5-10-3',
'1-2-3-5-10-4', '1-2-3-5-10-5', '1-2-3-5-11-9', '1-2-3-5-11-1',
'1-2-3-5-11-2', '1-2-3-5-11-3', '1-2-3-5-11-4', '1-2-3-5-11-5']
--
Arnaud
--
http://mail.python.org/mailman/listinfo/python-list
Re: Problem accessing a web page
Tim Chase wrote:
> When you get the second page, are you getting the same content
> back that you get if you do a search in your favorite browser?
>
> Using just
>
>content = urllib.urlopen(url2).read()
>'Error' in content # True
>'Friedrich' in content # False
>
> However, when you browse to the page, those two should be inverted:
>
>'Error' in content # False
>'Friedrich' in content # True
>
> I've tried adding in the parameters correctly via post
>
>params = urllib.urlencode([
> ('params.forzaQuery', 'N'),
> ...
> ('layout', 'busquedaisbn'),
> ])
>content = urllib.urlopen(url2, data).read()
>
> However, this too fails because the underlying engine expects a
> session ID in the URL. I finally got it to work with the code below:
>
>import urllib
>
>data = [
> ('params.forzaQuery', 'N'),
> ('params.cdispo', 'A'),
> ('params.cisbnExt', '8484031128'),
> ('params.liConceptosExt[0].texto', ''),
> ('params.orderByFormId', '1'),
> ('action', 'Buscar'),
> ('language', 'es'),
> ('prev_layout', 'busquedaisbn'),
> ('layout', 'busquedaisbn'),
> ]
>
>params = urllib.urlencode(data)
>
>url =
> 'http://www.mcu.es/webISBN/tituloSimpleDispatch.do;jsessionid=5E8D9A11E4A28BDF0BA6B254D0118262'
>
>fp = urllib.urlopen(url, params)
>content = fp.read()
>fp.close()
>
>
> but I had to hard-code the jsessionid parameter in the URL. This
> would have to be determined from the initial call & response of
> the initial URL (the initial URL returns a element with
> the URL to POST to, including this magic jsessionid parameter).
>
> Hope this helps nudge you (the OP) in the right direction to get
> what you're looking for.
>
> -tkc
>
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
OK, Tim, I think you got the point. The jsessionid change in every
response of the initial URL, so I need to read it and stand with it
during the session. Now I must guess how to do it.
Thank you very much to you and also to Chris.
Kind regards,
Toni
--
http://mail.python.org/mailman/listinfo/python-list
Re: How can I return a non-zero status result from a python script?
On Mon, 15 Dec 2008 13:12:08 -0800, [email protected] wrote: > How can I return a non-zero status result from the script? Just do a > return 1? at the end? ``sys.exit(42)`` Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I return a non-zero status result from a python script?
[email protected] wrote in news:74b53da4-bf07-431b-898b- [email protected] in comp.lang.python: > Hi > > How can I return a non-zero status result from the script? Just do a > return 1? at the end? > >>> import sys >>> help( sys.exit ) Help on built-in function exit in module sys: exit(...) exit([status]) Exit the interpreter by raising SystemExit(status). If the status is omitted or None, it defaults to zero (i.e., success). If the status is numeric, it will be used as the system exit status. If it is another kind of object, it will be printed and the system exit status will be one (i.e., failure). >>> Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Structure using whitespace vs logical whitespace
On Mon, 15 Dec 2008 12:27:12 -0800, [email protected] wrote: > On Dec 15, 11:10 am, Terry Reedy wrote: >> > In general, I'm using indentation to show logical flow through code. >> >> That, of course, is what Python does. >> > Python does NOT use indentation to show logical flow. It uses it to > show syntactical flow. What the heck is "syntactical flow"? Of course Python uses indentation for logical flow -- the indentation reflects the program logic. > The XML writer is the perfect example of a case where they are > different. No the program flow there is just some linear calls to methods. It's the XML structure that is not reflected by the indentation, the program flow is represented just fine here. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem Python 2.6.1 vs 2.6 & pyWin32
> I am very disappointed. Help me, please. Try installing Python 2.6.1 "for all users". Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Limit traceback from most recent call
[email protected] wrote: On Dec 14, 8:07 pm, Brian Allen Vanderburg II wrote: Hi, The interface of extract_tb is: traceback.extract_tb(tb, limit=None) try to play with the 'limit' argument Good luck, Yinon -- http://mail.python.org/mailman/listinfo/python-list I have, but the limit argument shows the first items and not the last items (where the exception occurred): def a(): b() def b(): c() def c(): d() def d(): open('/path/to/fake/file') try: a(): except: print traceback.format_exc(limit=2) try: a(): except: print format_partial_exc(limit=2) Prints something like this Traceback (most recent call last): File "b.py", line 52, in ? a() File "b.py", line 19, in a b() IOError: [Errno 2] No such file or directory: '/path/to/fake/file' Traceback (most recent call last): File "b.py", line 25, in c d() File "b.py", line 29, in d handle=open('/path/to/fake/file', 'rt') IOError: [Errno 2] No such file or directory: '/path/to/fake/file' The second one (using format_partial_exc) prints the last two items of the traceback instead of the first, showing the error is line 29 in function d, the first one limits the traceback but gives no indication of where the error occurred. Brian A. Vanderburg II -- http://mail.python.org/mailman/listinfo/python-list
