From fuzzyman at gmail.com Tue Feb 7 11:43:38 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 7 Feb 2006 08:43:38 -0800 Subject: Detecting line endings In-Reply-To: <1hadpni.1ne1raq17jjbyaN%aleaxit@yahoo.com> References: <1139236514.022464.319970@g14g2000cwa.googlegroups.com> <1hacujo.1p81efw1ej38ioN%aleaxit@yahoo.com> <1139304588.446722.255240@o13g2000cwo.googlegroups.com> <1hadpni.1ne1raq17jjbyaN%aleaxit@yahoo.com> Message-ID: <1139330618.241072.31770@g43g2000cwa.googlegroups.com> Alex Martelli wrote: > Fuzzyman wrote: > ... > > > Open the file with 'rU' mode, and check the file object's newline > > > attribute. > > > > Do you know if this works for multi-byte encodings ? Do files have > > You mean when you open them with the codecs module? > No, if I open a UTF16 encoded file in universal mode - will it still have the correct lineending attribute ? I can't open with a codec unless an encoding is explicitly supplied. I still want to detect UTF16 even if the encoding isn't specified. As I said, I ought to test this... Without metadata I wonder how Python determines it ? All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > > metadata associated with them showing the line-ending in use ? > > Not in the filesystems I'm familiar with (they did use to, in > filesystems used on VMS and other ancient OSs, but that was a very long > time ago). > > > Alex From hancock at anansispaceworks.com Fri Feb 10 08:39:57 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 10 Feb 2006 07:39:57 -0600 Subject: apostrophe or double quote? In-Reply-To: <0hu*B7S+q@news.chiark.greenend.org.uk> References: <1139370460.360400.232500@z14g2000cwz.googlegroups.com> <1139413150.237052.47320@o13g2000cwo.googlegroups.com> <17386.12524.935119.641171@montanaro.dyndns.org> <0hu*B7S+q@news.chiark.greenend.org.uk> Message-ID: <20060210073957.4cfaa674@samwise.anansi> On 09 Feb 2006 12:54:04 +0000 (GMT) Sion Arrowsmith wrote: > Terry Hancock wrote: > >skip at pobox.com wrote: > >> Just to present a complete picture, not mentioned in > >this > thread are triple-quoted strings: > >> [ ... ] > >Also in the mode of beating a dead horse ... ;-) > > > >Some people prefer to use single quotes for 'labels' > >(i.e. a name which is meaningful to the program, but not > >to the user), and reserve either double-quotes or > >triple-double-quotes for text to be shown to the user. > > [ ... ] > > Hmm, I made both these points a couple of posts upthread, > but it didn't appear to get through the news->mail > gateway. Ah well, it all came up on the list about a month or two ago anyway (I guess. I don't know, maybe it was a year ago), so I'm just repeating it. -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From cfbolz at gmx.de Wed Feb 22 05:04:49 2006 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Wed, 22 Feb 2006 11:04:49 +0100 Subject: May i customize basic operator (such as 1==3)? In-Reply-To: References: Message-ID: kanchy kang wrote: > many people write test cases with python scripts. > in these test scripts, there are many validation statements, > for example, in unittest, failUnless(a == b),(a/b may be stringType or > intType...) > > during running test scripts, if there is one exception raised from > failUnless, i still do not know a =?, b= ?... i have to add one statment > "print a" or "print b" again... > > as i know, there are many validation statements if using python as one > test tool... > i think my suggestion or requirement may benefit users greatly... > you could use the py.test testing framework (http://codespeak.net/py/current/doc/test.html), which tries to print useful information if a test fails. So if your test contains assert a == b and this is False, it will print the values of a and b. For example the test def test_fail(): a = 1 b = 2 assert a == b would result in the following failure: def test_fail(): a = 1 b = 2 E assert a == b > assert 1 == 2 This has the drawback that your expressions need to be side-effect free (because they will be re-evaluated) but it is quite useful. Cheers, Carl Friedrich Bolz From public at priatel.co.uk Fri Feb 3 09:20:43 2006 From: public at priatel.co.uk (Martin Biddiscombe) Date: 3 Feb 2006 06:20:43 -0800 Subject: Regular expression query Message-ID: <1138976443.473320.315170@g44g2000cwa.googlegroups.com> It's probably quite simple, but what I want is a regular expression to parse strings of the form: "parameter=12ab" "parameter=12ab foo bar" "parameter='12ab'" "parameter='12ab' biz boz" "parameter="12ab"" "parameter="12ab" junk" in each case returning 12ab as a match. "parameter" is known and fixed. The parameter value may or may not be enclosed in single or double quotes, and may or may not be the last thing on the line. If the value is quoted, it may contain spaces. I've tried a regex of the form: re.compile(r'parameter=(["\']?(.*?)\1( *|$)') This works fine when the parameter's value is quoted, but if the quotes are missing, it falls over since the \1 is empty and so the non-greedy "match anything" ends up matching nothing. Any suggestions? Thanks From sybrenUSE at YOURthirdtower.com.imagination Thu Feb 2 04:34:51 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 2 Feb 2006 10:34:51 +0100 Subject: redirect and python References: <1138865526.286565.282150@g14g2000cwa.googlegroups.com> Message-ID: questions? enlightened us with: > The things put to screen doesn't redirect to the file I want. What do you see on screen? What do you want to redirect to the file? > What's the trick in here? Giving us useful information. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From rainbow.cougar at gmail.com Tue Feb 14 09:44:02 2006 From: rainbow.cougar at gmail.com (rainbow.cougar at gmail.com) Date: 14 Feb 2006 06:44:02 -0800 Subject: Python 3000 deat !? Is true division ever coming ? References: <1139810036.943598.229030@g47g2000cwa.googlegroups.com> Message-ID: <1139928242.726349.221080@g44g2000cwa.googlegroups.com> seb.haase at gmail.com wrote: > Hi, > Is it true that that "Python 3000" is dead ? > Honestly I think that e.g. changing 5/2 to be 2.5 (instead of 2) would > just break to much code :-( > On the otherhand I'm using Python as "Matlab replacement" and would > generally like 5/2 ==2.5 > >... It's Comp. Sci. 101, based on third grade artithmetic, not Python. 5/2=2 is integer division, that's the way integer arithmetic works. 5./2.=2.5 is floating point math, with all the round off errors that incorporates. If Matlab assumes floating point, then that's what you're paying the big bucks for. Curtis From jack at performancedrivers.com Tue Feb 14 20:51:53 2006 From: jack at performancedrivers.com (Jack Diederich) Date: Tue, 14 Feb 2006 20:51:53 -0500 Subject: Soduku In-Reply-To: <1139967167.960780.171360@o13g2000cwo.googlegroups.com> References: <1139967167.960780.171360@o13g2000cwo.googlegroups.com> Message-ID: <20060215015153.GH6479@performancedrivers.com> On Tue, Feb 14, 2006 at 05:32:48PM -0800, Jonathan Gardner wrote: > Here at my job, Python gets no respect. > > A programmer here wanted to see which language among Python, Perl, and > Java was better. So he wrote a Python, perl, and Java version. Except > the Python version was 20x slower than the perl and Java versions. > > Well, luckily he asked around in our little Python group about what he > did wrong. He simply misindented a block of code, making it run 10x as > often as it needed to. With that one fix, it was running faster than > the Java and perl versions, about 2x as fast. A few other minor tweaks > made it run even faster. > > And we've been playing with different algorithms for soduku solutions. > I had it down to 27 ms to solve the puzzle. > A nice story to hear, did you measure how long each of the solutions took you to write (even if it was just a wrote translation of the same strategy)? Is my math off or does 27ms mean 0.027 seconds? On my laptop (1.3GHz) an empty python program takes 10ms to run (0.010 secs). I ask out of vanity, my own solver takes .15 seconds to run (20 seconds for a 16x16 grid). -jackdied From Gr.Dada at lycos.de Mon Feb 13 14:38:09 2006 From: Gr.Dada at lycos.de (Dada) Date: 13 Feb 2006 11:38:09 -0800 Subject: winfo_exists Message-ID: <1139859489.328195.122830@g44g2000cwa.googlegroups.com> I want to know, whether a window is already open or not. Following a peace of the code. ----- ... class Auswahlmenue: def __init__(AM): AM.Fenster = Toplevel() ... AM.Fenster.destroy(); Startsortierung() #------------------------- class Startsortierung: def __init__(SS): #------------------------- def Abbruch(xxx): SS.Fenster_2.destroy() #!! Abfragen, ob bereits ein Auswahlmen? ge?ffnet ist! if not Auswahlmenue.Fenster.winfo_exists(): Auswahlmenue() #------------------------- def Auswahl(xxx): Auswahlmenue() #------------------------- def weiter(xxx): SS.Fenster_2.destroy() #------------------------- SS.Fenster_2 = Toplevel() Label(SS.Fenster_2, text= u'... ...').pack() SF = Button(SS.Fenster_2, text= u'abbrechen', underline= 0) SF.pack(side= u'left') SS.Fenster_2.bind(sequence= '', func= Abbruch) SF = Button(SS.Fenster_2, text= u'Auswahlmen?', underline= 0) SF.pack(side= u'left') SS.Fenster_2.bind(sequence= '', func= Auswahl) SF = Button(SS.Fenster_2, text= u'weiter', underline= 0) SF.pack(side= u'right') SS.Fenster_2.bind(sequence= '', func= weiter) TkFenster.wait_window(SS.Fenster_2) ---- The main programm calls the class Auswahlmenue. In this class the user can choose Startsortierung. In this class the user may (after a prozess) go back to Auswahlmenue without destroying the Startsortierung-window (SS.Fenster_2), because he needs the information shown there. Or he may go back immeaditely to Auswahlmenue via Abbruch (destroying SS.Fenster_2 and opening AM.Fenster). In the first way the user later will close the SS.Fenster_2-window - but how do I get the information, the AM.Fenster is already open or not? I do not want have two AM.Fenster open. I hoped toget this via winfo_exists, but there?s a mistake in the if-row. Indeed I could do it with a global flag, but is there a possibility to do it with winfo_exists()? Thanks for help Dada From kent at kentsjohnson.com Mon Feb 13 15:51:29 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 13 Feb 2006 15:51:29 -0500 Subject: Jython inherit from Java class In-Reply-To: <1139858468.679378.103640@g43g2000cwa.googlegroups.com> References: <1139344211.725580.263660@g47g2000cwa.googlegroups.com> <43eab05b_2@newspeer2.tds.net> <1139594138.216488.12730@g14g2000cwa.googlegroups.com> <43ede2b8$1_1@newspeer2.tds.net> <1139858468.679378.103640@g43g2000cwa.googlegroups.com> Message-ID: <43f0ecfc$1_2@newspeer2.tds.net> Mark Fink wrote: > Hi Kent, > many thanks for your help! In the meantime I received my "Jython > Essentials" book and hope that I have much fewer questions in the near > future. > One last question for this thread. I tried to inherit from a Java class > and override on method. I figured that this approach was nonsense > because the method used private attributes of the Java class. Now I > read that there is injection used in Jython. Jython uses setter and > getter methods to do the injection, right? Unfortunately the Java class > has no setters and getters for the private members. Is there another > way to override the method besides rewriting the Java class or is this > approach really doomed? I don't know what you mean by injection in this context. But Jython has a property "python.security.respectJavaAccessibility" which may help - if you set it to false (on the command line or the Jython registry (see the docs)) then Jython code can access private members of Java objects. It seems a bit of a hack but it might help you out. Changing the Java class to make the private members be protected seems like a better fix if you can do it. Kent From wegwerp at gmail.com Wed Feb 15 05:03:56 2006 From: wegwerp at gmail.com (Bas) Date: 15 Feb 2006 02:03:56 -0800 Subject: a numarray question In-Reply-To: <1139995325.462403.126420@z14g2000cwz.googlegroups.com> References: <1139995325.462403.126420@z14g2000cwz.googlegroups.com> Message-ID: <1139997836.535385.160000@f14g2000cwb.googlegroups.com> I believe it is something like a[a==0] = 5 Note that numarray will eventually be replaced by Scipy/Numpy at some time, but this wouldn't change the basic stuff. Cheers, Bas From strombrg at dcs.nac.uci.edu Thu Feb 16 23:12:40 2006 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Fri, 17 Feb 2006 04:12:40 GMT Subject: Databases and python References: <1140075451.474898.106320@g43g2000cwa.googlegroups.com> Message-ID: On Wed, 15 Feb 2006 23:37:31 -0800, Jonathan Gardner wrote: > I'm no expert in BDBs, but I have spent a fair amount of time working > with PostgreSQL and Oracle. It sounds like you need to put some > optimization into your algorithm and data representation. > > I would do pretty much like you are doing, except I would only have the > following relations: > > - word to word ID > - filename to filename ID > - word ID to filename ID I think I could ditch the "word ID to word" table, but I think I'll probably eventually need the "filename ID to filename" table, so when I pull a list of filename ID's by word I can get back the filenames. > You're going to want an index on pretty much every column in this > database. That's because you're going to lookup by any one of these > columns for the corresponding value. I do need some pretty heavy indexing. In fact, so far everything seems to be clicking along pretty well, except the part that I'm having trouble indexing - the per-word list of filenames. And that's because I already have one relation (word number -> filenames' numbers) that's complicating getting another relation for the list of filenames (just filename ID to '', but it'd be soooo much faster if I could nest the relations somehow). > I said I wasn't an expert in BDBs. But I do have some experience > building up large databases. In the first stage, you just accumulate the > data. Then you build the indexes only as you need them. Let's say you > are scanning your files. You won't need an index on the filename-to-ID > table. That's because you are just putting data in there. The word-to-ID > table needs an index on the word, but not ID (you're not looking up by > ID yet.) And the word ID-to-filename ID table doesn't need any indexes > yet either. So build up the data without the indexes. Once your scan is > complete, then build up the indexes you'll need for regular operation. > You can probably incrementally add data as you go. Interesting thought! I think I need to ponder this a bit more. I think the filename <-> filename number tables are pretty inexpensive, and the word <-> word number tables seem pretty inexpensive too. I think it's primarily the word number to filename numbers table that's messing up the performance really bad, and that's probably because the list of filename numbers is growing so large in some cases, and adding a filename to a word tends to be O(n), n==the number of filenames already on the word. May I ask: In what representation would you keep this word number to filename numbers relation stashed away until later, to build your indexes from more rapidly in a later pass? Are you thinking to keep them all in memory, or store them in a flat file somehow? > As far as filename ID and word IDs go, just use a counter to generate > the next number. If you use base255 as the number, you're really not > going to save much space. That's basically what I'm doing - incrementing a counter for each word, except I'm converting that counter to base255. The base255 representation of that counter brings the following benefits: 1) Converting a set of numbers to a string, without losing number boundaries, becomes just mapping them to base255, and string.joinfields'ing them. 2) Converting a string to a set of numbers, again without losing number boundaries, is just string.splitfields'ing them, and mapping them from base255 back to a list or set of numbers. 3) The numbers can be arbitrarily large, unlike with a, say, 4 or 8 byte fixed-length record representation > And your idea of hundreds of thousands of tables? Very bad. Don't do it. Sigh. I was afraid of that. :-S I'm thinking though... what if I were to use the current representation for words that don't appear in that many files, and a table for each word that has >= 1000 (or whatever threshold) filenames associated with it...? That should greatly cut down on the number of tables, while still giving the more efficient representation for the words that need it. Or not? From codecraig at gmail.com Wed Feb 15 08:45:37 2006 From: codecraig at gmail.com (abcd) Date: 15 Feb 2006 05:45:37 -0800 Subject: Win32_Process.Create -- not starting process In-Reply-To: References: Message-ID: <1140011137.470140.319140@g43g2000cwa.googlegroups.com> Tim, Ok, well I verified that my python script and batch script are working properly. In fact, if I double click on the batch script (when its on Computer B), it starts the python script and the script runs fine with no problem. However when I try to execute the batch script from computer A using WMI it doesnt start. I say that because the python script that gets executed writes a status message to a file, and that does not occur as well as Python.exe does not show up in the task manager, even though Win32_Process.Create returns a PID and a 0 for the return code. So, if I try the same process a second time...it works. python.exe is running, status message is written to a file, etc. Is there some sort of initialization that needs to be done? Thanks From dananrg at yahoo.com Fri Feb 24 17:02:41 2006 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: 24 Feb 2006 14:02:41 -0800 Subject: Best python module for Oracle, but portable to other RDBMSes Message-ID: <1140818561.458171.237850@p10g2000cwp.googlegroups.com> I'm a little confused about what's out there for database modules at: http://python.org/topics/database/modules.html What I'd like to do is use Python to access an Oracle 9.X database for exporting a series of tables into one aggregated table as a text file, for import into a mainframe database. The catch is that I'd like to write code that wouldn't need to be changed (much) if we switched from Oracle to some other RDBMS (still need to export out as a text file for import to the mainframe database. Looks like I'd probably want to use something that conforms to the DB-API 2.0. On the module list, I see DCOracle2, but it hasn't been updated since 2001. Anyone here use this module, and does it work with both Oracle 9.2 and Oracle 10g? Are there other DB-API 2.0 compliant modules I should be looking at? What are the advantages and disadvantages of the ones that can access Oracle 9.2 and Oracle 10g databases? Thanks in advance. From grflanagan at yahoo.co.uk Fri Feb 24 11:08:43 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 24 Feb 2006 08:08:43 -0800 Subject: a little more help with python server-side scripting References: <59edncmGm6g2LmbeRVn-pw@rcn.net> <43ff1d75$1_1@newspeer2.tds.net> Message-ID: <1140797323.789782.87250@v46g2000cwv.googlegroups.com> John Salerno wrote: > Kent Johnson wrote: > > John Salerno wrote: > >> Magnus Lycka wrote: > >> > >>> The other option is ASP. You have been given information about > >>> that already. Be aware that ASP does not imply VBScript. You can > >>> use Python in ASP as long as that's enabled. It seems to be exactly > >>> what you are asking for, so I don't understand why you seem to reject > >>> it. Don't you like the file name endings? > >> > >> > >> Maybe I'm misunderstanding what is meant when you say to use ASP. I'm > >> thinking that it involves having to learn another language (such as C# > >> with ASP.NET), instead of writing my code in Python. Is that not the > >> case? > > > > See http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B276494 > > > > The last example on this page is exactly what you have been asking for. > > > > Kent > > But isn't this code: > > Response.Write('Python Test
') > Response.write('

Smaller heading') > > written using ASP instead of Python? Here's a demo script called 'tut1.asp' located in 'site-packages\win32comext\axscript\Demos\client\asp': ################### and here is 'CreateObject.asp' from the same directory: Gerard From bob.python at yahoo.com Thu Feb 23 15:30:05 2006 From: bob.python at yahoo.com (Bob) Date: 23 Feb 2006 12:30:05 -0800 Subject: How to move optparse from main to function? In-Reply-To: <1140724501.360284.227790@i39g2000cwa.googlegroups.com> References: <1140721179.096585.202560@g14g2000cwa.googlegroups.com> <1140724501.360284.227790@i39g2000cwa.googlegroups.com> Message-ID: <1140726605.085893.256240@z34g2000cwc.googlegroups.com> Yes the documentation is helpful, but I wouldn't have been able to do what you did in your code by just looking at section 6.21.2.9. I thought I could put "parser = parserSetup()" and "(options, args) = parser.parse_args()" in the function. Thanks for helping out with that! From kent at kentsjohnson.com Thu Feb 23 08:09:41 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 23 Feb 2006 08:09:41 -0500 Subject: why don't many test frameworks support file-output? In-Reply-To: References: Message-ID: <43fdaf8f$1_3@newspeer2.tds.net> kanchy kang wrote: > i browsed the following frameworks briefly: nose, OOBTest, > testosterone, py.test, Sancho ... and found out they do support > imediate screen-output only. unittest.TextTestRunner() has an optional stream argument that would let you output to a file. Kent From felipe.lessa at gmail.com Sun Feb 12 00:35:56 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 12 Feb 2006 03:35:56 -0200 Subject: itertools examples In-Reply-To: <1139717775.485803.129820@f14g2000cwb.googlegroups.com> References: <1139717775.485803.129820@f14g2000cwb.googlegroups.com> Message-ID: <1139722556.3978.5.camel@kenshin> Em S?b, 2006-02-11 ?s 20:16 -0800, Raymond Hettinger escreveu: > Both work just fine. It's a personal choice when to use map() and when > to use a list comprehension. Since many itertools have the flavor of > map/filter, its use is not out of place in the itertools docs. I know both work in the same way, but IIRC I heard someone (GvR?) saying list comprehensions should be used when possible to substitute map, filter and/or reduce. > Also, the use of map() provided an opportunity to demonstrate > operator.itemgetter(). While not essential to this example, it is > helpful with several other tools (especially those with a key= > argument). Itertools provide a kind of iterator algebra and > itemgetter() is an essential part of that algebra; hence, it is > appropriate that it be included in itertool examples. > > If your taste says otherwise, that's okay. Program however you want. > If reading the examples helped you understand the toolset, then the > docs accomplished their goal. IMO at a first glance the it's much easier to read and understand the list comprehension, but I have to admit that if I didn't see the operator.itemgetter(1) there I would probably never known it existed. Well, so let's just leave it there, but I'll surely program with the list comprehensions ;-). Thanks for your attention, Felipe. > > Raymond > -- "Quem excele em empregar a for?a militar subjulga os ex?rcitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destr?i os estados dos outros povos sem lutas prolongadas. Deve lutar sob o C?u com o prop?sito primordial da 'preserva??o'. Desse modo suas armas n?o se embotar?o, e os ganhos poder?o ser preservados. Essa ? a estrat?gia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" From lucaberto at libero.it Fri Feb 17 10:20:01 2006 From: lucaberto at libero.it (luca72) Date: 17 Feb 2006 07:20:01 -0800 Subject: Pyserial never read In-Reply-To: <1140140990.492289.185060@g47g2000cwa.googlegroups.com> References: <1140105936.408387.88130@z14g2000cwz.googlegroups.com> <1140140990.492289.185060@g47g2000cwa.googlegroups.com> Message-ID: <1140189601.611469.254940@g44g2000cwa.googlegroups.com> Thanks Luca From steve at holdenweb.com Tue Feb 28 02:06:13 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 28 Feb 2006 02:06:13 -0500 Subject: newbie In-Reply-To: <20060227203553.44475.qmail@web25702.mail.ukl.yahoo.com> References: <20060227203553.44475.qmail@web25702.mail.ukl.yahoo.com> Message-ID: Brain Murphy wrote: [...] > also i have heard that there are no crackers using python why is this?? > Because the Python Secret Underground seeks hackers out and -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From zunbeltz at gmail.com Fri Feb 10 11:27:31 2006 From: zunbeltz at gmail.com (zunbeltz at gmail.com) Date: 10 Feb 2006 08:27:31 -0800 Subject: html entity to unicode Message-ID: <1139588851.594418.301860@g14g2000cwa.googlegroups.com> Hi, I'm parsing html. I have a page with a lot of html enitties for hebrew characters. When i print what i get are blanks, dots and commas. How can i decode this entities to unicode charachters? TIA Zunbeltz From aleaxit at yahoo.com Sun Feb 26 16:42:04 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Feb 2006 13:42:04 -0800 Subject: sort one list using the values from another list References: <1140981038.788111.93500@j33g2000cwa.googlegroups.com> <9bpMf.109707$4l5.58949@dukeread05> Message-ID: <1hbdcma.11xgwfqcbbjjjN%aleaxit@yahoo.com> Ron Adam wrote: > bearophileHUGS at lycos.com wrote: > > Your solution Steven Bethard looks very intelligent, here is a small > > speed test, because sorting a list according another one is a quite > > common operation. > > (Not all solutions are really the same, as Alex has shown). > > Try this one. > > def psort10(s1, s2): > d = dict(zip(s2,s1)) > s1[:] = (d[n] for n in sorted(d.keys())) > > It's faster on my system because d.keys() is already sorted. But that > may not be the case on other versions of python. If there are duplicates in s2, this solution will silently lose some items from s1. I would at least include an assert len(s2)==len(d) as the second statement to get some insurance that this doesn't occur. Alex From grante at visi.com Wed Feb 15 11:13:08 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 15 Feb 2006 16:13:08 -0000 Subject: Best way of finding terminal width/height? References: <96nFf.43896$d5.199922@newsb.telia.net> <11uc3dohfitotc5@corp.supernews.com> <11udc0r2bq11042@corp.supernews.com> <43E719EE.3040401@gmail.com> <11ueq4nhn91qm91@corp.supernews.com> <43E8659D.6010101@gmail.com> <11uhcjj2p10mm0d@corp.supernews.com> <43E8D4DD.7040904@gmail.com> <11uhodjciifej02@corp.supernews.com> <11uk67a4ao5efe6@corp.supernews.com> <11umnq61kf9m5f3@corp.supernews.com> Message-ID: <11v6kokrmpgfecc@corp.supernews.com> On 2006-02-15, Joel Hedlund wrote: >> Sure. I was going to do that yesterday, but I realized that I >> didn't know how/where to do it. I assume there's a link >> somewhere at www.python.org, but I haven't had a chance to look >> yet. > > It's already reported to the bug tracker: > > http://www.python.org/sf/210599 > > Apparently, this has been around since 1.5.2. It's in fact > also in the feature request PEP right now: > > http://www.python.org/peps/pep-0042.html > > and it's listed as a "Big" project under the "Standard > library" heading. I assume we're going to have to live with > this for a while yet... Oh. I've got no complaints about the way things work, I was just going to suggest changing the documentation to correctly describe the way things work. Too mundane a solution? It seems a bit odd that we've known the documentation is wrong for 6 years and nobody's bothered to fix it. Or is the documentation describing how we wish things would work regardless of whether they work that way or not? -- Grant Edwards grante Yow! It's today's SPECIAL! at visi.com From fuzzyman at gmail.com Wed Feb 15 03:51:35 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 15 Feb 2006 00:51:35 -0800 Subject: How to *Search* with google from inside my programme and get the search result? In-Reply-To: References: Message-ID: <1139993495.896341.3160@g47g2000cwa.googlegroups.com> Frank Potter wrote: > I want to search something by a key word from inside my py script. > The using google idea comes to my mind first because write a search > programme from scratch is not so easy. > > I want to take advantage of goolge results, but I don't know how. > To extract the result from html of google can get the result, but it's not > reliable and stable because the html structure my be changed any time. > > Does google supply some webservice to programmers? I did see > some a tool use google to search and use it's result from the programme very > well. Its name is "Email catcher&sender 2.10", which can be download > at http://www.worldminer.com/download.htm. Windows users can take a > look at it. It supports more than google, but yahoo and some other search > engines. How does it do it? I really need some hints. If you'd like a (simple) example of using the google webservice, have a look at googlerank - htpp://www.voidspace.org.uk/python/recipebook.shtml#google In practise I've found the yahoo web services faster, simpler and less restrictive, so you may want to try that. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From rridge at csclub.uwaterloo.ca Fri Feb 10 23:24:34 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 10 Feb 2006 20:24:34 -0800 Subject: Legality of using Fonts References: <1139591308.864757.154740@g44g2000cwa.googlegroups.com> Message-ID: <1139631874.397548.37840@g47g2000cwa.googlegroups.com> Steven D'Aprano wrote: > It is highly unlikely that any judge will be fooled by a mere change in > format ("but Your Honour, I converted the TTF file into a bitmap"). If that were true, almost the entire X11 bitmap font collection would be illegal. Fonts aren't subject copyright, just the hints in most outline fonts, which are considered computer programs. Ross Ridge From orome.the.valar at gmail.com Thu Feb 16 03:18:08 2006 From: orome.the.valar at gmail.com (Sinan Nalkaya) Date: Thu, 16 Feb 2006 02:18:08 -0600 Subject: pop line from file In-Reply-To: <1140037192.930780.218270@g44g2000cwa.googlegroups.com> References: <1140037192.930780.218270@g44g2000cwa.googlegroups.com> Message-ID: <8c05f79c0602160018y792b068dw856a9213f9145fc0@mail.gmail.com> i am unix platform, now searching for the mkfifo topics. thank you all. From dan.gass at gmail.com Sun Feb 19 17:15:08 2006 From: dan.gass at gmail.com (dan.gass at gmail.com) Date: 19 Feb 2006 14:15:08 -0800 Subject: Making mouse wheel work with pmw ScrolledCanvas widget In-Reply-To: <1140287936.010845.68530@g44g2000cwa.googlegroups.com> References: <1140287936.010845.68530@g44g2000cwa.googlegroups.com> Message-ID: <1140387308.397819.267060@f14g2000cwb.googlegroups.com> This looks like it has nothing to do with Pmw (Mega widgets) but is really a basic Tkinter problem. From deets at nospam.web.de Thu Feb 2 14:31:39 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 02 Feb 2006 20:31:39 +0100 Subject: PyQt: QListView how to retrieve selected items? In-Reply-To: <1138907537.417067.228570@z14g2000cwz.googlegroups.com> References: <1138907537.417067.228570@z14g2000cwz.googlegroups.com> Message-ID: <44f50sF1u9c3U1@uni-berlin.de> Flavio schrieb: > Hi, > > I have a QListview widget that allows me to store a bunch of strings in > it. This strings can be visualized, sorted, selected, etc. > > My Problem is that I cant find a way to get the user selected items > back from it! I looked over the Qt documentation many times over but > there is no method to that end. > > Any PyQt guru lurking around? > > should I try some other list widget, that has a "getSelected()"method? > Is there one? QListViewItem.isSelected()? You have to loop over the items to get the ones selected. Additionally, you might want to register for the selectionChanged signal. In Single-selection-mode there even is a overloaded version that directly gives you the selected item. And all of this can be found within 20 seconds in the great Qt-Docs. Especially easy with the included QAssistant, a help-browser with indexing and whatever... Diez From timr at probo.com Tue Feb 21 02:32:06 2006 From: timr at probo.com (Tim Roberts) Date: Tue, 21 Feb 2006 07:32:06 GMT Subject: Multiplication optimization References: <1140310118.365847.111120@g14g2000cwa.googlegroups.com> Message-ID: "Paul McGuire" wrote: > >Does Python's run-time do any optimization of multiplication >operations, like it does for boolean short-cutting? That is, for a >product a*b, is there any shortcutting of (potentially expensive) >multiplication operations as in: Integer multiplication is a 1-cycle operation in Intel processors. Even multiple-precision multiplication is very efficient -- probably more so than multiple comparisons and jumps. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From rridge at csclub.uwaterloo.ca Wed Feb 8 21:17:19 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 8 Feb 2006 18:17:19 -0800 Subject: Replacing curses In-Reply-To: <11ul1mgplrah63e@corp.supernews.com> References: <43E9234B.6030108@v.loewis.de> <11uk55h47lruk18@corp.supernews.com> <11ukf0ci8d6ac64@corp.supernews.com> <11ul1mgplrah63e@corp.supernews.com> Message-ID: <1139451439.115775.223250@g43g2000cwa.googlegroups.com> Thomas Dickey wrote: > ...and send UTF-8 text, keeping track of where you really are on the screen. You make that sound so easy. Ross Ridge From l.exsteens at gmail.com Thu Feb 2 07:39:32 2006 From: l.exsteens at gmail.com (Laurent) Date: 2 Feb 2006 04:39:32 -0800 Subject: my openGL API need threads!!! But how to ,ake it work??? Message-ID: <1138883972.001578.149350@g44g2000cwa.googlegroups.com> Hi, here is the context: I'm coding a openGL API I will need for a project for my school. This API is quite simple: an ooglScene describe all needed to make an openGL, and inherits from a list. So an ooglScene is fundamentaly a list of ooglObjects (which is organised as a Composite Pattern). ooglScene.run() do everthing needed to initialise GL and GLUT, and then launch the GLUT Main Loop. (the display function I wrote juste call the display method of each ooglObject in the ooglScene) Here is the problem! Once the GLUT Main Loop is launched, I cannot add other ooglObjects to my ooglScene, neither modify any existing ooglObject in my scene! exemple that works but is sequential: ------------------------------------------------------ Scene = ooglScene() Scene.append(ooglObject()) Scene.run() What I want to do: --------------------------- Scene = ooglScene() Scene.run() Scene.append(ooglObject()) I don't know the threqding system, I've take a look on that but I don't know how to make what I need: the ooglScene.run() method must create a separate thread to launch the glutMainLoop! Actually I see only one solution: create two threads out of the ooglScene and launch run() in one, and the rest of my program in the other: Thread1.start() --> launch the ooglScene.run() Thread2.start() --> launch the rest of my program... THIS IS NOT ENOUGH TRANSPARENT IN MY POINT OF VIEW!! From grante at visi.com Sat Feb 11 09:07:29 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 11 Feb 2006 14:07:29 -0000 Subject: Shortest prime number program References: <1139652226.869102.310180@g14g2000cwa.googlegroups.com> <1139660566.389036.166090@g14g2000cwa.googlegroups.com> <43EDE17F.7030000@v.loewis.de> <1139664341.587464.78200@g44g2000cwa.googlegroups.com> Message-ID: <11urrt1j14vg0af@corp.supernews.com> On 2006-02-11, swisscheese wrote: >>You can save two bytes with > > 56 - nice catch. > 55: > r=range(2,99) > [x for x in r if sum(x%d<1 for d in r)<2] And if this were FORTRAN: r=range(2,99) [xforxinrifsum(x%d<1fordinr)<2] ;) -- Grant Edwards grante Yow! Hmmm... a CRIPPLED at ACCOUNTANT with a FALAFEL visi.com sandwich is HIT by a TROLLEY-CAR... From skip at pobox.com Tue Feb 21 11:35:40 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 21 Feb 2006 10:35:40 -0600 Subject: Mutable numbers In-Reply-To: References: <43fb2462$0$3211$636a55ce@news.free.fr> Message-ID: <17403.16732.239613.309098@montanaro.dyndns.org> Rocco> def f(): Rocco> a = 12100 Rocco> b = 12100 Rocco> c = 121*100 Rocco> print a is b Rocco> print a is c That the object with value 12100 is referenced by both a and b is a side effect of byte code compilation by CPython not an inherent property of integer objects. Nor is it an optimization performed by CPython on integers. As literals are collected during compilation they are only inserted into the local constants tuple once. >>> def f(): ... a = "12,100" ... b = "12,100" ... c = "12," + "100" ... print a is b ... print a is c ... >>> f() True False >>> print f.func_code.co_consts (None, '12,100', '12,', '100') >>> def f(): ... a = 12100 ... b = 12100 ... c = 121*100 ... print a is b ... print a is c ... >>> f() True False >>> print f.func_code.co_consts (None, 12100, 121, 100) Skip From dmbkiwi at gmail.com Sun Feb 26 03:58:03 2006 From: dmbkiwi at gmail.com (dmbkiwi at gmail.com) Date: 26 Feb 2006 00:58:03 -0800 Subject: dateutil and dates before today In-Reply-To: <1140942263.389308.133440@i39g2000cwa.googlegroups.com> References: <1140942263.389308.133440@i39g2000cwa.googlegroups.com> Message-ID: <1140944283.111719.263270@i39g2000cwa.googlegroups.com> I'll answer my own post. If you don't specify dtstart, it defaults to datetime.today(). Therefore, there are no instances before today. Specify dtstart as a historic date, and it works on any dates after dtstart. Wish I'd engaged brain before posting. Matt From fuzzyman at gmail.com Mon Feb 6 06:16:20 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 6 Feb 2006 03:16:20 -0800 Subject: UTF16, BOM, and Windows Line endings Message-ID: <1139224580.820529.198120@z14g2000cwz.googlegroups.com> Hello all, I'm handling some text files where I don't (necessarily) know the encoding beforehand. Because I use regular expressions to parse the text I *must* decode UTF16 encoded text (otherwise the regexes split on byte boundaries). I can recognise UTF8 and BOM and remove (but not necessarily decode). For UTF16 it seems that the Python codec will automatically remove the BOM. Having detected it (to trigger a decode) is it considered *invalid* to remove it ? The codec certainly handles the text without a BOM - I just don't want this part of the code to break later. Because I don't know the encoding until I've checked for the BOM I have to read in binary mode. Similarly I have to write in binary mode. How should I handle line-endings for UTF16 ? Is it possible that other programs (on windows) will have line endings as u'\r\n' ? When saving files for that platform should I make the line endings u'\r\n' ? (This sequence obviously encodes to four bytes in UTF16). I would only do this to ensure compatibility with other programs the user may use to create the text files. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From nyamatongwe+thunder at gmail.com Sun Feb 19 19:42:09 2006 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Mon, 20 Feb 2006 00:42:09 GMT Subject: commenting out blocks of code In-Reply-To: <1140245659.360215.253640@f14g2000cwb.googlegroups.com> References: <20060217231846.87613.qmail@web36708.mail.mud.yahoo.com> <1140245659.360215.253640@f14g2000cwb.googlegroups.com> Message-ID: Atanas Banov: > here is something you both seems to have not considered: imagine you > make decision if ^Q has to comment or uncomment based on the 1st line > and not on each line individually in the block. When first implementing Ctrl+Q, this looked to have similar advantages and disadvantages to the chosen implementation. However, it wouldn't allow a technique I've come to use which is to have two versions of some code or section of a configuration file and to toggle between the two by selecting the whole range and pressing Ctrl+Q. > #code1 > ##comment1 > ##comment2 > #code2 > ---------------- > > note how ## maintains where comments were. now, for the same selection, > ^Q again? 1st character is #, so the editor is asked to uncomment, > dwim: The problem with "##" as opposed to "#~" is that "##" is common in much source code particularly in barrier comments and comment sections: ############ Persistence section ############ ## These functions are responsible for load ## and save for the core media database. Neil From grante at visi.com Sun Feb 12 23:34:26 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 13 Feb 2006 04:34:26 -0000 Subject: how do you pronounce 'tuple'? References: Message-ID: <11v032ii4gvik72@corp.supernews.com> On 2006-02-13, John Salerno wrote: > I know it comes from the suffix -tuple, which makes me think > it's pronounced as 'toople', but I've seen (at m-w.com) that > the first pronunciation option is 'tuhple', so I wasn't sure. > Maybe it's both, but which is most prevalent? In my expereince, the latter. I don't think I've ever heard the other pronounciation. -- Grant Edwards grante Yow! Isn't this my STOP?! at visi.com From kent at kentsjohnson.com Thu Feb 23 11:26:09 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 23 Feb 2006 11:26:09 -0500 Subject: Unexpected timing results In-Reply-To: References: Message-ID: <43fddd97$1_2@newspeer2.tds.net> Steven D'Aprano wrote: > I have two code snippets to time a function object being executed. I > expected that they should give roughly the same result, but one is more > than an order of magnitude slower than the other. > > Here are the snippets: > > def timer1(): > timer = time.time > func = lambda : None > itr = [None] * 1000000 > t0 = timer() > for _ in itr: > func() > t1 = timer() > return t1 - t0 > > def timer2(): > timer = time.time > func = lambda : None > itr = [None] * 1000000 > t = 0.0 > for _ in itr: > t0 = timer() > func() > t1 = timer() > t += t1 - t0 > return t > > Here are the results: > > >>>>timer1() > > 0.54168200492858887 > >>>>timer2() > > 6.1631934642791748 > > Of course I expect timer2 should take longer to execute in total, > because it is doing a lot more work. But it seems to me that all that > extra work should not affect the time measured, which (I imagine) should > be about the same as timer1. Possibly even less as it isn't timing the > setup of the for loop. > > Any ideas what is causing the difference? I'm running Python 2.3 under > Linux. You are including the cost of one call to timer() in each loop: The cost of returning the time from the first call to timer() and the the cost of getting the time in the second call. On my computer with Python 2.4: D:\Projects\CB>python -m timeit -s "import time;timer=time.time" "t=timer()" 1000000 loops, best of 3: 0.498 usec per loop which is almost exactly the same as the difference between timer1() and timer2() on my machine: timer1 0.30999994278 timer2 0.812000274658 using Python 2.4.2 on Win2k. Kent From reply.in.the.newsgroup at my.address.is.invalid Sun Feb 26 05:35:39 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sun, 26 Feb 2006 11:35:39 +0100 Subject: ImportError in Unpickle References: <1140916392.357064.291290@t39g2000cwt.googlegroups.com> <8303025o795ogn175pdgoq7k2ahgqotnja@4ax.com> Message-ID: <731302l1kqegn9nnt3ba73dlormigrhpo4@4ax.com> Rene Pijlman: >draghuram at gmail.com: >>ImportError: No module named __main__ > >There are some posts in the Usenet archive Also: http://mail.python.org/pipermail/python-list/1999-April/000916.html -- Ren? Pijlman From lycka at carmen.se Mon Feb 13 13:06:22 2006 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 13 Feb 2006 19:06:22 +0100 Subject: Rethinking the Python tutorial In-Reply-To: References: Message-ID: Steve Holden wrote: > Magnus Lycka wrote: > As with all such content, the first thing you will need is a band of > volunteers dedicated to keeping the content up to date, both proactively > and in response to reader comments. That's why I suggested these already written tutorials. Both authors have shown that they can make an effort, and there are other people who have helped with contributions such as translations. Hopefully, giving these texts a more official status will stimulate them further and make more people interested, but I guess it could also go the other way, if it isn't handled well. > What we are talking about here is a Python Language Users' Guide. Agreed. > Google are very active supporters of Python already, though they don't > make a big song and dance about it. You might notice, for example, that > they are a Platinum Sponsor at PyCon this year, as well as being a > sponsor member of the PSF. The Summer of Code also benefited Python in > several ways. I didn't notice the PyCon sponsorship. Maybe that's something for the EuroPython arrangers to think about... After all, EuroPython 2006 will be at CERN, and that's where the whole web thingie started... :) > There are older-established companies with more Python programmers who > have made hardly any community contribution - the "takers" of the open > source world. I wouldn't like Google to think that the Python community > isn't recognizing their support. It has improved lately, and I agree that others could chip in as well. > You might also like to ask Alex what he'd feel about losing the > "Nutshell" revenue stream! Well, I suggested they'd pay him for it. Perhaps a decent sized sack of money now is as good as that long term stream... It was just a wild idea though. You know, they don't usually come true, but who knows? Suggesting it might increase the chances. It would certainly be a boost for Python to have such excellent documentation on the web. It would probably make it easier for Google (and you other big corps!) to find good Python programmers in the future. From loco_jokers_records at hotmail.com Fri Feb 10 18:47:14 2006 From: loco_jokers_records at hotmail.com (Gerber) Date: Sat, 11 Feb 2006 00:47:14 +0100 Subject: cmd Message-ID: I'd like some documentation on the cmd module, besides the regular docs, in help() and docs.python.org... Gerber From darkmooninorbit at gmail.com Thu Feb 2 02:04:05 2006 From: darkmooninorbit at gmail.com (Robert Deskoski) Date: Thu, 2 Feb 2006 18:04:05 +1100 Subject: popen and stderr Message-ID: <769bb5f0602012304g4e0cca90t6d39387e0971004a@mail.gmail.com> Hey all, Currently i'm trying to use popen3 to access stderr - i wanted to use it to output some text to the parent process, so it can display it (non-console, graphically is what I mean). Is it possible to write to stderr fromt he child process or, barring this, to attach another stream to the child process and use that to send back text. I'd use stdout, but it's already being used for console output. Thanks for any help given, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Fri Feb 24 08:36:16 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 24 Feb 2006 14:36:16 +0100 Subject: A C-like if statement References: <1140742149.011750.321530@z34g2000cwc.googlegroups.com> <1140775322.788083.256970@v46g2000cwv.googlegroups.com> Message-ID: <468giiF9p3beU1@uni-berlin.de> Roy Smith wrote: > In article , > Steven D'Aprano wrote: > >> Side-effects aren't always bad (import, for example, does all its work by >> side-effect). But they are generally frowned upon, and in functional >> languages they are verboten. > > How do you do any I/O in a functional language if side effects are > verboten? For that matter, how does a functional program ever stop > running? Using Monads. Which basically starts carrying around explicit state in an implicit manner. But that is restricted to very few, specific portions of the program. Diez From markleeds at verizon.net Sat Feb 25 18:01:21 2006 From: markleeds at verizon.net (MARK LEEDS) Date: Sat, 25 Feb 2006 15:01:21 -0800 Subject: looking for a simpe plotting module Message-ID: <001201c63a5f$65781330$2f01a8c0@m8d4477f3de884> i'm pretty much a python beginner so can anyone recommend a plooting package in python ( simple foating numbers that makes lines or dots with a yaxis and an an xaxis. i don't need fancy drawings ) that is a built in module in python ? i am using python 2.4 in linux if that matters. thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From carsten at uniqsys.com Mon Feb 13 13:50:11 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 13 Feb 2006 13:50:11 -0500 Subject: cx_Oracle string problems... In-Reply-To: <1139854719.427035.19820@g47g2000cwa.googlegroups.com> References: <1139850767.853237.122710@f14g2000cwb.googlegroups.com> <1139852585.938381.247590@f14g2000cwb.googlegroups.com> <1139854719.427035.19820@g47g2000cwa.googlegroups.com> Message-ID: <1139856611.11014.32.camel@dot.uniqsys.com> On Mon, 2006-02-13 at 13:18, MooMaster wrote: > Lol, that was a copy paste error into the post on my part...but the > problem has been fixed. Turns out that there was a string.replace call > somewhere else in the code that replaced all single quotes with empty > strings, which thus caused the singe quotes to disappear! Whoops! Please do yourself a favor and make use of the fact that Python's database API allows parametrized queries. Here's a sketch of what that might look like: sql = 'INSERT INTO prime.utwsLOT VALUES (:kID, etc...)' curse = self.connection.cursor() curse.execute(sql, kID=self.kID, etc...) Of course, "etc..." would have to be replaced with additional placeholders and parameter values for all the columns in utwsLOT. By using parametrized queries, you don't have to worry about any of the supplied values requiring special treatment due to any quotation marks or apostrophes that might they might contain. Hope this helps, Carsten. From tjreedy at udel.edu Sat Feb 11 16:35:23 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 11 Feb 2006 16:35:23 -0500 Subject: simple math question References: Message-ID: "John Salerno" wrote in message news:RuWdnVmaD4Q23XPeRVn-tw at rcn.net... > Can someone explain to me why the expression 5 / -2 evaluates to -3, > especially considering that -2 * -3 evaluates to 6? With same sign int division, one can think of the result as either being rounding down or rounding to zero. With mixed sign int division, rounding to zero becomes rounding up, so the language designer has to choose being consistent with one or the other but not both. There are pluses and minuses either way and different language designers have made different choices between the two. Guido's rational was posted some years ago but I forget. You might be able to find something in Google's c.l.p archives, or on the web in general. Terry Jan Reedy From martin at v.loewis.de Sun Feb 12 16:56:06 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 12 Feb 2006 22:56:06 +0100 Subject: Netstat in python. Does it's possible? In-Reply-To: References: <43EE0286.5020409@v.loewis.de> <43EE7B7E.5050802@v.loewis.de> Message-ID: <43efaef5$0$29674$9b622d9e@news.freenet.de> Jorgen Grahn wrote: > I was thinking mostly about /proc, /sys and related file systems. I have a > feeling parts of them they change quite frequently under Linux, and of > course under other Unices they may look completely different, or be absent. > > Like Mr Laird said elsewhere, the best thing might be to popen() netstat > and parse its output. Hmm. And the netstat output cannot change, and is identical across all systems? I agree that the format of the proc file system is different across systems (or other systems don't use netstat at all), however, on all systems I'm aware of, there is a certain committment to keeping the proc file system stable for applications (on Solaris more so than on Linux). Regards, Martin From larry.bates at websafe.com Thu Feb 23 19:06:46 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 23 Feb 2006 18:06:46 -0600 Subject: Concantenation and string slicing In-Reply-To: <1140735316.752278.298490@v46g2000cwv.googlegroups.com> References: <1140735316.752278.298490@v46g2000cwv.googlegroups.com> Message-ID: <43FE4E16.6040304@websafe.com> DannyB wrote: > I've written a program that takes a phrase and spits it back out > backwards. My problem is it throws each character on a new line. I'd > like the phrase to be on the same line. Is this possible? > > #Backward Message > > message = raw_input("Enter a message: ") > letter = len(message) > while (letter > 0): > newMessage = "" > newMessage += message[letter-1] > letter -= 1 > print newMessage > > > Thanks!! > > Dan > Better was is: message = raw_input("Enter a message: ") print message[::-1] -Larry Bates From scott.daniels at acm.org Sat Feb 4 16:09:06 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 04 Feb 2006 13:09:06 -0800 Subject: re.search slashes In-Reply-To: <6P6Ff.754501$_o.451742@attbi_s71> References: <43e4f066$1@nntp0.pdx.net> <6P6Ff.754501$_o.451742@attbi_s71> Message-ID: <43e516d7$1@nntp0.pdx.net> pyluke wrote: > Scott David Daniels wrote: >> pyluke wrote: >>> I... want to find lines with ... "\[" but not instances of "\\[" >> >> If you are parsing with regular expressions, you are running a marathon. >> If you are doing regular expressions without raw strings, you are running >> a marathon barefoot. > I'm not sure what you mean by running a marathon. I'm referring to this quote from: http://www.jwz.org/hacks/marginal.html "(Some people, when confronted with a problem, think ``I know, I'll use regular expressions.'' Now they have two problems.)" > I do follow your statement on raw strings, but that doesn't seem > to be the problem. It is an issue in the readability of your code, not the cause of the code behavior that you don't like. In your particular case, this is all made doubly hard to read since your patterns and search targets include back slashes. > \[ > \nabla \cdot u = 0 > \] > > I don't want to find the following > > \begin{tabular}{c c} > a & b \\[4pt] > 1 & 2 \\[3pt] > \end{tabular} > how about: r'(^|[^\\])\\\[' Which is: Find something beginning with either start-of-line or a non-backslash, followed (in either case) by a backslash and ending with an open square bracket. Generally, (for the example) I would have said a good test set describing your problem was: re.compile(pattern).search(r'\[ ') is not None re.compile(pattern).search(r' \[ ') is not None re.compile(pattern).search(r'\\[ ') is None re.compile(pattern).search(r' \\[ ') is None --Scott David Daniels scott.daniels at acm.org From bignose+hates-spam at benfinney.id.au Sat Feb 18 17:13:11 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 19 Feb 2006 09:13:11 +1100 Subject: share function argument between subsequent calls but not between class instances! References: <11vejkega5tbrc5@corp.supernews.com> Message-ID: <87wtfsb9jc.fsf@rose.polar.local> Duncan Booth writes: > If you intend to only use the default some of the time, and at other > times pass in a different list, then save the 'default' in the > instance and use a special marker value to indicate when you intend > the default to be used: The most common idiom for such a marker is the None value. class Test(object): def __init__(self): self.L = [] def f(self, a, L=None): if L is None: L = self.L L.append(a) return L -- \ "Consider the daffodil. And while you're doing that, I'll be | `\ over here, looking through your stuff." -- Jack Handey | _o__) | Ben Finney From reply.in.the.newsgroup at my.address.is.invalid Mon Feb 13 18:42:47 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 14 Feb 2006 00:42:47 +0100 Subject: Location of Python modules References: <1139854184.504114.46690@z14g2000cwz.googlegroups.com> Message-ID: Byte: >where are Python modules stored in Linux? Where are eggs laid on the western hemisphere? -- Ren? Pijlman From p at ulmcnett.com Fri Feb 17 19:10:04 2006 From: p at ulmcnett.com (Paul McNett) Date: Fri, 17 Feb 2006 16:10:04 -0800 Subject: commenting out blocks of code In-Reply-To: <20060217231846.87613.qmail@web36708.mail.mud.yahoo.com> References: <20060217231846.87613.qmail@web36708.mail.mud.yahoo.com> Message-ID: <43F665DC.2000201@ulmcnett.com> john peter wrote: > in java, i can prevent a block of code from executing > by bracketing the block with comment indicators, as shown > below: > /* > statement1 will not execute; > statement2 will not execute; > */ > statement3 will execute > > is there a similar mechanism in python, other than prefixing > the '#' character to the start of each statement i do not > want to execute (which gets old very quickly if one needs to > comment and uncomment several statements a couple of > times while "playing around with code" say during initial design)? IMO this is a missing feature in Python. However, if the block of code you are wanting to comment out doesn't happen to contain any triple-quotes, you can surround the code with those. For example: def myFunc(arg): return arg + 2 """ def myFunc(arg): return arg + 1 """ >>> print myFunc(2) 4 -- Paul From lycka at carmen.se Tue Feb 28 03:28:14 2006 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 28 Feb 2006 09:28:14 +0100 Subject: PEP 354: Enumerations in Python In-Reply-To: References: <87accdplbj.fsf@rose.polar.local> <7xmzgdtjl0.fsf@ruckus.brouhaha.com> <4402AB7F.7070804@REMOVEMEcyber.com.au> Message-ID: Tim Chase wrote: > ... throw UnthrowableKoan > ... > > (okay...maybe it's a little too early on a weekdays.mon morning) Probably, since a SyntaxError slipped in. Throw is C++ Tim. It's "raise UnRaisableKoan". From ian at excess.org Mon Feb 20 14:05:08 2006 From: ian at excess.org (Ian Ward) Date: Mon, 20 Feb 2006 14:05:08 -0500 Subject: ANN: Urwid 0.9.0 - Console UI library Message-ID: <43FA12E4.1080106@excess.org> Announcing Urwid 0.9.0 ---------------------- Urwid home page: http://excess.org/urwid/ Tarball: http://excess.org/urwid/urwid-0.9.0.tar.gz Screenshots: http://excess.org/urwid/utf8examples.html About this release: =================== This is the first release of Urwid with UTF-8 input and display support. A new raw_display module was added to enable UTF-8 display. This module also fixes the "dead corner" in the bottom right of the screen and improves legibility of bright text in some terminals. New in this release: ==================== - New support for UTF-8 encoding including input, display and editing of narrow and wide (CJK) characters. Preliminary combining (zero-width) character support is included, but full support will require terminal behavior detection. Right-to-Left input and display are not implemented. - New raw_display module that handles console display without relying on external libraries. This module was written as a work around for the lack of UTF-8 support in the standard version of ncurses. Eliminates "dead corner" in the bottom right of the screen. Avoids use of bold text in xterm and gnome-terminal for improved text legibility. - Fixed overlay bug related to UTF-8 handling. - Fixed Edit.move_cursor_to_coords(..) bug related to wide characters in UTF-8 encoding. About Urwid =========== Urwid is a console UI library for Python. It features fluid interface resizing, UTF-8 support, multiple text layouts, simple attribute markup, powerful scrolling list boxes and flexible interface design. Urwid is released under the GNU LGPL. From aahz at pythoncraft.com Fri Feb 24 13:31:25 2006 From: aahz at pythoncraft.com (Aahz) Date: 24 Feb 2006 10:31:25 -0800 Subject: python-list/python-dev quoting style References: Message-ID: In article , Michael Hoffman wrote: >Does anyone have a script to convert more conventional USENET quoting >style like this: > >John wrote: >> Jacob Jingleheimer Schmidt wrote in message-id > on 29 February 2004: >>> Lambda is the best Python feature ever! >> >> I disagree. > >to the commonly used python-dev/python-list style like this: > >[Jacob Jingleheimer Schmidt] >>> Lambda is the best Python feature ever! > >[John] >> I disagree. Blech. Stick with the standard Usenet quoting style for both! -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From claird at lairds.us Mon Feb 20 12:08:02 2006 From: claird at lairds.us (Cameron Laird) Date: Mon, 20 Feb 2006 17:08:02 GMT Subject: Python vs. Lisp -- please explain References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> Message-ID: In article , Alexander Schmolck wrote: . . . >However I don't find it at all implausible to assume that had Guido known all >the stuff that say, David Ungar and Guy Steele were aware of at the same time, >python would have come out not necessarily less dynamic but considerably >faster -- to its own detriment. > >'as Alexander, you've lost me. I *think* you're proposing that, were Guido more knowledgeable, he would have created a Python language that's roughly as we know now, implemented it with FASTER software ... and "to its own detriment". Do you truly believe that fewer people would use Python if its execution were faster? From mrstephengross at hotmail.com Mon Feb 20 23:49:06 2006 From: mrstephengross at hotmail.com (Stephen Gross) Date: Mon, 20 Feb 2006 23:49:06 -0500 Subject: Building python 2.4.2 on Cygwin References: <1140467074.739405.163440@g44g2000cwa.googlegroups.com> <20060220214414.GA1924@tishler.net> Message-ID: > On Mon, Feb 20, 2006 at 12:24:34PM -0800, mrstephengross wrote: >> Ok, I'm working on building python 2.4.2 on cygwin. I *think* it's >> version 3.0 or 3.1 (is there a quick way to find out what version of >> cygwin is running within a shell?) > > Use "uname -r". What version are you running? Uname tells me: $ uname -r 1.5.18(0.132/4/2) --Steve From cjw at sympatico.ca Thu Feb 9 15:22:55 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 09 Feb 2006 15:22:55 -0500 Subject: What editor shall I use? In-Reply-To: <1139410110.389122.215400@z14g2000cwz.googlegroups.com> References: <1139410110.389122.215400@z14g2000cwz.googlegroups.com> Message-ID: Lad wrote: > What editor shall I use if my Python script must contain utf-8 > characters? > I use XP > Thank you for reply > l.b. > I like PyScripter, although it's much more than an editor. http://mmm-experts.com/Products.aspx?ProductId=4 Colin W From scott.daniels at acm.org Thu Feb 23 18:06:47 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 23 Feb 2006 15:06:47 -0800 Subject: What's up with this code? In-Reply-To: <1140700754.171942.70530@o13g2000cwo.googlegroups.com> References: <1140649331.924736.128420@g43g2000cwa.googlegroups.com> <43fd08cf$1@nntp0.pdx.net> <1140699277.658249.280130@u72g2000cwu.googlegroups.com> <1140700754.171942.70530@o13g2000cwo.googlegroups.com> Message-ID: <43fe3e65$1@nntp0.pdx.net> Gregory Petrosyan wrote: > Oh, by the way, is there any documentation about time of execution of > standard functions? Nope. The reason is (A) that's a lot of work, (B) there are too many caveats in practice to make such information useful, (C) any such spec might corner the possible implementations in a later version. > is len(list) O(1) or O(n), etc) and is there any C version of decimal? len(list) is O(1), list[n] is O(1), and if you (and others) continue using decimal and it gets popular, rest assured that it will get faster. Also, dictionary access is \Theta(1) (but only because you run on machines with quite finite limitations). The general Python rule when writing is "only worry about fast enough" and optimize only after the code works and it needs to be faster. Further, to determine speed, measure (use the timeit module) rather than guess. Nobody's intuition is great WRT performance, and you'd be shocked at the number of hours people spend speeding up a chunk of code that cannot possibly substantially affect an applications performance. --Scott David Daniels scott.daniels at acm.org From xavier.morel at masklinn.net Sun Feb 26 07:15:53 2006 From: xavier.morel at masklinn.net (Xavier Morel) Date: Sun, 26 Feb 2006 13:15:53 +0100 Subject: Pure python implementation of string-like class In-Reply-To: <1140915354.024788.25720@z34g2000cwc.googlegroups.com> References: <20060225.102645.74687871.kayama@st.rim.or.jp> <1140891600.822510.189140@v46g2000cwv.googlegroups.com> <1140915354.024788.25720@z34g2000cwc.googlegroups.com> Message-ID: Ross Ridge wrote: > Xavier Morel wrote: >> Not if you're still within Unicode / Universal Character Set code space. > > Akihiro Kayama in his original post made it clear that he wanted to use > a character set larger than entire Unicode code space. > > Ross Ridge > He implies that, but in later messages he 1. Implies that he wants to use the Unicode private spaces, which are in the Unicode code space 2. Says explicitly that his needs concern Kanji encoding, which do fit in the existing Unicode code space, even if you take the largest estimates of the number of existing Kanjis (~80000), and which are (I think) already partially represented by the CJK Unified Ideograms and CJK Unified Ideograms extension A sets of regular Unicode. From bonono at gmail.com Tue Feb 21 02:14:54 2006 From: bonono at gmail.com (bonono at gmail.com) Date: 20 Feb 2006 23:14:54 -0800 Subject: Augmented assignment In-Reply-To: References: Message-ID: <1140506094.387829.60890@g14g2000cwa.googlegroups.com> Terry Reedy wrote: > Program performance might be noticeable if 'x' is something like a.b.c.d > that takes some lookup time. But again, I would use the += form for > readability without testing run time. Would x=x + 1 be more readable, regardless of the background(whether being introduced to the += form in some other language like C before) ? From rtilley at vt.edu Mon Feb 13 14:43:24 2006 From: rtilley at vt.edu (rtilley) Date: Mon, 13 Feb 2006 19:43:24 +0000 Subject: readlines and break apart based on letters In-Reply-To: References: Message-ID: I got this to work... just FYI: s = 'O:owner_sidG:group_sidD:dacl_flags(string_ace1)(string_ace2)...(string_acen)S:sacl_flags(string_ace1)(string_ace2)...(string_acen)' SD = {} S = str.split(s, 'S:') SD['S_ACL'] = S[1] D = str.split(S[0], 'D:') SD['D_ACL'] = D[1] G = str.split(D[0], 'G:') SD['G_SID'] = G[1] O = str.split(G[0], 'O:') SD['O_SID'] = O[1] for k,v in SD.iteritems(): print k,v From jes at nl.demon.net Fri Feb 3 17:59:46 2006 From: jes at nl.demon.net (Jim Segrave) Date: Fri, 03 Feb 2006 22:59:46 -0000 Subject: MySQLdb question... using table name as arg References: <%cNEf.19800$sA3.14913@fed1read02> Message-ID: <11u7o32q27aosb1@corp.supernews.com> In article <%cNEf.19800$sA3.14913 at fed1read02>, Sean Berry wrote: >I have four tables that all have the same column names (50 in each.) > >I have created an admin program to edit, delete and add records to the >tables and would like to use the table name as a variable in each query so >the code can be used for each of the 4 tables. Usually I would do something >like this by having 1 table with special column to categorize the records as >I am doing with each table, but this specific application requires that I do >it with 4 tables instead. > >To ensure that string are quoted properly without any hassle I use the >execute function like so assuming c is my cursor object... > >c.execute("update tableName set col1 = %s, col2 = %s, col3 = %s, ...", >(val1, val2, val3, ...)) > >But, not I want to do this with a variable tableName. If I add it to the >tuple of parameters in the second arg before val1 and replace tableName with >%s, then the tableName will be quoted in the query, causing an error. > >What is the best (easiest) way for me to accomplish this? I know it may be >a stupid question but I just can't figure it out. How about interpolating the table name into the string: c.execute("update %s set col1 = %%s, col2 = %%s, col3=%%s" % (sometable), \ ['the', 'cat', 'in the hat']) Note the need to double the %'s for the parameters to be bound. -- Jim Segrave (jes at jes-2.demon.nl) From kay.schluehr at gmx.net Tue Feb 21 05:38:54 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 21 Feb 2006 02:38:54 -0800 Subject: Python vs. Lisp -- please explain In-Reply-To: References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> <1140441519.702761.326130@g14g2000cwa.googlegroups.com> <1140471528.655265.312730@f14g2000cwb.googlegroups.com> Message-ID: <1140518334.035011.243270@o13g2000cwo.googlegroups.com> Alexander Schmolck wrote: > "Kay Schluehr" writes: > > > Alexanders hypothesis is completely absurd. > > You're currently not in the best position to make this claim, since you > evidently misunderstood what I wrote (I certainly did not mean to suggest that > Guido *deliberately* chose to make python slow; quite the opposite in fact). Like everyone else. It's sometimes hard extract the intended meaning in particular if it's opposed to the published one. I apologize if I overreacted. > > Maybe I wasn't sufficiently clear, so if rereading my original post doesn't > bring about enlightenment, I'll try a restatement. > > > It turned out over the years that capabilities of Python optimization are > > lower than those of Lisp and Smalltalk. But its a system effect and > > epiphenomenon of certain design decisions. > > The point is that the design decisions, certainly for Common Lisp, scheme and > particularly for dylan where also informed by what could be done > *efficiently*, because the people who designed these languages knew a lot > about advanced compiler implementation strategies for dynamic languages and > thought that they could achieve high levels of expressiveness whilst retaining > the possibility of very fast implementations (IIRC dylan specifically was > meant to be something like within 90% of C performance). CL and dylan were > also specifically designed for building very large and sophisticated systems, > whereas it seems Guido originally thought that python would scale to about 500 > LOC. O.K. To repeat it in an accurate manner. Python was originally designed by Guido to be a scripting language for a new OS as a more complete version of a shell scripting language. Unlike those its design was strongly influenced by the usability ideas of the ABC development team. Therefore speed considerations were not the primary concern but an open model that was easily extendable both on the C-API level and the language level. So a VM architecture was chosen to achieve this. Adding new opcodes should have been as simple as interfacing with the C-API. After growing strongly in the late 90s large scale projects emerged such as Zope and many users started to request more Python performance since they wanted to escape from the dual-language model. Writing C-code was not self evident for a new programmers generation grewn up with Java and the ffi turned out to be a hurdle. After remodeling the object core ( "new style classes" ) progressive optimizations came to hold. In 2002 a new genius programmer entered the scene, namely Armin Rigo, who came up with Psyco and launched the PyPy project together with a few other Python hackers in order to aggressively optimize Python using Pythons introspective capabilities. That's were we still are. Remembering the historical context we might draw some parallels to other contexts and language design intentions. We might also figure out parallels and differences between motives of language designers and leading persons who drive language evolution. Python is not just Guido although his signature is quite pervasive. In his latest musings he comes back to his central idea of language design as a kind of user interface design. It's probably this shift in perspective that can be attributed as original to him and which goes beyond making things just "simple" or "powerfull" or "efficient" ( at least he made this shift public and visible ). It is also the most controversial aspect of the language because it is still inseparable from technical decisions ( non-true closures, explicit self, statement-expression distinction, anonymous function as an expression with limited abilities etc. ) Kay From deets at nospam.web.de Tue Feb 7 12:16:51 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 07 Feb 2006 18:16:51 +0100 Subject: Is Python good for web crawlers? References: <1139330008.270988.227170@g44g2000cwa.googlegroups.com> <1139332188.851343.20580@g14g2000cwa.googlegroups.com> Message-ID: <44s30nF38tqrU1@uni-berlin.de> Tempo wrote: > Why do you say that the bottleneck of the crawler will always be > downloading the page? Is it becasue there isn't already a modual to do > this and I will have to start from scratch? Or a bandwidth issue? Because of bandwidth - not necessarily yours directly, but the maximum flow between your uplink and the site in question. It will always take at least a fractioin of a second up to several seconds until the data is there - in that time, lots of python code can run. Diez From exarkun at divmod.com Thu Feb 16 12:40:22 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 16 Feb 2006 12:40:22 -0500 Subject: question about scope In-Reply-To: <9J0Jf.1630$No6.38274@news.tufts.edu> Message-ID: <20060216174022.6122.44277867.divmod.quotient.697@ohm> On Thu, 16 Feb 2006 15:18:29 GMT, John Salerno wrote: > [snip] > >I understand what global and built-in are, and I thought I understood >the concept of local too, but when I got to this sentence (and the >previous sentence), I became confused about the first two scopes. What's >the difference between 'local' and 'enclosing functions'? I thought that >the only way to create a local namespace was if there *was* a function >definition, so now I'm confused by the apparent difference that the >authors are referring to. What's an example of a local scope without >having a function definition? Loops and if statements, perhaps? print dir # comes from __builtins__ dir = 10 print dir # comes from globals def foo(): dir = 10 print dir # comes from locals def bar(): print dir # comes from "enclosing scope" - foo's scope Hope this helps, Jean-Paul From gregpinero at gmail.com Sat Feb 4 02:18:27 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Sat, 4 Feb 2006 02:18:27 -0500 Subject: Recursive function going infinite and I can't see why. Message-ID: <312cfe2b0602032318i3fcb075di31406adefd1bbe@mail.gmail.com> Hi, Would anyone be able to tell me why my function below is getting stuck in infinite recusion? Maybe I'm just tired and missing something obvious? def replace_within_node(node,oldnode,newnode): if node is oldnode: return newnode else: for varname,value in node.__dict__.items(): node.__dict__[varname]=replace_within_node(value,oldnode,newnode) return node At the end of this email I pasted the whole text of the sample code in case it would help to see it in context or maybe step through it? -- Gregory Pi?ero Chief Innovation Officer Blended Technologies (www.blendedtechnologies.com) #This is the code that's causing my problem: #---------------------------------------------------------------------- import random import sys class Test_Class: pass class Node: def __init__(self): self.arg0=0 self.arg1=0 self.arg2=0 self.arg3=0 def snip(node): prob_of_returning_this_node=.4 if random.random()<=prob_of_returning_this_node: return node else: if hasattr(node,'__dict__') and len(node.__dict__)>0: return snip(random.choice(node.__dict__.values())) else: return node def replace_within_node(node,oldnode,newnode): if node is oldnode: return newnode else: if hasattr(node,'__dict__'): for varname,value in node.__dict__.items(): node.__dict__[varname]=replace_within_node(value,oldnode,newnode) return node def generate_random_program(currdepth,mindepth=2,maxdepth=4): node=Node() if currdepth==maxdepth: return node else: node=Node() for varname,value in node.__dict__.items(): node.__dict__[varname]=generate_random_program(currdepth+1,mindepth,maxdepth) return node def breed(father,mother): #want to take subtree from each input parameter and swap them. snip_from_mother=snip(mother.program) snip_from_father=snip(father.program) program_for_father=replace_within_node(father.program,snip_from_father,snip_from_mother) program_for_mother=replace_within_node(mother.program,snip_from_mother,snip_from_father) return program_for_father,program_for_mother if __name__=='__main__': dragons=[Test_Class() for i in range(10)] for dragon in dragons: dragon.program=generate_random_program(0) for i in range(100): breed(dragons[0],dragons[1]) From fabioz at esss.com.br Thu Feb 16 11:29:42 2006 From: fabioz at esss.com.br (Fabio Zadrozny) Date: Thu, 16 Feb 2006 14:29:42 -0200 Subject: [ANN] Pydev and Pydev Extensions 1.0.2 release In-Reply-To: <43E78E4F.20703@esss.com.br> References: <43382E1F.3000600@esss.com.br> <434E801E.3010702@esss.com.br> <43E78E4F.20703@esss.com.br> Message-ID: <43F4A876.6030001@esss.com.br> Hi All, Pydev and Pydev Extensions 1.0.2 have been released Check http://www.fabioz.com/pydev for details on Pydev Extensions and http://pydev.sf.net has for details on Pydev Highlights in Pydev Extensions: ------------------------------- - New feature in the debugger: the console is available for probing when in 'suspendend mode' - New feature in code analysis: Provided a way to consider tokens that should be in the globals - Halt fix when too many matches where found in the go to definition. - Code analysis minor bugs fixed. - Error when opening browser fixed. Highlights in Pydev: ----------------------- - Jython debugging now working. - Code coverage does not report docstrings as not being executed. - Freeze when making a 'step-in' fixed in the debugger. - Grammar generated with javacc version 4.0 Cheers, Fabio -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev PyDev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com From mehmetmutigozel at gmail.com Tue Feb 28 08:40:02 2006 From: mehmetmutigozel at gmail.com (mehmetmutigozel at gmail.com) Date: 28 Feb 2006 05:40:02 -0800 Subject: compiled program input In-Reply-To: References: <1141131055.777748.153150@v46g2000cwv.googlegroups.com> Message-ID: <1141134002.355298.99030@i39g2000cwa.googlegroups.com> :) yes it does. thank you very much fredrick. From dprovins at rpcl.com Fri Feb 24 12:41:39 2006 From: dprovins at rpcl.com (Dean Allen Provins) Date: Fri, 24 Feb 2006 17:41:39 GMT Subject: Tkinter canvas size determination In-Reply-To: References: <43FC9532.2050800@rpcl.com> <43FF22FB.5000407@rpcl.com> Message-ID: <43FF456A.6010504@rpcl.com> Martin: Martin Franklin wrote: > Dean Allen Provins wrote: > >> Cameron: >> >> Cameron Laird wrote: >> >>> In article <43FC9532.2050800 at rpcl.com>, >>> Dean Allen Provins wrote: >>> >>>> I need to determine the size of a canvas while the process is running. >>>> Does anyone know of a technique that will let me do that? >>> >>> . >>> . >>> . >>> Does >>> >>> import Tkinter >>> >>> c = Tkinter.Canvas() >>> >>> c.create_oval(13, 51, 80, 130) >>> 1 >>> >>> c.pack() >>> >>> print c.cget("width") >>> 284 >>> help? >>> >>> There are actually several different notions of the size of a >>> canvas. The example abovve should be a good starting point, >>> though. >>> There's also a mailing list specifically for Tkinter >> http://tkinter.unpythonic.net/wiki/mailing_20lists >; that >>> might interest you. >> >> >> I tried the "cget" function, and it returned the width that I had used >> when creating the canvas - even though the canvas was wider than that >> value at display time (and also after manually resizing the window). >> >> To your knowledge, is there a method to determine the current dimensions? >> >> Thanks, >> >> Dean > > > > Dean, > > Look at the winfo_* methods of Tkinter widgets, I think the one you want > is called winfo_reqheight / winfo_reqwidth or something very similar > pydoc Tkinter.Canvas will sort that out > > Martin Thanks. That is exactly what I needed. I tried it, and it returned the desired values. Regards, Dean From johnpote at blueyonder.co.uk Tue Feb 7 12:46:32 2006 From: johnpote at blueyonder.co.uk (John Pote) Date: Tue, 07 Feb 2006 17:46:32 GMT Subject: Hi reliability files, writing,reading and maintaining Message-ID: Hello, help/advice appreciated. Background: I am writing some web scripts in python to receive small amounts of data from remote sensors and store the data in a file. 50 to 100 bytes every 5 or 10 minutes. A new file for each day is anticipated. Of considerable importance is the long term availability of this data and it's gathering and storage without gaps. As the remote sensors have little on board storage it is important that a web server is available to receive the data. To that end two separately located servers will be running at all times and updating each other as new data arrives. I also assume each server will maintain two copies of the current data file, only one of which would be open at any one time, and some means of indicating if a file write has failed and which file contains valid data. The latter is not so important as the data itself will indicate both its completeness (missing samples) and its newness because of a time stamp with each sample. I would wish to secure this data gathering against crashes of the OS, hardware failures and power outages. So my request: 1. Are there any python modules 'out there' that might help in securely writing such files. 2. Can anyone suggest a book or two on this kind of file management. (These kind of problems must have been solved in the financial world many times). Many thanks, John Pote From __peter__ at web.de Thu Feb 2 07:50:33 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 02 Feb 2006 13:50:33 +0100 Subject: Builder Pattern References: <1138495045.948821.129010@z14g2000cwz.googlegroups.com> <1h9w0w5.1hjl1421g4btuoN%aleax@mail.comcast.net> <1138535681.097562.252810@g43g2000cwa.googlegroups.com> <1138883051.882700.94370@g44g2000cwa.googlegroups.com> Message-ID: > I have converted another example of strategy which I prefer to the 2 > described earlier, here it is: > > class FindMinima: > ????????def algorithm(self):raise NotImplementedError When most of your code does nothing in a pompous way that is a sure sign that you are heading in the wrong direction. Here's a translation into python: def least_squares(line): return 1.1, 2.2 def newtons_method(line): return 3.3, 4.4 def bisection(line): return 5.5, 6.6 def conjugate_gradient(line): return 3.3, 4.4 def test(): solver = least_squares print solver((5.5,5.5)) solver = bisection print solver((5.5,5.5)) test() Peter From jimlewis at emachineshop.com Fri Feb 3 08:16:26 2006 From: jimlewis at emachineshop.com (jimlewis at emachineshop.com) Date: 3 Feb 2006 05:16:26 -0800 Subject: Server side newbie In-Reply-To: <1138968318.121755.97100@g47g2000cwa.googlegroups.com> References: <1138552847.103899.302880@g14g2000cwa.googlegroups.com> <1138968318.121755.97100@g47g2000cwa.googlegroups.com> Message-ID: <1138972586.701860.208170@o13g2000cwo.googlegroups.com> Thanks but the math is a bit complex and already coded and debugged in a python desktop gui. From steve at REMOVETHIScyber.com.au Sun Feb 5 03:14:29 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 05 Feb 2006 19:14:29 +1100 Subject: Generators vs. Functions? References: <0001HW.C00ABC2B000323A6F0335550@news.individual.de> <43E50E73.40504@kzoo.edu> Message-ID: On Sun, 05 Feb 2006 03:31:24 +0000, Neil Schemenauer wrote: > Peter Hansen wrote: >> More precisely, the state of the function is *saved* when a yield >> occurs, so you certainly don't *recreate* it from scratch, but merely >> restore the state, and this should definitely be faster than creating it >> from scratch in the first place. > > Right. Resuming a generator is faster than calling a function. Have you actually measured this, or are you just making a wild guess? According to a short test performed by Magnus Lycka, resuming a generator takes more time than calling a function. My own test agrees. Here is my test, using Python 2.3. I've tried to make the test as fair as possible, with the same number of name lookups in both pieces of test code. # straight function, two name lookups >>> import timeit >>> >>> t1 = timeit.Timer(stmt="func.next()", setup= ... """class K: ... pass ... ... def next(): ... return 1 ... ... func = K() ... func.next = next ... """) >>> >>> t1.timeit() 0.63980388641357422 # generator, two name lookups >>> t2 = timeit.Timer(stmt="gen.next()", setup= ... """def g(): ... while 1: yield 1 ... ... gen = g() ... """) >>> >>> t2.timeit() 0.82081794738769531 # straight function, one name lookup >>> t3 = timeit.Timer(stmt="f()", setup= ... """def f(): ... return 1 ... """) >>> >>> t3.timeit() 0.47273492813110352 # generator, one name lookup >>> t4 = timeit.Timer(stmt="gnext()", setup= ... """def g(): ... while 1: yield 1 ... ... gnext = g().next ... """) >>> >>> t4.timeit() 0.55085492134094238 So on the basis of my tests, there is a small, but significant speed advantage to _calling_ a function versus _resuming_ a generator. Of course the other advantages of generators often far outweigh the tiny setup cost each time you call one. In addition, for any complex function with significant execution time, the call/resume time may be an insignificant fraction of the total execution time. There is little or no point in avoiding generators due to a misplaced and foolish attempt to optimise your code. -- Steven. From cdkrug at aol.com Sat Feb 11 08:54:46 2006 From: cdkrug at aol.com (Charles Krug) Date: Sat, 11 Feb 2006 07:54:46 -0600 Subject: Is there any books such as 'effective python' or else about the performance? References: Message-ID: On 2006-02-11, Kenneth Xie wrote: > att, thx. A lot of the ideas discussed in Effective C++ et al are things that Python does for us already. C++ works at a much lower layer of abstraction and you need to deal explicitly with freestore for any nontrivial class. EC++ is mostly about how NOT to crash your programs. The Python Cookbook is a "more pythonic" version of the same idea--proven techniques appropriate to the abstraction level of the language. Design Patterns is worth reading as well, but be careful with it. Many of the ideas that are difficult to do in C++, Java, Smalltalk, etc (singletons come to mind) are trivially easy to do in Python because of how our object model works. Bruce Eckle's "Thinking in Python" gives a pattern introduction explaining how things work in Python that can give you a sprinboard to adapting other patterns from C++ et al. From steve at REMOVETHIScyber.com.au Tue Feb 21 17:16:00 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 22 Feb 2006 09:16:00 +1100 Subject: Python vs. Lisp -- please explain References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> <43f8ba1e$0$2895$626a54ce@news.free.fr> <43f8cb3f$0$4225$626a54ce@news.free.fr> <87bqx3glb1.fsf@wilson.homeunix.com> <43f984dc$0$27151$626a54ce@news.free.fr> <873bienwlx.fsf@wilson.homeunix.com> <1140454473.335788@jetspin.drizzle.com> <1140490302.639049@jetspin.drizzle.com> <43FAD2C2.7080908@REMOVEMEcyber.com.au> Message-ID: On Tue, 21 Feb 2006 09:46:27 -0800, Donn Cave wrote: > In article <43FAD2C2.7080908 at REMOVEMEcyber.com.au>, > Steven D'Aprano wrote: > ... >> Hey Donn, here is a compiled program for the PowerPC, >> or an ARM processor, or one of IBM's Big Iron >> mainframes. Or even a Commodore 64. What do you think >> the chances are that you can execute it on your >> x86-compatible PC? It's compiled, it should just >> work!!! Right? >> >> No of course not. If your CPU can't interpret the >> machine code correctly, the fact that the code is >> compiled makes NO difference at all. [snip for brevity] > Sure, all this is true, except for the term "interpreter." > You would surely not use the word that way, unless you > just didn't want to communicate. Do you honestly believe that the CPU doesn't have to interpret the machine code, or are you just deliberately playing silly buggers with language? In modern CPUs, there is an intermediate layer of micro-code between the machine code your C compiler generates and the actual instructions executed in hardware. But even if we limit ourselves to obsolete hardware without micro-code, I ask you think about what an interpreter does, and what the CPU does, in the most general way possible. Both take a stream of instructions. Both have to take each instruction, and execute it. In both cases the link between the instruction and the effect is indirect: for example, the machine code 00000101 on the Zilog Z80 processor causes the CPU to decrement the B processor register. In assembly language this would be written as DEC B. There is absolutely nothing fundamental about the byte value 5 that inherently means "decrement B processor register". In other words, machine language is a language, just like it says, and like all languages, it must be interpreted. > Your paragraph above that starts with "No of course not", > even omits a point that everyone understands, you can in > fact expect a .py file will work independent of machine > architecture - like any interpreted language. Amazing. In your previous post you were telling everybody how the *disadvantage* of interpreted programs is that they won't run unless the interpreter is present, and in this post you are telling us that interpreted languages will just work. What happened to the requirement for an interpreter? Let's see you run that Python program on a Zilog Z80 without a Python interpreter. Can't be done. No interpreter, whether in hardware or software, and the program won't run, whether in source code or byte code or machine code. If I allow that the machines have an interpreter, perhaps you'll return the favour and install an interpreter for machine language (often called an emulator). Now your compiled C or Lisp code also will run independent of machine architecture. In order to force "interpreted language" and "compiled language" into two distinct categories, rather than just two overlapping extremes of a single unified category, you have to ignore reality. You ignore interpreted languages that are compiled, you ignore the reality of how machine code is used in the CPU, you ignore the existence of emulators, and you ignore virtual machines. > We all know > what native code compilation buys you and what it doesn't. Did you fail to learn *anything* from my parable of interpreted Lisp on a Macintosh II running faster than compiled Lisp running on a Mac II fitted with a Lisp processor? -- Steven From nogradi at gmail.com Tue Feb 14 10:23:06 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 14 Feb 2006 16:23:06 +0100 Subject: Embedding an Application in a Web browser Message-ID: <5f56302b0602140723v123741ffweeee939cec9a3828@mail.gmail.com> > Is it possible to embed a Python application within Internet explorer? > If so how do people recommend going about it. > > As for the application it has to be able display simple animated > graphics such as circles, lines and squares. However if someone clicks > on a shape it should open up another application, such as Word. > > Thanks, > > Rod > > Python Newbie Do you mean perhaps embedding python into a webserver? If you want to use apache as your server that is possible, check the mod_python module which embeds the python interpreter into apache. You can then write your application in python (displaying your animated graphics, etc) and visitors to your server will see what you the output from your program. For further info: http://modpython.org/ From invitro81 at gmx.net Sun Feb 26 17:01:26 2006 From: invitro81 at gmx.net (invitro81) Date: Sun, 26 Feb 2006 23:01:26 +0100 Subject: Memory allocation in for loops In-Reply-To: References: <1134298072.537702.158870@g49g2000cwa.googlegroups.com> Message-ID: Which one is better w.r.t. memory allocation but also w.r.t. speed: ## 1.1 ## def forloop(a,b): for idx in range(a,b): ## .. ## do something ## .. ## 1.2 ## def whileloop(a,b): idx = a while idx < b: ## .. ## do something ## .. idx += 1 ######### I mean what I really would like is to have something C++ - like "for (int idx = a; idx < b; i++) { .. }" where no internal vector or something like that is allocated but only a few op's on registers are performed; in the whileloop in python the picture is roughly the same behind the scenes I guess.. but what about in the forloop? Is python smart enough not to generate an internal vector as it does usually for lists or do I have to apply some modifications (xrange..)? What happens further if I do the following: ## 2.1 ## def forloop(a,b,lst): for idx in lst.sort(): ## .. ## do something ## .. ####### Is the sorting function called in every iteration just to detect that (after the first sorting) it is useless comming back to the loop or does this happen: ## 2.2 ## def forloop(a,b,lst): lst.sort() for idx in lst: ## .. ## do something ## .. ####### From onurb at xiludom.gro Wed Feb 15 12:13:23 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 15 Feb 2006 18:13:23 +0100 Subject: Pythonic gui format? In-Reply-To: <1140012875.616899.146890@f14g2000cwb.googlegroups.com> References: <1139858810.606052.39130@z14g2000cwz.googlegroups.com> <43f11990$0$667$626a54ce@news.free.fr> <1139923105.939191.200660@z14g2000cwz.googlegroups.com> <1140003644.055366.316620@g47g2000cwa.googlegroups.com> <43f314df$0$32162$626a54ce@news.free.fr> <1140012875.616899.146890@f14g2000cwb.googlegroups.com> Message-ID: <43f36150$0$675$626a54ce@news.free.fr> Fuzzyman wrote: > bruno at modulix wrote: > >>Fuzzyman wrote: >>(snip) >> >> >>>You say you don't want an 'extra layer' between your GUI and Python - >>>but your approach of using XML has the same drawback. Storing your 'GUI >>>configuration' in a text based format is a nice idea, but you will need >>>*something* to do the translation. >> >>Well, if the conf is valid Python, you've already get most of the >>'something to do the translation' for free !-) >> > > > Except he can't use ordinary dictionaries because they don't preserve > order, which is one of his requirements... Except that dict ordering (or lack of) is not a problem here, cf my other posts about this !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From limodou at gmail.com Mon Feb 6 11:41:04 2006 From: limodou at gmail.com (limodou) Date: Tue, 7 Feb 2006 00:41:04 +0800 Subject: Size of list In-Reply-To: <1139243538.269506.214060@f14g2000cwb.googlegroups.com> References: <1139243538.269506.214060@f14g2000cwb.googlegroups.com> Message-ID: <505f13c0602060841l719c9b00x@mail.gmail.com> 6 Feb 2006 08:32:18 -0800, Ernesto : > for line in PM_File_Handle.readlines(): > PM_fields = line.split(';') > > # Is there a way to get the size of PM_Fields here ? > # Something like > > size = PM_fields.size( ) > > # I could not find this attribute in the python docs. Thanks try: size = len(PM_fields) -- I like python! My Blog: http://www.donews.net/limodou NewEdit Maillist: http://groups.google.com/group/NewEdit From simon at titanic.co.uk Fri Feb 3 12:01:29 2006 From: simon at titanic.co.uk (Simon Faulkner) Date: Fri, 03 Feb 2006 17:01:29 +0000 Subject: Compiling Message-ID: <43E38C69.9070007@titanic.co.uk> Pardon me if this has been done to death but I can't find a simple explanation. I love Python for it's ease and speed of development especially for the "Programming Challenged" like me but why hasn't someone written a compiler for Python? I guess it's not that simple eh? Simon From tim.leeuwvander at nl.unisys.com Thu Feb 2 15:14:16 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 2 Feb 2006 12:14:16 -0800 Subject: Detecting filename-encoding (on WinXP)? In-Reply-To: References: <1138896194.914220.60080@o13g2000cwo.googlegroups.com> Message-ID: <1138911256.708199.223290@g43g2000cwa.googlegroups.com> Hi Magnus, I get the filename from a URL, which probably is not in any kind of unicode-string but just a plain ASCII string. It should be possible to cast this to an ASCII string -- I'll try it right away to see if this works. Thanks! --Tim From Sebastien.Boisgerault at gmail.com Wed Feb 15 17:41:07 2006 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 15 Feb 2006 14:41:07 -0800 Subject: multiple inheritance In-Reply-To: <1140041977.692748.133570@g43g2000cwa.googlegroups.com> References: <1140041977.692748.133570@g43g2000cwa.googlegroups.com> Message-ID: <1140043267.445069.218370@g43g2000cwa.googlegroups.com> Thomas Girod a ?crit : > Hi. > > I think I'm missing something about multiple inheritance in python. > > I've got this code. > > class Foo: > def __init__(self): > self.x = "defined by foo" > self.foo = None > > class Bar: > def __init__(self): > self.x = "defined by bar" > self.bar = None > > class Foobar(Foo,Bar): > pass > > fb = Foobar() > print fb.x > print fb.__dict__ > > which returns : > > >>> > defined by foo > {'x': 'defined by foo', 'foo': None} > > So I guess not defining __init__ in my class Foobar will call __init__ > from my superclass Foo. Also __dict__ doesn't show an attribute > 'bar':None so I guess Bar.__init__ is not called at all. > > I would like to have a subclass with all attributes from superclasses > defined, and only the attribute from the first when there is conflict > (i.e. in this case, Foobar would be like this but with bar:None) > > I tried this : > > class Foobar(Foo,Bar): > def __init__(self): > Foo.__init__(self) > Bar.__init__(self) > > >>> > defined by bar > {'x': 'defined by bar', 'foo': None, 'bar': None} > > Here I have all I want, except the value of 'x' comes from the 'Bar' > superclass rather than Foo. So, to have what I want, I would have to > invert the two calls to __init__ in order to have the right x value. > > What I find awkward here is that the order of __init__ calls matters, > rather than the order of the classes in the class declaration. > > Do you have any ideas of a way to get this multiple inheritance thing > solved without having to do those __init__ calls ? try: class Foo(object): def __init__(self): super(Foo, self).__init__() # not really necessary here self.x = "defined by foo" class Bar(object): def __init__(self): super(Bar, self).__init__() self.x = "defined by bar" class FooBar(Foo, Bar): def __init__(self): super(FooBar, self).__init__() and search for the "cooperative methods and super" section in http://www.python.org/2.2/descrintro.html Cheers, SB > > Thomas From iddw at hotmail.com Thu Feb 16 16:13:28 2006 From: iddw at hotmail.com (Dave Hansen) Date: Thu, 16 Feb 2006 15:13:28 -0600 Subject: Merging two lists of data (Pythonic way) References: <8k5Jf.27896$sA3.57@fed1read02> <1140122391.823206.74580@g14g2000cwa.googlegroups.com> Message-ID: <5iq9v11peim9ehamh39v2fcilq3ndq1s52@4ax.com> On Thu, 16 Feb 2006 12:51:24 -0800 in comp.lang.python, "SMB" wrote: > >"Jonathan Gardner" wrote in message >news:1140122391.823206.74580 at g14g2000cwa.googlegroups.com... >> codes = map(lambda x: x[0], list1) >> for d in list2: >> if d['code'] in codes: >> d['VERIFIED'] = 1 >> >> Is this what you were looking for? >> > >That is exactly what I was looking for. I will have to take a look at map. You might also look at list comprehensions. Replacing the first line in the above with codes = [x[0] for x in list1] should yield the same result. Regards, -=Dave -- Change is inevitable, progress is not. From apgwoz at gmail.com Fri Feb 3 10:32:10 2006 From: apgwoz at gmail.com (Andrew Gwozdziewycz) Date: Fri, 3 Feb 2006 10:32:10 -0500 Subject: would it be feasable to write python DJing software In-Reply-To: <11u6t3qc13jplad@corp.supernews.com> References: <1138925819.465108.181760@o13g2000cwo.googlegroups.com> <1138962918.427815.70300@g14g2000cwa.googlegroups.com> <11u6t3qc13jplad@corp.supernews.com> Message-ID: <8ba244fb0602030732l5ca57cd0i7b9227059b232efd@mail.gmail.com> > If that's the way you want to look at it, there is nothing that > can be done in pure python. Both the built-ins and the basic > operators and sematics are implimented in C. What makes python a powerful programming language? It's the fact that it bundles up all sorts of c-code into a nice easy to use language. When you write _any_ python, you are taking a peice of c here, a piece of c here, and when you import a "pure python" module, you're really just importing more c, because it's all being built from c. What makes a builtin faster? It's the fact that there's less work to be done before it's called. As more work needs to get done to find the builtins that make it possible to run, execution time increases. Plain and simple. So, to answer the original posters question, Use python to peice together the things you need. You're development time will be fast, and you will probably see some good results. -- Andrew Gwozdziewycz http://ihadagreatview.org http://plasticandroid.org From codecraig at gmail.com Sat Feb 18 12:51:27 2006 From: codecraig at gmail.com (abcd) Date: 18 Feb 2006 09:51:27 -0800 Subject: Get parameters from URL using CGI Message-ID: <1140285087.919635.74530@g43g2000cwa.googlegroups.com> i want to create a CGI script which simply prints out values given via the URL (such as when a GET is performed). So if I have a script named, foo.cgi ....and I access it by going to: http://www.somesite.com/cgi-bin/foo.cgi?name=john&age=90 I want foo.cgi to print out: name: john age: 90 how do i get the values from the URL like that? thanks From pmartin at snakecard.com Thu Feb 23 22:42:13 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Thu, 23 Feb 2006 21:42:13 -0600 Subject: Python stdout and Win 2003 References: Message-ID: PS: I forgot to mention that some of the "print"s are made from wxPython timer events. Philippe Philippe Martin wrote: > Hi, > > I have a program at a customer's site that seems to have random problem > which eventually come down to not being able to read/write from serial > ports. > > I trapped all the exceptions I could think of and all of them look like > this: > *********************************** > (ACCESS CONTROL)Fri, 24 Feb 2006 02:07:18 +0000 : Traceback (most recent > call last): > File "C > \Python24\lib\site-packages\SC\readers\SC_IDTech_MiniSmart_RS232.py", line > 308, in Is_Card_Inserted > print 'CARD NOT INSERTED' > IOError: [Errno 9] Bad file descriptor > *********************************** > > To me that means the print failed ... that stdout was not available > anymore. > > Am I correct? .... what could cause this. > > > Many thanks. > > Philippe From aleaxit at yahoo.com Wed Feb 8 01:12:52 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 7 Feb 2006 22:12:52 -0800 Subject: how to copy a Python object References: <1139301392.205225.48690@o13g2000cwo.googlegroups.com> <1139308149.557027.77160@z14g2000cwz.googlegroups.com> <1139309738.750080.183090@g47g2000cwa.googlegroups.com> Message-ID: <1haetkq.vpm95g4aixxhN%aleaxit@yahoo.com> Sch?le Daniel wrote: ... > >>> class X(object): > ... def __init__(self,lst): > ... self.lst = lst > ... def copy(self): > ... return X(self.lst[:]) > ... def __str__(self): > ... return "lst has id %i" % id(self.lst) ... > ... anyone? > are there better approaches? def __getstate__(self): return self.lst def __setstate__(self, L): self.lst = L and copy an instance x of X with copy.copy(x) [[after import copy, of course]]. This will also support pickling &c. getstate/setstate are generally the best approach. An equally good alternative here, omit setstate and just: def __getstate__(self): return dict(lst=self.lst) Alex From gene.tani at gmail.com Thu Feb 9 08:52:38 2006 From: gene.tani at gmail.com (gene tani) Date: 9 Feb 2006 05:52:38 -0800 Subject: Twisted book opinions? In-Reply-To: References: Message-ID: <1139493158.820123.17250@o13g2000cwo.googlegroups.com> Matt Goodall wrote: > Jay Parlar wrote: > > I was hoping to get some c.l.p. opinions on O'Reilly's new Twisted book. > > I think it's a good book to get. I know a fair amount about Twisted but > it still made for interesting reading. > > Tommi Virtanen (aka tv) posted a great review of the book shortly after > it was published. . > > - Matt here are some other useful sources http://www.pyzine.com/Issue006/Section_Articles/article_GettingTwisted.html http://www.onlamp.com/pub/a/python/2004/01/15/twisted_intro.html http://www.onlamp.com/pub/a/python/2004/02/12/advanced_nio.html http://www.rexx.com/~dkuhlman/twisted_patterns.html http://www.python.org/pycon/papers/applications.html From rrr at ronadam.com Tue Feb 28 14:12:49 2006 From: rrr at ronadam.com (Ron Adam) Date: Tue, 28 Feb 2006 13:12:49 -0600 Subject: sort one list using the values from another list In-Reply-To: <1141085589.680130.204380@j33g2000cwa.googlegroups.com> References: <1140981038.788111.93500@j33g2000cwa.googlegroups.com> <9bpMf.109707$4l5.58949@dukeread05> <1140990438.693026.14600@p10g2000cwp.googlegroups.com> <00sMf.109743$4l5.9230@dukeread05> <1hbdmux.1uvypp25sjx7jN%aleaxit@yahoo.com> <44034b68$1@nntp0.pdx.net> <1141085589.680130.204380@j33g2000cwa.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Following Ron Adam solution (and using [] instead of list() in the last > line), this may be a possible solution of the problem, that is often > quite fast: > > def psort16(s1, s2): > try: > d = dict(izip(s2, s1)) > except TypeError: > _indices = range(len(s1)) > _indices.sort(key=s2.__getitem__) > s1[:] = map(s1.__getitem__, _indices) > else: > if len(d) == len(s1): > s1[:] = [d[v] for v in sorted(d)] > else: > _indices = range(len(s1)) > _indices.sort(key=s2.__getitem__) > s1[:] = map(s1.__getitem__, _indices) > > Bye, > bearophile Looks good, but I think It would be simpler to just do. def psort17(s1, s2): try: d = dict(izip(s2, s1)) assert len(d) != len(s2) s1[:] = [d[v] for v in sorted(d)] except Exception: _indices = range(len(s1)) _indices.sort(key=s2.__getitem__) s1[:] = map(s1.__getitem__, _indices) We don't need to specify which exception. Any problems will just get raised again on the second try it also fails. Cheers, Ron From steve at REMOVETHIScyber.com.au Mon Feb 20 16:59:13 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 21 Feb 2006 08:59:13 +1100 Subject: Python vs. Lisp -- please explain References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> <43f8ba1e$0$2895$626a54ce@news.free.fr> <43f8cb3f$0$4225$626a54ce@news.free.fr> <87bqx3glb1.fsf@wilson.homeunix.com> <43f984dc$0$27151$626a54ce@news.free.fr> <873bienwlx.fsf@wilson.homeunix.com> <1140454473.335788@jetspin.drizzle.com> Message-ID: On Mon, 20 Feb 2006 16:54:34 +0000, Donn Cave wrote: > The reason this isn't just an abstruse philosophical argument where it > makes sense for us to obtusely cling to some indefensible point of view, > is that as the man points out, there are differences that we can't hide > forever from potential Python users. The most obvious to me is that > your Python program essential includes its interpreter - can't go anywhere > without it, and any change to the interpreter is a change to the program. > There are various strategies to address this, but pretending that Python > isn't interpreted is not one of them. Python programs (.py files) don't contain an interpreter. Some of those files are *really* small, you can't hide a full blown Python interpreter in just half a dozen lines. What you mean is that Python programs are only executable on a platform which contains the Python interpreter, and if it is not already installed, you have to install it yourself. So how exactly is that different from the fact that my compiled C program is only executable on a platform that already contains the correct machine code interpreter, and if that interpreter is not already installed, I have to install a machine code interpreter (either the correct CPU or a software emulator) for it? Moving compiled C programs from one system to another one with a different CPU also changes the performance (and sometimes even the semantics!) of the program. It is easier for the average user to change the version of Python than it is to change the CPU. Nobody denies that Python code running with no optimization tricks is (currently) slower than compiled C code. That's a matter of objective fact. Nobody denies that Python can be easily run in interactive mode. Nobody denies that *at some level* Python code has to be interpreted. But ALL code is interpreted at some level or another. And it is equally true that at another level Python code is compiled. Why should one take precedence over the other? The current state of the art is that the Python virtual machine is slower than the typical machine code virtual machine built into your CPU. That speed difference is only going to shrink, possibly disappear completely. But whatever happens in the future, it doesn't change two essential facts: - Python code must be compiled to execute; - machine code must be interpreted to execute. Far from being indefensible, philosophically there is no difference between the two. Python and C are both Turing Complete languages, and both are compiled, and both are interpreted (just at different places). Of course, the difference between theory and practice is that in theory there is no difference between theory and practice, but in practice there is. I've already allowed that in practice Python is slower than machine code. But Python is faster than purely interpreted languages like bash. Consider that Forth code can be as fast (and sometimes faster) than the equivalent machine code despite being interpreted. I remember a Apple/Texas Instruments collaborative PC back in the mid to late 1980s with a Lisp chip. Much to their chagrin, Lisp code interpreted on a vanilla Macintosh ran faster than compiled Lisp code running on their expensive Lisp machine. Funnily enough, the Apple/TI Lisp machine sank like a stone. So speed in and of itself tells you nothing about whether a language is interpreted or compiled. A fast interpreter beats a slow interpreter, that's all, even when the slow interpreter is in hardware. Describing C (or Lisp) as "compiled" and Python as "interpreted" is to paint with an extremely broad brush, both ignoring what actually happens in fact, and giving a false impression about Python. It is absolutely true to say that Python does not compile to machine code. (At least not yet.) But it is also absolutely true that Python is compiled. Why emphasise the interpreter, and therefore Python's similarity to bash, rather than the compiler and Python's similarity to (say) Java or Lisp? -- Steven. From jason.mobarak at gmail.com Sun Feb 26 01:16:31 2006 From: jason.mobarak at gmail.com (Jason Mobarak) Date: 25 Feb 2006 22:16:31 -0800 Subject: Modify the local scope inside a function References: <1140911588.659020.7640@i39g2000cwa.googlegroups.com> Message-ID: <1140934591.462650.176800@t39g2000cwt.googlegroups.com> Sandra-24 wrote: > Is there a way in python to add the items of a dictionary to the local > function scope? i.e. var_foo = dict['var_foo']. I don't know how many > items are in this dictionary, or what they are until runtime. Why do you want to do this? Exec and eval should -not- be used for this unless you are specifically creating a system allows arbitrary code execution. What's wrong with using a dictionary? It's much safer than allowing arbitrary names to be injected into a namespace. From abhinavduggal at gmail.com Thu Feb 16 02:46:02 2006 From: abhinavduggal at gmail.com (abhinav) Date: 15 Feb 2006 23:46:02 -0800 Subject: web crawler in python or C? In-Reply-To: <7xy80b96h2.fsf@ruckus.brouhaha.com> References: <1140069412.051298.242150@g44g2000cwa.googlegroups.com> <7xy80b96h2.fsf@ruckus.brouhaha.com> Message-ID: <1140075962.037640.126340@g43g2000cwa.googlegroups.com> It is DSL broadband 128kbps.But thats not the point.What i am saying is that would python be fine for implementing fast crawler algorithms or should i use C.Handling huge data,multithreading,file handling,heuristics for ranking,and maintaining huge data structures.What should be the language so as not to compromise that much on speed.What is the performance of python based crawlers vs C based crawlers.Should I use both the languages(partly C and python).How should i decide what part to be implemented in C and what should be done in python? Please guide me.Thanks. From cvanarsdall at mvista.com Wed Feb 15 15:59:03 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 15 Feb 2006 12:59:03 -0800 Subject: is socket thread safe? In-Reply-To: References: <1139912679.559724.131020@f14g2000cwb.googlegroups.com> Message-ID: <43F39617.9050006@mvista.com> Steve Horsley wrote: > e2wugui at gmail.com wrote: > >> thread1: >> while 1: >> buf = s.read() >> process(buf) >> >> thread2: >> while 1: >> buf = getdata() >> s.write(buf) >> >> > > It is safe, but watch out for this gotcha: If thread B calls > s.close() while thread A is blocked in s.read(), thread A will > never return from the read. My preferred solution is to set > socket timeout to a few seconds, and loop checking a status flag > so I know when to quit. > > I think a better thing would be to use something like a condition object to tie the two threads together and not use any polling loops. i.e. consumer goes to sleep while data buffer is empty, producer produces and signals condition object, consumer wakes up and consumes. To take this a step further, you have a status flag that is set to something like QUIT or CONSUME and when the condition is triggered wake up, then examine the status flag to determine if the consumer should then quit, consume, or whatever else you'd want your consumer thread to do. -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From kent at kentsjohnson.com Mon Feb 6 08:14:13 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 06 Feb 2006 08:14:13 -0500 Subject: fairly large webapp: from Java to Python. experiences? In-Reply-To: References: <1139005746.363918.267370@g47g2000cwa.googlegroups.com> <1139018653.508049.182020@g43g2000cwa.googlegroups.com> Message-ID: <43e74776$1_2@newspeer2.tds.net> Fabio Zadrozny wrote: > I agree that python code is usually smaller... but what you did is too > unfair (the code below would be more suitable for the comparrison). > > python: > print "%10.2f" % 10 > > java: > System.out.println(String.format("%10.2f", 10.0)); Though String.format() is new in Java 1.5 so in older code or for backward compatibility the longer code may be found. OTOH Python has supported % formatting since at least version 1.4 released in 1996. http://www.python.org/doc/1.4/lib/node11.html#SECTION00315100000000000000 In my experience the original point is valid - Python is usually (always?) more concise than equivalent Java code, and often dramatically so. Python makes common operations easy; Java sometimes seems to go out of its way to make them awkward. Kent From steve at REMOVETHIScyber.com.au Fri Feb 3 06:57:36 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 03 Feb 2006 22:57:36 +1100 Subject: Another try at Python's selfishness References: <1138918102.863033.298700@o13g2000cwo.googlegroups.com> <1138926741.052843.169270@z14g2000cwz.googlegroups.com> <1138965780.698016.95590@o13g2000cwo.googlegroups.com> Message-ID: On Fri, 03 Feb 2006 03:23:00 -0800, n.estner wrote: >> That usage (self is second parameter to B.test) is bound >> to cause trouble in general, but in this case doesn't have >> any effect I can see. The function call "test" would be >> resolved from its first parameter, instance of A, and that >> function would return 1. One of us is missing something >> here, could be me. > > Probably my example wasn't clear, let's try another: > > class A: > def test(a, **kwargs): return 1 > class B: > def test(b, **kwargs): return 2 > test(a=A(), b=B()) > > "self" isn't a keyword, so nothing should forbid this code. What is the > interpreter to do if it stumbles across this "test" call? You could try running it to see: >>> class A: ... def test(a, **kwargs): return 1 ... >>> class B: ... def test(b, **kwargs): return 2 ... >>> test(a=A(), b=B()) Traceback (most recent call last): File "", line 1, in ? NameError: name 'test' is not defined Oops! You have defined a name "test" in two namespaces, the class A and the class B, but there is no name "test" in the global namespace you are trying to run it in. Since namespaces are critical to Python, your test code is a problem that just cannot happen in Python. It is a non-issue. Python will not get confused between the two definitions of test. > I mean, > named-argument lookup is a tricky thing even if you do know what > function you're calling. If this would depend on one of the parameters, > I think it would become completely unintelligible. (you can think of > more complex examples yourself) > >> That's exactly the problem, it doesn't read from left to right, >> because we swap back and forth between function(parameter and >> parameter.function notation. > > That's because they're doing two different things: object.method() does > an attribute lookup, while function(parameter) looks for the function > in the current scope. No, function(parameter) does not look for a function. It looks for any object at all, and then tries to call it. Both calls do almost the same thing. object.method() looks up the name "method" in the object namespace, function(parameter) looks up the name "function" in the current namespace. Neither "method" nor "function" must be methods or functions, although if they are not callable objects, calling them will raise an exception. But regardless of what sort of objects they are, the look up proceeds in the same fashion. Unless you understand namespaces, you don't understand Python, and any criticism is likely to be due to misunderstanding. As near as I can tell, your original complaint might be solved simply: it seems to me that you are concerned about that extraneous "self" parameter for methods that don't need it: class Foo: def bar(self, a,b): return a+b Foo().bar(1,2) => 3 If bar doesn't need the instance or class Foo, perhaps it would be better off as an ordinary function rather than bound to a class. But if bar does need to be a method, perhaps you want something like this: # for Python 2.2 and up class Foo: def bar(a,b): return a+b bar = staticmethod(bar) # for Python 2.4 and up class Foo: @staticmethod def bar(a,b): return a+b Foo().bar(1,2) works exactly the same as before, but your definition of bar doesn't need that extraneous "self" parameter. -- Steven. From iainking at gmail.com Thu Feb 16 10:00:47 2006 From: iainking at gmail.com (Iain King) Date: 16 Feb 2006 07:00:47 -0800 Subject: looping over more than one list Message-ID: <1140102047.341803.10400@g44g2000cwa.googlegroups.com> When I loop over one list I use: for item in items: print item but often I want to loop through two lists at once, and I've been doing this like I would in any other language - creating an index counter and incrementing it. For example, (completely arbitrary), I have two strings of the same length, and I want to return a string which, at each character position, has the letter closest to 'A' from each of the original strings: def lowest(s1,s2): s = "" for i in xrange(len(s1)): s += lowerChar(s1[i],s2[i]) return s this seems unpythonic, compared to something like: def lowest(s1,s2): s = "" for c1,c2 in s1,s2: s += lowerChar(c1,c2) return s this doesn't work - s1,s2 becomes a tuple. Is there a way to do this that I'm missing? I don't see it in the docs. This works: def lowest(s1,s2): s = "" for c1,c2 in [x for x in zip(s1,s2)]: s += lowerChar(c1,c2) return s but it's hardly any more elegant than using a loop counter, and I'm guessing it's performance is a lot worse - I assume that the zip operation is extra work? Iain From theller at python.net Fri Feb 3 10:26:11 2006 From: theller at python.net (Thomas Heller) Date: Fri, 03 Feb 2006 16:26:11 +0100 Subject: newbie - script works in PythonWin - fails from Python References: <1138960717.927268.22640@g44g2000cwa.googlegroups.com> <1138961665.684357.78060@g44g2000cwa.googlegroups.com> <1138962543.290178.77790@g47g2000cwa.googlegroups.com> <1138978837.557550.144350@f14g2000cwb.googlegroups.com> Message-ID: marcus.tettmar at gmail.com writes: > Hi, > > This is all I get: > > error 250477278 > Traceback (most recent call last): > File "script1.py", line 5, in ? > Inst = lib.Initialize(0) > WindowsError: exception code 0xeedfade > > I get this when running python.exe script1.py > > ** When run from inside PythonWin it runs beautifully and returns with > no errors ** > > Regardless of what the error actually is it *works* when run from > PythonWin. It fails only when run from the command line. I'm trying > to find out why there is a difference. Clearly both either run a > different interpreter or with different switches. I was hoping someone > knows what the difference is. One difference is that PythonWin runs a messageloop. Does the documentation of the library you call say something about the error code you get? Thomas From mfranklin1 at gatwick.westerngeco.slb.com Tue Feb 21 04:28:15 2006 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 21 Feb 2006 09:28:15 +0000 Subject: Little tool - but very big size... :-( In-Reply-To: <43FAD9E3.5010004@gmail.com> References: <43FAD9E3.5010004@gmail.com> Message-ID: <43FADD2F.8060601@gatwick.westerngeco.slb.com> Durumdara wrote: > Hi ! > > I have a problem. > I have a little tool that can get data about filesystems and wrote it in > python. > > The main user asked me a GUI for this software. > > This user is needed a portable program, so I create this kind of the > software with Py2Exe. > > But it have very big size: 11 MB... :-( > > I need to have more compressed result. Can I compress dll-s, pyd-s with > Py2Exe ? > Can I decrease the total size with something ? you could try UPX http://upx.sourceforge.net/ I think it will handle the .pyd and dll files (it did the last time I tested it) > > If not, how to I create an self-unpackager and self-starter program that > use an temporary directory in the disk ? With WinRar ? I may be wrong (havn't used py2exe in a while) but I think it can now (again) create a single exe file? Otherwise something like Inno Setup http://www.jrsoftware.org/isinfo.php or a simple self extracting zip file > > Thanx for help: > dd > > > From jparlar at cogeco.ca Thu Feb 9 00:36:31 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Wed, 8 Feb 2006 21:36:31 -0800 Subject: Twisted book opinions? Message-ID: I was hoping to get some c.l.p. opinions on O'Reilly's new Twisted book. I'm coming at Twisted as someone who's been programming mainly in Python for almost 6 years now, but who's never done any Twisted development. I've used some of its prepackaged libraries before (and did some custom tweaks to TwistedSNMP), but I don't really know much at all about Twisted fundamentals. The few reviews on Amazon seem to imply that it's more of a cookbook. Would I be better off, for now, trying to get what I can from the twistedmatrix.com docs, and then move to the book when I'm comfortable with the basics? Or would the fact that I'm already pretty strong in Python be enough that I could start with the book? I considered posting this to the Twisted list instead, but thought I'd try somewhere a little more impartial :) Thanks in advance, JayP. From port001 at gentoo.org Fri Feb 10 19:23:51 2006 From: port001 at gentoo.org (Ian Leitch) Date: Sat, 11 Feb 2006 00:23:51 +0000 Subject: PySizeof: almost useful Message-ID: <43ED2E97.4010703@gentoo.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi list, I'm writing a little module to calculate the size of given objects, I just need a few little pointers to get the thing into a useful shape. Code here: http://dev.gentoo.org/~port001/Code/PySizeof/ The points I'm confused about are: 1. My method of determining the malloc() overhead is probably laughable, what's the correct method? 2. I'm at a loss as how to calculate the size of a long object -- any tips? 3. How much memory do instance, module and instancemethod objects hold? You'll notice I'm getting the size of most objects internal structures, what structures' size should I be measuring for such objects? 4. When calculating the size of a dict, if it contains more than the initial ma_smalltable size (8) should I be subtracting 8 from the len() number multiplied with the size of a dict entry? See line 73 in pysizeof.py No doubt there are some other glaring mistakes :) Many thanks to anyone bored enough to review this code. - -- Ian -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) iD8DBQFD7S6XefZ4eWAXRGIRAre2AJ4nf//qF/O9B+IhVgdQOj+1rLePZwCaAhvH 7FoGfjjhlm4bH4ZoQY+b+SA= =C3np -----END PGP SIGNATURE----- From miller_ralph at sbcglobal.net Wed Feb 15 17:34:58 2006 From: miller_ralph at sbcglobal.net (Ralph Miller) Date: Wed, 15 Feb 2006 16:34:58 -0600 Subject: ANN: PyIE - Python Inference Engine Message-ID: PyIE, Python Inference Engine, is now available at "DFWPython.org", under "Our Source Repository", thanks to Jeff Rush. The current revision is 0.9.10. What's PyIE ? ------------- PyIE is an hypothesis based, agenda driven, object oriented inference engine written in Python. Inferencing modes include back chaining, opportunistic forward chaining and explicit forward chaining. The object base supports classes, first-class objects and multiple, dynamic inheritance. PyIE uses a TMS (truth maintenance system) for non-monotonic reasoning. All objects are first class objects and all values are slot values, i.e. data members attached to some object. The GUI uses TKinter and consists of a main control panel and seven editors for the agenda, classes, objects, slots, rules, methods and commands. The knowledge base file types are currently XML and an older Python-like text format. A version is associated with all .py files and when the KBs are saved, this current version number is saved within the knowledge base source files. Only the XML format supports methods and is the default file type. Knowledge is usually, but not always, expressed in rules and the sequencing of the inferencing is controlled by a structure called an agenda. The current truth-values of each clause and each rule are kept in an hypothesis. Rules typically contain the main expression of knowledge and experience. Every rule must be associated with a hypo. Every rule has one or more antecedent clauses, usually termed the 'left hand side' (lhs). Rules may also have one or more consequent clauses; usually termed the 'right hand side' (rhs). In order to prove the associated hypo true, a rule must prove all antecedent clauses true. A hypothesis is simply a truth-value, in PyIE one of four possible values: True, False, Not Known or Unknown. 'Unknown' indicates that the hypo has not been tested, while 'Not Known' specifies that the hypo has been tested but proven neither 'True' nor 'False'. The engine proves hypotheses taken from an agenda. The agenda is hypothesis driven, that is, only hypotheses are contained in the agenda, not rules. The engine selects the relevant hypothesis to be proved and follows a specific set of steps to prove the hypo. Firing rules is only one method for proving a hypothesis. Download -------- The current PyIE may be exported from the subversion repository: https://python.taupro.com/repo/Projects/PyIE/trunk Compressed gzip and zip files will be available from time to time from: https://python.taupro.com/repo/Projects/PyIE/downloads External Dependencies --------------------- PyIE relies on Python 2.3 and later and also TKinter. No other modules need be installed. License ------- The license is MIT. Caveats ------- This is a research project. The documenetation is woefully incomplete. 'Eval' and 'compile' are used in the "KBsXML.py" module to process rules and methods. The underlying assumption is that there will be no malicious use. Author ------ Ralph S. Miller miller_ralph at sbcglobal.net Regards, Ralph From exarkun at divmod.com Thu Feb 2 12:36:16 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 2 Feb 2006 12:36:16 -0500 Subject: my openGL API need threads!!! But how to ,ake it work??? In-Reply-To: <1138901385.767694.288170@g49g2000cwa.googlegroups.com> Message-ID: <20060202173616.2697.2052539175.divmod.quotient.4730@ohm> On 2 Feb 2006 09:29:45 -0800, Laurent wrote: >That is exactly what I do not want!! > >this is not transparent, I'm sure it is possible to make what I want: >Scene = ooglScene() >Scene.run() >scene.append(ooglPoint()) Most concurrency is never even remotely transparent. Stop chasing a fantasy, or start doing ground-breaking research to advance the state of the art. Jean-Paul From pmartin at snakecard.com Thu Feb 23 08:30:00 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Thu, 23 Feb 2006 07:30:00 -0600 Subject: catching traceback.print_exc() Message-ID: Hi, Is there a way to catch traceback.print_exc() output into a string ? Philippe From vinay_sajip at yahoo.co.uk Tue Feb 7 18:13:01 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 7 Feb 2006 15:13:01 -0800 Subject: Strange behavior with os call in cgi script References: <1139171873.431432.195080@f14g2000cwb.googlegroups.com> <43e665f1$1@news.uni-ulm.de> <1139176638.972414.19590@g47g2000cwa.googlegroups.com> Message-ID: <1139353981.620749.254230@z14g2000cwz.googlegroups.com> Rene Pijlman wrote: > It struck me as somewhat complicated as well. > > Looking at the basic example: > http://www.python.org/doc/2.3.5/lib/node304.html > > ... the things that first-time users shouldn't be bothered with IMO are: > > 1. Getting a logger by name from a hierarchical namespace. There should be > a module-level log function that logs through the root logger. > 2. Formatting the message (use a sensible default) > 3. Adding a handler to a logger (artefact of the logging system). > 4. Setting a log level (use a sensible default). > > Perhaps there should be some module-level functions that make it easier to > 'just log this message to that file'. > > But I do think that adding logging to a cgi script is a sensible thing to > do for a beginner. Getting that to run in a debugger is probably way more > complicated. You should look at later versions of Python - your points above about easier configuration have already been addressed: here's a link from the current (2.4) docs: http://docs.python.org/lib/minimal-example.html Regards, Vinay Sajip From grante at visi.com Fri Feb 3 15:39:09 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 03 Feb 2006 20:39:09 -0000 Subject: would it be feasable to write python DJing software References: <1138925819.465108.181760@o13g2000cwo.googlegroups.com> <1138962918.427815.70300@g14g2000cwa.googlegroups.com> <11u6t3qc13jplad@corp.supernews.com> Message-ID: <11u7frd3e5mm2f4@corp.supernews.com> On 2006-02-03, Ivan Voras wrote: >>>>Actually, manipulating and mixing audio samples can be both fast and >>>>elegant, in Python, if you use Numeric or a similar library. >>> >>>... at which point you're actually doing it in C, not pure python... :) >> >> If that's the way you want to look at it, there is nothing that >> can be done in pure python. > > I think people who say that deliberately misunderstand the > point. Python is suitable for some things, not for others. So > is C. People who say what? -- Grant Edwards grante Yow! Do you need at any MOUTH-TO-MOUTH visi.com resuscitation? From iddw at hotmail.com Tue Feb 14 12:39:15 2006 From: iddw at hotmail.com (Dave Hansen) Date: Tue, 14 Feb 2006 11:39:15 -0600 Subject: processing limitation in Python References: <1139935358.128826.58660@g14g2000cwa.googlegroups.com> Message-ID: On 14 Feb 2006 08:42:38 -0800 in comp.lang.python, "pdr14 at comcast.net" wrote: >If I un-comment any line in this program below the line where I >commented " all OK up to this point " This program locks up my >computer. Hmm. Ctrl-C gets me out just fine. In Idle, at least. > >Windows task manager will show "Not Responding" for Python in the >Applications tab and in the Performance tabe the CPU usage will be >locked at %100. Well sure. It's pretty busy code. > >I've experienced the same problem on 2 different computers, one running >2000 pro. the other running XP home eddition. both computers run >Python 2.4.2 > >I'm just wondering if any one else has noticed any problems with >working with large numbers in Python ind if there is anything that can >work around this issue. Try running with the changes I've made below, and see if that tells you anything. def factor(n): d = 2 pctr = 0 factors = [ ] while n > 1: if n % d == 0: factors.append(d) n = n/d else: d = d + 1 pctr += 1 if pctr >= 1000000: print "So Far: " + str(factors) pctr = 0 print factors factor (12) factor (123) factor (1234) factor (12345) factor (123456) factor (1234567) factor (12345678) factor (123456789) factor (1234567898) factor (12345678987) factor (123456789876) factor (1234567898765) # all OK up to this point factor (12345678987654) # locks up computer if I run this line #factor (123456789876543) #factor (1234567898765432) #factor (12345678987654321) Hint: 2057613164609L is a Really Big Number (tm). If it's prime (I don't know if it is or not), it will take more than 46 days on my computer to figure that out. Did you wait that long? Regards, -=Dave -- Change is inevitable, progress is not. From eoinrogers at gmail.com Sun Feb 5 12:33:15 2006 From: eoinrogers at gmail.com (Byte) Date: 5 Feb 2006 09:33:15 -0800 Subject: Learning Python In-Reply-To: <1139159843.488988.279770@g43g2000cwa.googlegroups.com> References: <1139154754.099716.71300@f14g2000cwb.googlegroups.com> <1139156577.897100.69140@g43g2000cwa.googlegroups.com> <1139158796.288778.244000@z14g2000cwz.googlegroups.com> <1139159843.488988.279770@g43g2000cwa.googlegroups.com> Message-ID: <1139160795.149427.120760@g44g2000cwa.googlegroups.com> >parse the expression, extract the operands and the operation, apply the operation to the operands How? Give me some example code, but please keep it simple. >are you trying to code a calculator? Not intending to, just trying to learn Python. Suppose what i'm trying to code is a but like a CLI calculator, but i'm just writing it for my own educational beifits. From benji at benjiyork.com Sat Feb 18 22:05:52 2006 From: benji at benjiyork.com (Benji York) Date: Sat, 18 Feb 2006 22:05:52 -0500 Subject: define loop statement? In-Reply-To: References: Message-ID: <43F7E090.50200@benjiyork.com> David Isaac wrote: > I would like to be able to define a loop statement > (nevermind why) so that I can write something like > > loop 10: > do_something Here's a flagrant hack: import sys VAR_NAME = '__repeat_counter' def set_repeat_counter(value): frame = sys._getframe(2) frame.f_locals[VAR_NAME] = value def get_repeat_counter(value): frame = sys._getframe(2) if VAR_NAME not in frame.f_locals: frame.f_locals[VAR_NAME] = value return frame.f_locals[VAR_NAME] def repeat(limit): set_repeat_counter(get_repeat_counter(limit)-1) return get_repeat_counter(limit) while repeat(10): print 'OK' Without more work it doesn't allow nested loops though. And for the record, if you're worrying about Python's counted loop construct you need better things to worry about. -- Benji York From fuzzyman at gmail.com Mon Feb 6 06:08:33 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 6 Feb 2006 03:08:33 -0800 Subject: would it be feasable to write python DJing software In-Reply-To: References: <1138925819.465108.181760@o13g2000cwo.googlegroups.com> Message-ID: <1139224113.713168.168700@z14g2000cwz.googlegroups.com> Ivan Voras wrote: > Ivan Voras wrote: > > > Because "bar and aba happen to be parts of extension library" :) > > To end this disussion: I meant "doing it in C" as a colloquial > expression, not a technical one. The expression holds true for every > case where a function/class/module/etc is implemented in a lower-level > language, and "C" was used only as an example. I think the point we were trying to make, is that even in 'colloquial terms' there is *no difference* between using a part of the standard library (e.g. the builtin module md5) and a third party extension module written in C. All the logic you actually write is in pure python. If you write *your own extension module* in C, then you could rightly be described as doing it in C. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From steve at holdenweb.com Wed Feb 22 15:01:39 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 22 Feb 2006 15:01:39 -0500 Subject: a little more help with python server-side scripting In-Reply-To: References: <59edncmGm6g2LmbeRVn-pw@rcn.net> Message-ID: John Salerno wrote: > John Salerno wrote: > >>I contacted my domain host about how Python is implemented on their >>server, and got this response: > > > Uh, okay, I asked a related question to them and now I got this: > > ------------ > Hello John, > > There are some corrections based on last reply. > > The python installation on our windows hosting is not configured as > mod_python. Howevet, it is directly map with a website extensions > mapping in IIS. Save your python script as .py file on the wwwroot and > you may call the scripts using http://www.yourdomain.com/yourfile.py > > If you have any enquiries, please do not hesitate to contact. > > Best regards, > > Mackenzie S. > Support Executive > ----------- > > Does that really change anything? > Well, it means that PSP is out, unfortunately. > What I had asked was if I could just embed Python code within my HTML > files, like you do with PHP, but they didn't address that yet. OK, what you need to ask them is whether they have installed Python as an Active Scripting language. If they have then you can use it pretty much like VBscript. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From skip at pobox.com Wed Feb 8 12:57:00 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 8 Feb 2006 11:57:00 -0600 Subject: apostrophe or double quote? In-Reply-To: <1139413150.237052.47320@o13g2000cwo.googlegroups.com> References: <1139370460.360400.232500@z14g2000cwz.googlegroups.com> <1139413150.237052.47320@o13g2000cwo.googlegroups.com> Message-ID: <17386.12524.935119.641171@montanaro.dyndns.org> Just to present a complete picture, not mentioned in this thread are triple-quoted strings: 'abc' == '''abc''' == "abc" == """abc""" Triple-quoted strings are no different than regular strings, though they do allow literal newlines to be embedded in the string. Their presence is most often detected in doc strings precisely for this reason. Skip From grante at visi.com Fri Feb 3 10:30:26 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 03 Feb 2006 15:30:26 -0000 Subject: would it be feasable to write python DJing software References: <1138925819.465108.181760@o13g2000cwo.googlegroups.com> <1138962918.427815.70300@g14g2000cwa.googlegroups.com> <1138966084.385205.254410@g14g2000cwa.googlegroups.com> Message-ID: <11u6toijlcufs8d@corp.supernews.com> On 2006-02-03, Fuzzyman wrote: > Come to that, you're **really** doing it in machine code... And probably not the machine code emitted by the assembler but rather the actual micro-code that's implemented in hardware that's running a program that implements the VM for the machine code emitted by the assemblers. Hell, from the Python point of view it might as well be tortoises all the way down. -- Grant Edwards grante Yow! Dehydrated EGGS are at STREWN across ROULETTE visi.com TABLES... From me at privacy.net Thu Feb 16 15:21:24 2006 From: me at privacy.net (Charles) Date: Thu, 16 Feb 2006 17:21:24 -0300 Subject: mod_python and open HTTP connection Message-ID: Hello, I'm think about using mod_python for a project but I need to make sure: Does mod_python time out after a minute ? (I hope not). If I leave an HTTP connection open so that the content keeps loading inside the browser window indefinately, and if I close the browser window, the mod_python process is terminated, right? Thanks, -- Charles. Desenvolvimento e cria??o de sites: www.auriance.com Hospedagem de sites e servidores dedicados: www.auriance.net From sybrenUSE at YOURthirdtower.com.imagination Tue Feb 14 06:06:11 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 14 Feb 2006 12:06:11 +0100 Subject: Python / Apache / MySQL References: <1139907519.427789.188760@g14g2000cwa.googlegroups.com> <0001HW.C01764D700060858F0407550@news.individual.de> <43f1aebb$0$1728$636a55ce@news.free.fr> <0001HW.C01772E1000952B1F0407550@news.individual.de> Message-ID: Kalle Anke enlightened us with: > What about speed? I've always had the impression that while > PostgreSQL is more complete than MySQL it's also slower. For simple queries, I believe (no real knowledge here) MySQL is indeed faster. One of the problems I have with MySQL is that it doesn't support foreign keys nor transactions on the default table format. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From nospamformeSVP at gmail.com Wed Feb 22 18:38:26 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Wed, 22 Feb 2006 18:38:26 -0500 Subject: Newbie question: Multiple installations of Python on Windows machines In-Reply-To: <1140642974.386791.107270@o13g2000cwo.googlegroups.com> References: <1140519304.913540.296600@g14g2000cwa.googlegroups.com> <1140642974.386791.107270@o13g2000cwo.googlegroups.com> Message-ID: Fuzzyman wrote: > > It means installing a compiler (but I don't see a way around that) - > but this worked for me : > > http://www.vrplumber.com/programming/mstoolkit/index.html > > So long as the module can be installed with distutils, the instuctions > there will work for you. Hefty download though. > Oh, I was not expecting something like this. I wonder if anyone has tried the newish free Visual Studio 2005 Visual C++ Express insatll instead of all of the stuff that this link calls for plus mods to distutils. I suppose that it would too much to hope for. Ah well. Don. From peter at engcorp.com Fri Feb 17 19:12:01 2006 From: peter at engcorp.com (Peter Hansen) Date: Fri, 17 Feb 2006 19:12:01 -0500 Subject: commenting out blocks of code In-Reply-To: <20060217231846.87613.qmail@web36708.mail.mud.yahoo.com> References: <20060217231846.87613.qmail@web36708.mail.mud.yahoo.com> Message-ID: john peter wrote: > is there a similar mechanism in python, other than prefixing > the '#' character to the start of each statement i do not > want to execute (which gets old very quickly if one needs to > comment and uncomment several statements a couple of > times while "playing around with code" say during initial design)? In addition to the approach Paul has suggested, you should also consider using a better editor, as most decent editors should have some kind of "block comment/uncomment" feature that prevents that operation from getting old very quickly... Scite, for example, lets me selected a block and hit Ctrl-Q to either comment or uncomment the block. (It does this by prefixing each line with #~ instead of just #, which allows it to detect when a line is already so commented and reverse the operation.) Other decent editors have their own approach. -Peter From sbaush at gmail.com Mon Feb 6 12:35:25 2006 From: sbaush at gmail.com (Sbaush) Date: Mon, 6 Feb 2006 18:35:25 +0100 Subject: problem in ElementTree SubElement Message-ID: Hi all. I would get this element in xml: I have write this: date=ET.SubElement(idsreq,"date") date.set("month",month) date.set("day",day) but i get this: The attributes are not in my order!! how i can get the attributes in right order??? Thanks all. -- Sbaush -------------- next part -------------- An HTML attachment was scrubbed... URL: From oddr at home.no.no Fri Feb 24 04:57:58 2006 From: oddr at home.no.no (Odd-R.) Date: 24 Feb 2006 09:57:58 GMT Subject: Exception-handling Message-ID: I have come over a strange problem regarding exceptions This is my code: try: #some operation except Exception, info: #some message except: #?? When executing my code, I get to the last block here. This I find rather strange, because I thought Exception would catch all exceptions. But this is obviously not the case here. What is this, and how can I get a hold of what causes the exception? Thanks! -- Har du et kj?leskap, har du en TV s? har du alt du trenger for ? leve -Jokke & Valentinerne From rtilley at vt.edu Mon Feb 20 18:32:46 2006 From: rtilley at vt.edu (rtilley) Date: Mon, 20 Feb 2006 18:32:46 -0500 Subject: urllib2 auth error Message-ID: I get this error: HTTP Error 401: Authorization Required When I do this: try: handler = urllib2.HTTPBasicAuthHandler() handler.add_password('realm', 'website', 'user', 'pass') opener = urllib2.build_opener(handler) urllib2.install_opener(opener) f = urllib2.urlopen('http://website') print f.read() f.close() except Exception, e: print e I have the right username and password. I may be using the above code wrong. Any tips? Thanks, Brad From claudio.grondi at freenet.de Sat Feb 25 16:16:55 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sat, 25 Feb 2006 22:16:55 +0100 Subject: Is Python a Zen language? In-Reply-To: <1140876556.080086.252390@e56g2000cwe.googlegroups.com> References: <1140876556.080086.252390@e56g2000cwe.googlegroups.com> Message-ID: John Coleman wrote: > Greetings, > I have a rough classification of languages into 2 classes: Zen > languages and tool languages. A tool language is a language that is, > well, a *tool* for programming a computer. C is the prototypical tool > language. Most languages in the Algol family are tool languages. Visual > Basic and Java are also tool languages. On the other hand, a Zen > language is a language which is purported to transform your way of > thinking about programming. Lisp, Scheme, Forth, Smalltalk and (maybe) > C++ are Zen languages. Disciples acknowledge that it is difficult to > pick up these languages but claim that, if you persevere, you sooner or > later reach a state of computational satori in which it all makes > sense. Interestingly enough, these languages often have books which > approach scriptural status e.g. SICP for Scheme. > > So (assuming my classification makes sense) which is Python? The > emphasis on simplicity and the beginner-friendly nature of it seems to > put it in the tool category. On the other hand, the emphasis on the ONE > TRUE WAY to accomplish most tasks and the tendency for participants in > this newsgroup to criticize one another's code as being "unpythonic" > seems to move it towards the Zen category. Of course, even tool > languages have their idioms which the novice needs to pick up, so maybe > this isn't decisive, but I detect an element of zeal in this newsgroup > that I don't detect in (say) Excel VBA programming newsgroups. > > No value judgement is intended by my classification. There is no > denying that Zen languages are often very powerful tools (for those who > have reached satori) and that there is a Zen to really mastering, say, > C. Personally, I have never been able to master any Zen language but > can pick up tool languages fairly quickly, so I prefer tool languages. > This is probably because I am not a programmer (I'm a mathematician who > likes to program as a hobby and for numerical simulations) and so don't > have the time to invest in picking up a Zen language. Hard-core hackers > might presumably lean towards the Zen languages. > > Just curious > > -John Coleman > I was lately involved in some very long threads trying to answer the question what a simple assignment operator does and what is behind a Python identifier (variable). In the context of the above mentioned experience I agree with the notion, that from the beginner point of view, as long as there is no need to get deep understanding what goes on behind the scenes, Python is a tool. At that moment, when it becomes necessary to optimize the code for speed and understand the exact details of what is going on behind the scenes Python turns into a mystery which needs time, effort and ability to grasp new concepts in order to gain control over it, i.e. Python reveals its Zen character. In this context it appears to me worth to mention, that in my eyes a 'pythonic' way of programming has not necessarily something to do with the Python language itself. Even if it is sure better to use Python for 'pythonic' way of programming, it can also be done using any other programming language. I assume, that many of todays advanced Python users were already aware of the 'pythonic' way of programming long before they started to use Python. In Python they found many of the tools they have developed for themselves over the time already built-in and even some more, so they embraced it as programming language of their choice and coined the way it helps to code ideas as 'pythonic' way of programming. This is in my eyes the reason why 'pythonic' way of programming can usually be fully understood only by very experienced programmer who already went all the stages through many other programming languages to Python and use it where it is appropriate being at the same time aware, that there are purposes for which Python is not the way to go and being aware which problems other programming languages have were solved by the design of the Python language. So 'pythonic' way of programming has only a meaning for an _experienced programmer_ as intuitively easy to understand and in different context easy to reuse way of programming where the initial idea must not be bended to fit into the programming language, but where the programming language provides by own design some aid in expressing it. I don't see how Microsoft Visual Basic fits into the category of tool languages. As MS-DOS Quick Basic surely do, Visual Basic/Visual C++ need a total new understanding of programming and belong due to the very hard to grasp event driven way not allowing any workaround it to the category of Zen languages. There is the 'hidden' event handling and the way from the GUI to the code and not other way what makes Visual Basic in my eyes a Zen language where Basic, Algol, Fortran, C are tools. If it makes sense to speak about tool and Zen languages at all, I will draw the line between the two categories depending on the amount of from the programmer hidden amount of code added to his own code in order to make the program run. Assembler, as it runs entirely as it is written is sure a tool. C/C++ is also a tool, as long as it does not extensively use large libraries providing special functionality. Usage of for example C++ build upon the MFC library (Microsoft Foundation Class) makes in my eyes C++/MFC a kind of Zen language out of a C++ tool. Forth belongs according to this definition to the category of Zen languages not because it is so different, but, because you have to track in own mind, that behind the scenes the next command will use what was put on the stack before, what makes part of the processing done 'hidden' behind the scenes. From the experience of the in another thread currently going on hot discussion about Python and Lisp I draw the conclusion, that it is from todays point of view not easy to draw exact lines between the categories like tool/Zen, interpreted/compiled language. In between even making a difference between software/hardware appears to me problematic. Claudio From luis.armendariz at gmail.com Wed Feb 15 17:47:57 2006 From: luis.armendariz at gmail.com (luis.armendariz at gmail.com) Date: 15 Feb 2006 14:47:57 -0800 Subject: Attached images by plain email. In-Reply-To: <1140037314.129890.135970@o13g2000cwo.googlegroups.com> References: <1140037314.129890.135970@o13g2000cwo.googlegroups.com> Message-ID: <1140043677.756437.315080@g14g2000cwa.googlegroups.com> Hi Gaz, Perhaps this will help? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52243 From vishalm1975 at gmail.com Wed Feb 22 10:01:34 2006 From: vishalm1975 at gmail.com (vishalm1975 at gmail.com) Date: 22 Feb 2006 07:01:34 -0800 Subject: can't use NetcdfFile Message-ID: <1140617998.563835.136220@g43g2000cwa.googlegroups.com> Hi, I'm trying to open a Netcdf file using NetcdfFile but I always get an import error DLL failed even though I've tried using all these: import Numeric from Scientific.IO.NetCDF import NetCDFFile from Scientific.IO import NetCDF from Scientific import * from Scientific.IO.NetCDF import * I've got Scientific,Numeric and numpy installed I'd appreciate anyone's help Thanks Vishal. From rainbow.cougar at gmail.com Mon Feb 20 12:51:40 2006 From: rainbow.cougar at gmail.com (rainbow.cougar at gmail.com) Date: 20 Feb 2006 09:51:40 -0800 Subject: editor for Python on Linux In-Reply-To: References: Message-ID: <1140457900.354733.179780@g43g2000cwa.googlegroups.com> Mladen Adamovic wrote: > Mladen Adamovic wrote: > > I wonder which editor or IDE you can recommend me for writing Python > > programs. I tried with jEdit but it isn't perfect. > > I've got a lot of replies on this message. > In jEdit auto ident don't work OK. > > Answers like vi, emacs and gedit I won't take seriously. > For gods sake, gedit don't even have syntax highlighting (at least on > Centos 4.2). Actually gedit does have syntax highlighting and works quite well. If you put down emacs so casually you obviously have no experience with one of the most powerful text editors available. I don't use because I like the X windows editors more. Basically any editor that can insert spaces for tabs and maintain indentation level works well. For Unices: I like cooledit, besides syntax highlighting for a variety of languages, it uses python as its internal scripting language and has a powerful indent/undent feature. xcoral is good, another highly configurable editor. gedit idle ee (also know as aee) works pretty decently for maintaining tabbing vi (*not* vim, which is a travesty that doesn't even work right) if nothing else is available For M$: Idle PFE vim From nephish at xit.net Mon Feb 6 13:43:40 2006 From: nephish at xit.net (nephish at xit.net) Date: 6 Feb 2006 10:43:40 -0800 Subject: in over my head ascii References: <1139245216.350356.272170@z14g2000cwz.googlegroups.com> Message-ID: <1139251420.501345.91850@g44g2000cwa.googlegroups.com> i think like byte 1 = 'S' byte 2 = 'T' and byte 3 = 'X' still new at this, and thanks for the references -sk From john_zenger at yahoo.com Sat Feb 18 16:41:58 2006 From: john_zenger at yahoo.com (John Zenger) Date: Sat, 18 Feb 2006 16:41:58 -0500 Subject: Tab Character? In-Reply-To: <1140298494.225985.103510@g47g2000cwa.googlegroups.com> References: <1140298494.225985.103510@g47g2000cwa.googlegroups.com> Message-ID: <2KadnUmb69Y3CWrenZ2dnUVZ_tSdnZ2d@comcast.com> Tab is \t . As in: print "coke\tpepsi" tsvline.split("\t") tbonejo at gmail.com wrote: > How do I make a tab character in code to split a line read with tabs in > it? > > > Thanks. > > Tom > From jstroud at ucla.edu Thu Feb 9 21:01:20 2006 From: jstroud at ucla.edu (James Stroud) Date: Thu, 09 Feb 2006 18:01:20 -0800 Subject: Simple Tkinter app works in Linux, not in Windows In-Reply-To: <1139531183.792405.148600@o13g2000cwo.googlegroups.com> References: <1139531183.792405.148600@o13g2000cwo.googlegroups.com> Message-ID: john.orlando at gmail.com wrote: > Hello, > I'm a newbie to Python (literally, within the last two weeks), and I am > playing around with Tkinter to build some simple GUIs. I am attempting > to build a simple class that displays a GIF. Here is the code: > > #start of code > from Tkinter import * > > class DisplayPict(Frame): > > def __init__(self,parent=None): > Frame.__init__(self,parent) > self.pack() > self.img=PhotoImage(file="moon.gif") > self.can=Canvas(self) > self.can.create_image(2,2,image=self.img,anchor=NW) > self.can.pack(fill=BOTH) > > #keep a reference to the img around > self.can.photo=self.img > > if __name__ == '__main__': DisplayPict().mainloop() > #end of code > > Anyway, I started with this code in Windoze using IDLE, and everytime I > ran it I kept getting an empty frame (well, presumably with a Canvas > that had nothing in it). I kept thinking that it had to be something > to do with the whole images-get-garbage-collected-if-not-referenced > issue that I read so much about. So I tried a bunch of different > permutations and nothing made a difference. > > On a whim, I tried this code under Linux, and amazingly, it worked just > fine: the image was displayed as expected. > > So...I am confused. I tried to do my homework (i.e., read through > "Programming Python", "Learning Python", and scouring the internet), > but I can't come up with an explanation as to why this doesn't work > under Windoze. Can anyone out there show me the error in what I have? > > Thanks in advance, > John O > I'm inclined to think that its your python installation. It worked for me with both the cygwin python (both in the console and in an xterm) and it also worked for me with idle using enthought python. I haven't tried the active state python. From grante at visi.com Sat Feb 25 07:58:41 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 25 Feb 2006 12:58:41 -0000 Subject: Multiple threaded download streams? References: <1140867665.749334.210370@v46g2000cwv.googlegroups.com> Message-ID: <1200l41lq3dgu73@corp.supernews.com> On 2006-02-25, gjzusenet at gmail.com wrote: > Though Python supports threading, I think it is limited to > python code - as soon as you issue a command that uses an > external (C?) module, all of your python threads hang until > this command returns. Is that true? No. Not unless the C modules is broken. > I'm using urllib2 to download many files, and I have a double > problem: > > 1. downloading all of them is painfully slow since it's serial > - one has to finish before the next request gets sent. Then don't do it that way. > 2. my GUI becomes non responsive during the downloads - major > problem! Use a separate thread for downloading. > Is there any way to work around that? Yes. Use threads. > I want to run multiple download streams, in parallel, and while keeping > my program responsive. Then do it that way. > Are there alternative modules that I can use for that? And what, exactly, didn't work right when you tried the threading module? -- Grant Edwards grante Yow! I demand IMPUNITY! at visi.com From durumdara at gmail.com Mon Feb 6 06:13:13 2006 From: durumdara at gmail.com (Durumdara) Date: Mon, 06 Feb 2006 12:13:13 +0100 Subject: How to I write DBASE files without ODBC Message-ID: <43E72F49.9090306@gmail.com> Hi ! I have a text processor code and I want to put the results to standard files. HTML, XML, SQLite - they are ok. But I want to put these datas to DBF too, because when records are many, does not fit in Excel table (load from HTML). XML and SQLite need some development to get datas. I need some memo fields, not only standard field types. The fixed DBASE tables are simply writeable, but for memo I need some tool. ODBC is good for this, but I want to create standalone exe, without installation, and ODBC must be manually set... Can anybody known about DBASE handler module for Python ? Thanx for help: dd From arutz at mimoza.pantel.net Thu Feb 2 15:51:17 2006 From: arutz at mimoza.pantel.net (Antal Rutz) Date: Thu, 02 Feb 2006 21:51:17 +0100 Subject: Collecting snmp data - threads, processes, twisted? Message-ID: <43E270C5.6030601@mimoza.pantel.net> Hi all, I'd like to collect snmp data from varoius network devices parallel. First I tried with my own threadpool class then I gave a try to Christopher Arndt's threadpool.py (http://chrisarndt.de/en/software/python/threadpool.html). I got the same result: with one thread it finished about 2 mins with more threads it needed more and more time. Maybe I ran into the situation where threads aren't the best. I use yapsnmp (fair easy to 'snmpwalk') for collecting. it uses net-snmp. Could you give me some advice how can I make my script really parallel? My options maybe: 1. pySNMP (as it's full in python) 2. subprocess (I'd like to make (find) a solution as threadpool.py) (running yapsnmp, pySNMP or even net-snmp?...) 3. TwistedSNMP (seems too weird for me.. cannot imagine a simple solution for my problem) 4. ... thanks for your help -- --arutz From steve at REMOVETHIScyber.com.au Tue Feb 14 07:09:43 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 14 Feb 2006 23:09:43 +1100 Subject: file names longer than MAX_PATH under Windows 2003 References: Message-ID: On Tue, 14 Feb 2006 22:43:50 +1100, Steven D'Aprano wrote: > On Tue, 14 Feb 2006 14:29:44 +0300, Sergey wrote: > >> Hello. >> >> I try to open file with pathname length 282 bytes: >> E:\files\..................\something.dat >> >> On MSDN (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/naming_a_file.asp) described method to access >> files with path length >> up to 32000 bytes: just add prefix \\?\ to file name. >> But when I try to pass prefixed name to file(), I get the same result as when I don't add the prefix: file not found. May be Python >> just doesn't support long unicode filenames? >> Is there way to open such files? > > Backslashes have special meaning to Python and need to be escaped. If you > do this: > > f = file("E:\files\...\something.dat", "r") > > Python's string escape rules means you are actually trying to open the > file "E:files...something.dat" which doesn't exist. [slaps head] I seem to be a bit confused about string escaping rules. Only some backslashes have special meaning, the rest remain in the string. Sergey, you said UNICODE file names. Not just ordinary strings. Are you passing a unicode object to the function? f = file(u"E:\\files\\...\\something.dat", "r") -- Steven. From john at totalrekall.co.uk Mon Feb 6 06:02:56 2006 From: john at totalrekall.co.uk (John Dean) Date: Mon, 6 Feb 2006 11:02:56 GMT Subject: Python V2.4.2 source code References: <43e710de$0$23286$db0fefd9@news.zen.co.uk> Message-ID: <43e72b68$0$29572$da0feed9@news.zen.co.uk> Hi That particular file doesn't include the implementation files for the core modules. The platform specific directories only include two or three files. Only the Mac directory contains any C code files -- Best Regards John From ptmcg at austin.rr._bogus_.com Fri Feb 10 08:55:37 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 10 Feb 2006 13:55:37 GMT Subject: Create dict from two lists References: <1139579518.129742.265680@o13g2000cwo.googlegroups.com> Message-ID: "py" wrote in message news:1139579518.129742.265680 at o13g2000cwo.googlegroups.com... > I have two lists which I want to use to create a dictionary. List x > would be the keys, and list y is the values. > > x = [1,2,3,4,5] > y = ['a','b','c','d','e'] > > Any suggestions? looking for an efficent simple way to do this...maybe > i am just having a brain fart...i feel like this is quit simple. > > thanks. > >>> x = [1,2,3,4,5] >>> y = ['a','b','c','d','e'] >>> dict(zip(x,y)) {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} -- Paul From rtilley at vt.edu Mon Feb 27 10:54:31 2006 From: rtilley at vt.edu (rtilley) Date: Mon, 27 Feb 2006 10:54:31 -0500 Subject: spaces at ends of filenames or directory names on Win32 In-Reply-To: <1140897423.932377.304640@i39g2000cwa.googlegroups.com> References: <1140897423.932377.304640@i39g2000cwa.googlegroups.com> Message-ID: <440320B7.3010909@vt.edu> drobinow at gmail.com wrote: > Please post your Python code. I don't see the problem you're > describing. OK, here's a copy. This works on Mac/Unix/Linux yet has no effect on Windows: ----------------------------------------------------------------- import os import os.path for root, dirs, files in os.walk(os.getcwd()): for d in dirs: new_d = d.strip() ## Uncomment the next 4 lines just to print dirs with end spaces. ## if new_d != d: ## print d ## else: ## print "No end spaces." ## Uncomment the next 7 lines to try a rename of dirs with end spaces. ## if new_d != d: ## try: ## new_path = os.path.join(root, new_d) ## old_path = os.path.join(root, d) ## os.renames(old_path, new_path) ## except Exception, e: ## print e ------------------------------------------------------------------ From peter at engcorp.com Sat Feb 18 09:47:49 2006 From: peter at engcorp.com (Peter Hansen) Date: Sat, 18 Feb 2006 09:47:49 -0500 Subject: Difference: __iadd__ and __add__ In-Reply-To: <1140242247.989089.43460@f14g2000cwb.googlegroups.com> References: <1140228134.408383.182270@o13g2000cwo.googlegroups.com> <1140242247.989089.43460@f14g2000cwb.googlegroups.com> Message-ID: Jonathan Gardner wrote: > I would like to point out that it isn't entirely obvious where to find > documentation for this particular thing. I know from experience where > to go, but I remember spending a long time trying to hunt this down. I'd like to point out it should be obvious, at least as far as going to http://docs.python.org and typing "__iadd__" into the Search field in the upper right should be an obvious first step... > For reference, you may want to check out the index of the language > reference manual. > > http://www.python.org/doc/2.4.2/ref/genindex.html That one is the second hit in those results... (It does seem to require reading a few of those pages to learn enough to answer the original question. To be fair, I didn't find (in a few minutes) any page that explicitly states what tomerfiliba at gmail.com said, about += falling back to __add__ if __iadd__ is not defined, though I didn't try searching for it directly.) -Peter From bpeng at rice.edu Fri Feb 24 10:59:15 2006 From: bpeng at rice.edu (Bo Peng) Date: Fri, 24 Feb 2006 09:59:15 -0600 Subject: Module written in C does not repond to Ctrl-C interruption. Message-ID: Dear list, I have not done a thorough test, but it occurs to me that 1. python code can be interrupted by Ctrl-C. 2. A C module, if I add a main() function and run independently, can be interrupted by Ctrl-C. 3. If I load the C module in python and run, the program will not respond to Ctrl-C interruption. I have to kill python explicitly. If this is a known behavior or just a special case of mine? Any fix to it? I am using python 2.3.4 under Redhat EL4 with gcc 3.3.4. Many thanks in advance. Bo From grahn+nntp at snipabacken.dyndns.org Sat Feb 11 15:00:19 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 11 Feb 2006 20:00:19 GMT Subject: Is there any books such as 'effective python' or else about the performance? References: Message-ID: On Sat, 11 Feb 2006 07:54:46 -0600, Charles Krug wrote: > On 2006-02-11, Kenneth Xie wrote: >> att, thx. > > A lot of the ideas discussed in Effective C++ et al are things that > Python does for us already. C++ works at a much lower layer of > abstraction Yes. > and you need to deal explicitly with freestore for any > nontrivial class. Not true. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From aleaxit at yahoo.com Sat Feb 4 10:33:14 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Feb 2006 07:33:14 -0800 Subject: OO conventions References: <1138888210.827054.68690@g49g2000cwa.googlegroups.com> <5f56302b0602020904h4a130392kf0a8730f5a53d097@mail.gmail.com> Message-ID: <1ha846s.1pnjkg2cjc961N%aleaxit@yahoo.com> Daniel Nogradi wrote: ... > So after all, what is a 'factory' or 'factory function'? A brief explanation in Python terms is at http://www.aleax.it/ep03_pydp.pdf -- "pages" (slides) 37-44 (the rest of the presentation is about an even more fundamental design pattern, "template method"). A far more extensive essay can be found, for example, at http://gsraj.tripod.com/design/creational/factory/factory.html -- it names the pattern "factory method", not "factory function" ("method" is probably a more widespread name for it) and presents examples in Java and Corba IDL. Anyway, trying to summarize: - "what": any function or method or other callable whose task it is to build and return new objects can be called "a factory"; - sometimes a factory may get away with returning an existing object for recycling "as if" it was a new one, saving some resources, and this is one advantage; - a factory may choose what exact type of object to build and return based on arguments or other circumstances, and this is a second advantage. "Program to an interface, not to an implementation" -- the key underlying principle ot the gang of 4's "Design Patterns" book. If you build an object of a specific given type ("new Foo" in Java or C++), you're hardwiring the choice of implementation (the exact concrete type); delegating the building to a method or function frees your application from such hardwiring and lets it be concentrated (if needed at all) in one spot (the factory). [[With the "registry" pattern you may even be able to remove any hardwiring, but that's a pretty advanced and subtle idea]]. Alex From girodt at gmail.com Tue Feb 14 20:42:58 2006 From: girodt at gmail.com (Thomas Girod) Date: 14 Feb 2006 17:42:58 -0800 Subject: listing attributes In-Reply-To: References: <1139884643.749492.221140@g43g2000cwa.googlegroups.com> Message-ID: <1139967778.838793.258190@f14g2000cwb.googlegroups.com> You are right, using __dict__ is what i needed. But I chose the solution explained before because i don't want to list all attributes of the object, only attributes that are instances of the class Property (or a subclass of it). From mrstephengross at hotmail.com Fri Feb 17 12:10:58 2006 From: mrstephengross at hotmail.com (mrstephengross) Date: 17 Feb 2006 09:10:58 -0800 Subject: Another simple freeze question Message-ID: <1140196258.624634.54210@g44g2000cwa.googlegroups.com> Is there a user manual for freeze.py? --Steve (mrstephengross at hotmail.com) From johnjsal at NOSPAMgmail.com Wed Feb 22 15:43:38 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 22 Feb 2006 20:43:38 GMT Subject: a little more help with python server-side scripting In-Reply-To: References: <59edncmGm6g2LmbeRVn-pw@rcn.net> Message-ID: <_14Lf.1655$No6.38835@news.tufts.edu> Steve Holden wrote: > OK, what you need to ask them is whether they have installed Python as > an Active Scripting language. If they have then you can use it pretty > much like VBscript. Here's there latest: ---------- Please note that it is possible for the server to recognize bits of Python code that are embedded within an HTML file. However, it will need a custom mapping on the domain for mapping .html to the Python executable on the server. But note that after mapping .html will no longer be call as normal html file to be loaded on the browser as the IIS server now will parse .html with the Python executable engine. Your user will need to embed the Python coding into each of the .html file in order for it to be load properly on the browser. ------------ Does that answer the question about active scripting language? From reply.in.the.newsgroup at my.address.is.invalid Mon Feb 20 06:20:54 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 20 Feb 2006 12:20:54 +0100 Subject: Regular expression gone mad References: <1140432942.392985.148820@z14g2000cwz.googlegroups.com> Message-ID: fileexit: >(Search finds nothing) > >>>> a=r"MemT" >>>> pat = re.compile(a) >>>> m=pat.search(ProcMem, re.DOTALL) >>>> m >From the docs: "Compiled regular expression objects support the following methods and attributes: match( string[, pos[, endpos]])" Your re.DOTALL is seen as start position. That's why it's probably matching 'MemFree' instead of 'MemTotal'. -- Ren? Pijlman From fn-mail at t-online.de Sun Feb 5 11:14:33 2006 From: fn-mail at t-online.de (Florian Nykrin) Date: Sun, 05 Feb 2006 17:14:33 +0100 Subject: Learning Python In-Reply-To: <1139154754.099716.71300@f14g2000cwb.googlegroups.com> References: <1139154754.099716.71300@f14g2000cwb.googlegroups.com> Message-ID: Hi Byte! Your code should look like this: x = raw_input('Please enter your name: ') if x == 'myself': print 'OK' Because myself should be a string and not a variable name, you have to put it in quotes. Regards, Florian. From kkranabetter at yahoo.com Thu Feb 9 14:04:34 2006 From: kkranabetter at yahoo.com (Kelly) Date: Thu, 09 Feb 2006 19:04:34 GMT Subject: Inserting record with Microsoft Access References: Message-ID: "jeffhg582003" wrote in news:mailman.1648.1139475091.27775.python-list at python.org: > fields. I am trying to capture the number generated from the insert but > I am not exactly sure how to do that after an insert. Other folks have pointed you to "select @@identity" but I thought I should mention that if you use ADO with the AddNew method then autonumbers are magically retrieved. Something like this should work: rs.AddNew() rs.Fields("somefield").Value= "Blah" rs.Update() print "Autonumber is", rs.Fields("TheAutonumberField").Value This didn't always work so ADO and the MDB can't be ancient versions. SQL Server will also do this but the recordset must be opened with: rs.CursorLocation= constants.adUseServer rs.Open("Tablename", conn, constants.adOpenKeyset, constants.adLockOptimistic) From fredrik at pythonware.com Sun Feb 5 11:38:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 5 Feb 2006 17:38:55 +0100 Subject: Learning Python References: <1139154754.099716.71300@f14g2000cwb.googlegroups.com> <1139156577.897100.69140@g43g2000cwa.googlegroups.com> Message-ID: Byte wrote: > p.s. Xavier Morel, you seem to be using Windows, not Linux what makes you think that basic Python functions work in radically different ways on different platforms ? From epost2 at gmail.com Sun Feb 12 11:51:59 2006 From: epost2 at gmail.com (epost2 at gmail.com) Date: 12 Feb 2006 08:51:59 -0800 Subject: Newbie References: Message-ID: <1139763119.480391.210910@g43g2000cwa.googlegroups.com> This is a good place for posting questions about programming in python. However, if you are a newbie, your questions are most likely already answered. I recommend searching in this groups archives reading the python tutorial http://docs.python.org/tut/tut.html reading http://www.byteofpython.info/read/ This one is frequently recommended for newbies: reading www.diveintopython.org This book is recommended also for those who have programming experience. If you can`t find the answer to your question from the above, feel free to post in this group LittlePython skrev: > Is this a good place to post python questions from newbie's, or would you > suggest another board? > Thx From apgwoz at gmail.com Thu Feb 16 09:34:18 2006 From: apgwoz at gmail.com (Andrew Gwozdziewycz) Date: Thu, 16 Feb 2006 09:34:18 -0500 Subject: ANN: FreeImagePy 1.2.2 In-Reply-To: References: <43f43ec3$0$29107$5fc30a8@news.tiscali.it> Message-ID: <8ba244fb0602160634l799f3adevbe6e67ae9db338be@mail.gmail.com> > Knowing some details about PIL and as good as no details about > FreeImage, I would like in this context to become enlightened by the > answer to the question, when does it make sense to use FreeImage instead > of PIL? > From what I know up to now I can't see any use for FreeImage :-( . both freeimagepy and freeimage are released under the GPL, PIL is not. -- Andrew Gwozdziewycz http://ihadagreatview.org http://plasticandroid.org From erniedude at gmail.com Tue Feb 7 16:02:18 2006 From: erniedude at gmail.com (Ernesto) Date: 7 Feb 2006 13:02:18 -0800 Subject: tricky regular expressions Message-ID: <1139343779.721205.221410@f14g2000cwb.googlegroups.com> So regular expressions have been good to me so far, but now my problem is a bit trickier. The string I'm getting data from looks like this: myString = [USELESS DATA] Request : Play [USELESS DATA] Title: Beethoven's 5th [USELESS DATA] Request : next [USELESS DATA] Title: song #2 ..... I'm using this code to search myString: .... pattern = '''(?x) Title:\s+(.+) ''' Titles = re.findall(pattern, myString) .... The problem is that I only want the "Titles" which are either: a) Followed by "Request : Play" b) Followed by "Request : next" I'm not sure if I should use RE's or some other mechanism. Thanks From onurb at xiludom.gro Fri Feb 3 12:47:04 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 03 Feb 2006 18:47:04 +0100 Subject: Compiling In-Reply-To: References: <43e392d1$0$31853$626a54ce@news.free.fr> Message-ID: <43e3972f$0$624$626a14ce@news.free.fr> Simon Faulkner wrote: >>> I love Python for it's ease and speed of development especially for the >>> "Programming Challenged" like me but why hasn't someone written a >>> compiler for Python? >> >> >> >> But there *is* a compiler for Python. >> http://www.python.org/doc/2.4.2/lib/module-compiler.html > > > ty Bruno, I must confes that I don't understand much of that chapter! > > I will work harder... :-) > Hint : You probably don't need to understand anything in this chapter. This compiler compiles Python source code to Python bytecode, which is then executed by the Python interpreter. You may not have noticed - since the Python interpreter is smart enough to call the compiler when needed - but Python is compiled to bytecode before execution. Just look at all the .pyc files on your filesystem. For short : this was kind of a joke... I understand that what you were looking for is a 'native code' compiler. AFAIK, this could of course be done, but due to Python's very dynamic nature, it's not sure this would lead to drastically better performances. HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From nephish at xit.net Mon Feb 6 15:13:37 2006 From: nephish at xit.net (nephish at xit.net) Date: 6 Feb 2006 12:13:37 -0800 Subject: in over my head ascii In-Reply-To: <1139251420.501345.91850@g44g2000cwa.googlegroups.com> References: <1139245216.350356.272170@z14g2000cwz.googlegroups.com> <1139251420.501345.91850@g44g2000cwa.googlegroups.com> Message-ID: <1139256817.218319.160370@f14g2000cwb.googlegroups.com> ok, part of what i have to do is know how many bytes will be sent. in ascii is it one byte per character ? like "password" would be 8 bytes long? From paul at boddie.org.uk Fri Feb 3 13:03:08 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 3 Feb 2006 10:03:08 -0800 Subject: Compiling References: <1138989575.503830.197820@g47g2000cwa.googlegroups.com> Message-ID: <1138989787.980000.142070@o13g2000cwo.googlegroups.com> Oh, and I forgot another Aycock creation: UCPy [16]. Paul [16] http://pages.cpsc.ucalgary.ca/~aycock/papers/ucpy.pdf From robert.kern at gmail.com Sat Feb 18 14:40:09 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 18 Feb 2006 13:40:09 -0600 Subject: Numpy for PythonCE In-Reply-To: References: Message-ID: "G???????????????????????????????????????" wrote: > Hi, > is there a version of Numpy (or Numarray) available > that is compatible to PythonCE 2.3? I haven't heard of anyone trying. Perhaps you could try compiling the latest SVN of numpy and tell us how it goes on numpy-discussion at lists.sourceforge.net . -- Robert Kern robert.kern at gmail.com "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From nogradi at gmail.com Sat Feb 4 09:00:29 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 4 Feb 2006 15:00:29 +0100 Subject: OO conventions In-Reply-To: <5f56302b0602020904h4a130392kf0a8730f5a53d097@mail.gmail.com> References: <1138888210.827054.68690@g49g2000cwa.googlegroups.com> <5f56302b0602020904h4a130392kf0a8730f5a53d097@mail.gmail.com> Message-ID: <5f56302b0602040600s22aa718bwced7fd9f327bf551@mail.gmail.com> > > Actually, this way of creating a class instance is good OO practice in > > many places: The Image.open() method acts as a factory-function for > > creating Image objects. > > You don't know, until you inspect the return value, if the created > > object is actually an instance of class Image or something which just > > happens to behave like one... > > It could for instance be a sub-class of Image, JpegImage, if that > > better suits the class library designers. > > In general, factory-functions allow greater uncoupling between > > interface and implementation. > > > > From all the enlightening replies it seems to me that my next task > should be to look into what 'factory functions' are. Whenever I've > seen the word 'factory' I just skipped it, knowing that if I really > need to know what it is, I'll come back to it later. Apparently it's > just about time, thanks all for the comments. > I've been looking around for what factory functions are, but honestly I've been grepping and googling but couldn't find a clear definition of the concept of 'factory', 'factory function' or 'class factory'. As I've said I'm relatively new to OOP and the reason is that for too long I thought that there is no need for it, ordinary C will do. But once the concepts became clear, it started to become useful. That's why I'm not particularly interested in examples and code snippets but rather the general ideas and their definitions, but for these 'factories' I really couldn't find a clear explanation anywhere only how to use them, example code and such. Perhaps because I was only searching in the context of Python. So after all, what is a 'factory' or 'factory function'? From dbough77 at yahoo.com Thu Feb 23 18:37:19 2006 From: dbough77 at yahoo.com (DannyB) Date: 23 Feb 2006 15:37:19 -0800 Subject: Concantenation and string slicing In-Reply-To: <1140737092.542387.178050@i39g2000cwa.googlegroups.com> References: <1140735316.752278.298490@v46g2000cwv.googlegroups.com> <1140737092.542387.178050@i39g2000cwa.googlegroups.com> Message-ID: <1140737839.117053.73290@e56g2000cwe.googlegroups.com> Wow - thats simple =). Thanks a ton!! From rick at localhost.localdomain Sun Feb 5 13:39:18 2006 From: rick at localhost.localdomain (Rick Spencer) Date: Sun, 05 Feb 2006 10:39:18 -0800 Subject: what's wrong with my popen reasoning? Message-ID: Hi all, I am very new to Python programming. I am writing a program to manage wireless connections, this is for GNOME on Linux. I present the user with a "connect" button. I want to handle the connection for them slightly different depending on whether or not the wireless access point they are trying to connect to is secure. In either case, I have a similar question. In the first case, the wireless access point is secured. I want to bring up the GNOME applet for configuring a wireless access interface. I can pass the command line commands to bring it up, but I can't figure out how to bring it up in a modal fashion, so that my Python program waits for the user to dismiss it before my program gets control again. In the second case, the access point is not secured. I just want to fire off the command line utility (iwconfig) for connecting. In this case, I want my program to wait until iwconfig is done before continuing on. I figure that I could just write a line of code to read in from the console, but I thought there might be a more pythonic way of doing it. Here's my function so far, with variables replaced with constants to make it easier to read: def connect_clicked(self, widget, data=None): if locked: os.popen("sudo network-admin -c ath0") self.emit('connection-attempted', "ath0") else: os.popen("sudo iwconfig ath0 ap 00:0F:B3:31:CB:01") self.emit('connection-attempted', "ath0") Thanks much! Cheers, Rick From sjstreat2002 at yahoo.com Thu Feb 23 19:21:51 2006 From: sjstreat2002 at yahoo.com (S Streat) Date: Thu, 23 Feb 2006 16:21:51 -0800 (PST) Subject: Help with questor Message-ID: <20060224002151.72495.qmail@web32805.mail.mud.yahoo.com> I am new to python and computer programming. I am trying to save the questor.py file so that it retains it's data. My problem is that I don't really understand how to do it. I have been reviewing tutorials and I have gotten this far, but the data still doesn't save. Can someone tell me what it is I am overlooking? # questor.py # define some constants for future use kQuestion = 'question' kGuess = 'guess' # define a function for asking yes/no questions def yesno(prompt): ans = raw_input(prompt) return (ans[0]=='y' or ans[0]=='Y') # define a node in the question tree (either question or guess) class Qnode: # initialization method def __init__(self,guess): self.nodetype = kGuess self.desc = guess def retrieve(self, file): self.desc = file.readline().rstrip() self.nodetype = file.readline().rstrip() if self.nodetype == kQuestion: slef.nodes = {0:Qnode(''), 1:Qnode('')} retrieve(self.nodes[0], file) retrieve(self.nodes[1], file) return def save(self, file): file.write(self.desc + "\n") file.write(self.nodetype + "\n") if self.nodetype == kQuestion: save(self.nodes[0], file) save(self.nodes[1], file) return # get the question to ask def query(self): if (self.nodetype == kQuestion): return self.desc + " " elif (self.nodetype == kGuess): return "Is it a " + self.desc + "? " else: return "Error: invalid node type!" # return new node, given a boolean response def nextnode(self,answer): return self.nodes[answer] # turn a guess node into a question node and add new item # give a question, the new item, and the answer for that item def makeQuest( self, question, newitem, newanswer ): # create new nodes for the new answer and old answer newAnsNode = Qnode(newitem) oldAnsNode = Qnode(self.desc) # turn this node into a question node self.nodetype = kQuestion self.desc = question # assign the yes and no nodes appropriately self.nodes = {newanswer:newAnsNode, not newanswer:oldAnsNode} def traverse(fromNode): # ask the question yes = yesno( fromNode.query() ) # if this is a guess node, then did we get it right? if (fromNode.nodetype == kGuess): if (yes): print "I'm a genius!!!" return # if we didn't get it right, return the node return fromNode # if it's a question node, then ask another question return traverse( fromNode.nextnode(yes) ) def run(): # start with a single guess node try: f = open('c:\nodetree.txt', 'r') cont = f.readlines() known = cont.count('guess\n') del cont f.seek(0) topNode = Qnode('') retrieve(topNode, f) f.close() except: topNode = Qnode('python') known = 1 done = 0 while not done: # ask questions till we get to the end result = traverse( topNode ) # if result is a node, we need to add a question if (result): item = raw_input("OK, what were you thinking of? ") print "Enter a question that distinguishes a", print item, "from a", result.desc + ":" q = raw_input() ans = yesno("What is the answer for " + item + "? ") result.makeQuest( q, item, ans ) print "Got it." # repeat until done print done = not yesno("Do another? ") print # immediate-mode commands, for drag-and-drop or execfile() execution if __name__ == '__main__': run() print raw_input("press Return>") else: print "Module questor imported." print "To run, type: questor.run()" print "To reload after changes to the source, type: reload(questor)" # end of questor.py --------------------------------- Relax. Yahoo! Mail virus scanning helps detect nasty viruses! -------------- next part -------------- An HTML attachment was scrubbed... URL: From codecraig at gmail.com Sun Feb 19 17:17:11 2006 From: codecraig at gmail.com (abcd) Date: 19 Feb 2006 14:17:11 -0800 Subject: Format file size for printing Message-ID: <1140387431.610729.48700@o13g2000cwo.googlegroups.com> is there a built-in way of printing the size of a file nicely? So if the file size is 103803 bytes it prints out like: 103.8K or 0.1MB something liek that? From sw at wordtech-software.com Sat Feb 11 12:24:34 2006 From: sw at wordtech-software.com (Kevin Walzer) Date: Sat, 11 Feb 2006 12:24:34 -0500 Subject: Yet another GUI toolkit question... In-Reply-To: References: <9eae7$43ed2ce5$4275d90a$5719@FUSE.NET> Message-ID: <43EE1DD2.7040009@wordtech-software.com> Peter Decker wrote: > On 2/10/06, Kevin Walzer wrote: > >> I'm undertaking my first semi-substantial Python GUI application after a >> long time dabbling with the language. >> > ... >> So: my question is, would it be more productive for me to wrestle with >> these extensions when there doesn't seem to be much constituency for >> their use, or would it be better/faster/more efficient for me to start >> scaling the wxPython mountain? > > If you're going cross-platform, then wxPython is the toolkit to use. > It looks and works correctly on all platforms. > > I worked with wxPython for a couple of years, and constantly struggled > with the ugle, C++ style syntax, and then discovered Dabo. Dabo is a > full 3-tier application framework, and its UI tier wraps wxPython. So > while you're using wxPython when you use dabo.ui, you're writing > clean, Pythonic code. I found that after playing around with Dabo for > a little bit, I could write apps that worked without constantly going > to the docs to look up some obscure constant or event name. The > authors are also extremely helpful, so if write your app using Dabo, > I'm sure that you'll have tons of support. > > http://dabodev.com > > -- > > # p.d. Dabo looks interesting, but isn't it mainly for database applications? Has any other kind of application been developed with it? Also, it seems very Windows/Linux-centric. Is anyone using it on OS X? -- Kevin Walzer iReveal: File Search Tool http://www.wordtech-software.com From eels at nikocity.de Tue Feb 7 06:29:19 2006 From: eels at nikocity.de (eels) Date: 7 Feb 2006 03:29:19 -0800 Subject: ftp: get list of files Message-ID: <1139311759.603645.13790@f14g2000cwb.googlegroups.com> Hello, I want to get a listing of my files at web server with ftp. I wantn 't download the files. With yyy = ftp.retrlines('LIST') I get this listing at stdout, but I need this information at variable yyy. How can I resolve this problem? Thank's for your hints, Thomas From steve at holdenweb.com Sat Feb 4 10:09:05 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 04 Feb 2006 15:09:05 +0000 Subject: OO conventions In-Reply-To: <5f56302b0602040600s22aa718bwced7fd9f327bf551@mail.gmail.com> References: <1138888210.827054.68690@g49g2000cwa.googlegroups.com> <5f56302b0602020904h4a130392kf0a8730f5a53d097@mail.gmail.com> <5f56302b0602040600s22aa718bwced7fd9f327bf551@mail.gmail.com> Message-ID: Daniel Nogradi wrote: [...] > So after all, what is a 'factory' or 'factory function'? The name is intended to be indicative: it's a function that makes things - usually instances of some class. As has already been pointed out. Image is a module from PIL, so Image.open() is a function in that module. When you call it, it creates an instance of some suitable image class (which will depend on the type of the image) and returns that. The point here is that Image.open() returns a JpegImagePlugin.JpegImageFile instance for a .jpg file, a GifImagePlugin.GifImageFile instance for a .gif file, and so on. It wouldn't make sense to use a single class to represent all these different image types, so Image.open() just creates an instance of the appropriate class (whatever that may be, which will vary from call to call) and returns that. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From lycka at carmen.se Fri Feb 10 04:59:04 2006 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 10 Feb 2006 10:59:04 +0100 Subject: Question about idioms for clearing a list In-Reply-To: References: <1139231464.914400.37100@g44g2000cwa.googlegroups.com> <43E7F59B.9070009@REMOVEMEcyber.com.au> <1139300825.858426.12680@o13g2000cwo.googlegroups.com> Message-ID: Bryan Olson wrote: > Magnus Lycka wrote: >> Do you really have a usecase for this? It seems to me that your >> argument is pretty hollow. > > Sure: > > if item_triggering_end in collection: > handle_end(whatever) > collection.clear() > > Or maybe moving everything from several collections into > a single union: > > big_union = set() > for collection in some_iter: > big_union.update(t) > collection.clear() I don't understand the second one. Where did 't' come from? Anyway, tiny code snippets are hardly usecases. Are these from real code? If they are, why aren't there support for emptying lists? Have you patched your Python? Didn't you actually need to support lists? I still don't see any convincing usecase for the kind of ducktyping you imply. There are certainly situations where people have used lists or dicts before there were sets in Python, and want to support both variants for a while at least, but since their APIs are so differnt for these types, .clear() seems like a non-issue. If this was a problem in the real world, I bet we'd see a lot of code with functions similar to this: def clear(container): try: del container[:] except TypeError: container.clear() If you *do* have this problem, this is a very simple workaround. >> As far as I understand, the only operation which is currently used >> by all three collections is .pop, but that takes a different number >> or parameters, since these collections are conceptually different! > > The all support len, iteration, and membership test. Ok. Forgot that. id(), str() and repr() as well. Still, after almost 10 years of Python programming I can't remember that I ever ran into a situation where I ever needed one single piece of code to empty an arbitrary container. It's trivial to solve, so I wouldn't have stopped to think about it for even a minute if it happened, but I still don't think it happened.This was never a problem for me, and I don't think I saw anyone else complain about it either, and I've seen plenty of complaints! ;) I can understand the argument about making it easy to remember how to perform an action. I think the current situation is correct. To introduce redunancy in this case (del x[:] <==> x.clear()) would not be an improvement of Python. In the long run, such a strategy of synonyms would make Python much more like Perl, and we don't want that. So I can understand that the question pops up though (but not why it gets such proportions). I don't buy this duck-typing argument though. Considering how little it would change in unifying these divergent APIs, it still sounds as hollow to me. > Many algorithms make sense for either sets or lists. Even if they > cannot work on every type of collection, that's no reason not > to help them be as general as logic allows. >>> class BryansList(list): ... add=list.append ... def clear(self): ... del self[:] ... >>> b = BryansList([1,2,3,4,5]) >>> b [1, 2, 3, 4, 5] >>> b.add(6) >>> b.clear() >>> b [] Happy now? You can keep it, I don't need it. :) Most of us consider minimal interfaces a virtue. From michaeltaft at gmail.com Sun Feb 12 20:40:21 2006 From: michaeltaft at gmail.com (mwt) Date: 12 Feb 2006 17:40:21 -0800 Subject: Downloading Large Files -- Feedback? In-Reply-To: <43EFDB34.80103@REMOVEMEcyber.com.au> References: <1139773494.245577.102870@g47g2000cwa.googlegroups.com> <7x3bioxrnj.fsf@ruckus.brouhaha.com> <1139780009.673785.51270@g14g2000cwa.googlegroups.com> <43EFDB34.80103@REMOVEMEcyber.com.au> Message-ID: <1139794821.875941.39230@g14g2000cwa.googlegroups.com> >It isn't written in C, but get your hands on wget. It >is probably already on your Linux distro, but if not, >check it out here: >http://www.gnu.org/software/wget/wget.html Thanks. I'm checking it out. From bokr at oz.net Tue Feb 7 10:42:32 2006 From: bokr at oz.net (Bengt Richter) Date: Tue, 07 Feb 2006 15:42:32 GMT Subject: Detecting line endings References: <1139236514.022464.319970@g14g2000cwa.googlegroups.com> Message-ID: <43e8bb1e.177822094@news.oz.net> On 6 Feb 2006 06:35:14 -0800, "Fuzzyman" wrote: >Hello all, > >I'm trying to detect line endings used in text files. I *might* be >decoding the files into unicode first (which may be encoded using >multi-byte encodings) - which is why I'm not letting Python handle the >line endings. > >Is the following safe and sane : > >text = open('test.txt', 'rb').read() >if encoding: > text = text.decode(encoding) >ending = '\n' # default >if '\r\n' in text: > text = text.replace('\r\n', '\n') > ending = '\r\n' >elif '\n' in text: > ending = '\n' >elif '\r' in text: > text = text.replace('\r', '\n') > ending = '\r' > > >My worry is that if '\n' *doesn't* signify a line break on the Mac, >then it may exist in the body of the text - and trigger ``ending = >'\n'`` prematurely ? > Are you guaranteed that text bodies don't contain escape or quoting mechanisms for binary data where it would be a mistake to convert or delete an '\r' ? (E.g., I think XML CDATA might be an example). Regards, Bengt Richter From hancock at anansispaceworks.com Sun Feb 19 12:59:58 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 19 Feb 2006 11:59:58 -0600 Subject: ANN: FreeImagePy 1.2.2 In-Reply-To: <8ba244fb0602160634l799f3adevbe6e67ae9db338be@mail.gmail.com> References: <43f43ec3$0$29107$5fc30a8@news.tiscali.it> <8ba244fb0602160634l799f3adevbe6e67ae9db338be@mail.gmail.com> Message-ID: <20060219115958.05238d31@samwise.anansi> On Thu, 16 Feb 2006 09:34:18 -0500 Andrew Gwozdziewycz wrote: > > Knowing some details about PIL and as good as no details > > about FreeImage, I would like in this context to become > > enlightened by the answer to the question, when does it > > make sense to use FreeImage instead of PIL? > > From what I know up to now I can't see any use for > > FreeImage :-( . > > both freeimagepy and freeimage are released under the GPL, > PIL is not. This is misleading! The PIL license is GPL-compatible (i.e. it could be incorporated into a GPL work), as it is a non-copyleft free license. You may be confused by Lundh's proprietary-then-free release strategy: he always releases a newer version under a proprietary license, at which point the old version is free-licensed. But the old version is completely without strings -- you could, if you wanted, try to give Mr. Lundh "a run for his money" by extending PIL faster than he can. Not exactly "cricket", but legal. ;-) However, while PIL is very strong at image-manipulation, it is weak on file-format compatibility: As long as you stick to PNG format, you can do just about anything you want (and there is decent JPG and GIF support). But if you have compelling reasons to output data in other formats, you'll find PIL disappointing -- there are many formats it can't deal with at all, and most of the rest it can only import (in the wild, there are *dozens* of obscure image formats to be found). IMHO, this isn't too serious an issue -- it's just specialization: PIL is for *image manipulation* not *image conversion*, and it provides enough of the latter for the most common applications. Other choices include ImageMagick, but API stability, particularly of the Python bindings, is a real problem (in fact, I think there's more than one python binding for ImageMagick, but I'm not sure -- which goes some way to showing why it's a frustrating package to use). Things may have improved lately, I haven't checked in awhile. So, IMHO, there's still PLENTY of room for innovation in the application area of image-handling tools for Python. PIL is not a "category-killer". At least not yet. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From bokr at oz.net Fri Feb 10 19:03:57 2006 From: bokr at oz.net (Bengt Richter) Date: Sat, 11 Feb 2006 00:03:57 GMT Subject: module with __call__ defined is not callable? References: Message-ID: <43ed269d.467485969@news.oz.net> On Thu, 9 Feb 2006 10:07:49 +1100, "Delaney, Timothy (Tim)" wrote: >Steven D'Aprano wrote: > >> That's not a _reason_, it is just a (re-)statement of fact. We know >> that defining a __call__ method on a module doesn't make it callable. >> Why not? The answer isn't "because defining a __call__ method on a >> module or an instance doesn't make it callable", that's just avoiding >> the question.=20 > >My reading of the OP sounded like he wanted to know the *technical* >reason for why it doesn't work - which is what I provided. > >If you can come up with a convincing argument, after re-reading the OP >(as I've just done), that that is *not* what he meant, I'm all ears. > While you can't put __call__ on the builtin module type, you _can_ put it on a subclass: >>> class M(type(__builtins__)): ... def __call__(self): return '%r was called'%self ... >>> m = M('M') >>> m() " was called" Not that I can see why the OP would want to spell any module access module(). OTOH, I could see wanting to define properties, and access module.latest_foo and have it choose dynamically from versioned stuff, or something like that. Of course you can write module.get_latest_foo() as an ordinary function, and not be bothered with subclassing and jimmying sys.modules and such. Properties and methods are both forms of descriptors, so they need to be attributes of the type to work. With a subclass you could do that too. Regards, Bengt Richter From steve at holdenweb.com Mon Feb 13 00:25:00 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Feb 2006 00:25:00 -0500 Subject: ordered sets operations on lists.. In-Reply-To: <1139807477.28916.7.camel@kenshin> References: <1139592166.993686.212000@f14g2000cwb.googlegroups.com> <1139599834.975607.77180@f14g2000cwb.googlegroups.com> <1halbdx.dd0p1l1obawfkN%aleaxit@yahoo.com> <43ef8e5f.625119424@news.oz.net> <1hana3d.1bwbt4c1esela5N%aleaxit@yahoo.com> <43F007F9.3090103@holdenweb.com> <1139805374.7547.24.camel@kenshin> <1139807477.28916.7.camel@kenshin> Message-ID: Felipe Almeida Lessa wrote: > Em Dom, 2006-02-12 ?s 23:51 -0500, Steve Holden escreveu: > >>The basic answer is that so far no developer has felt it worthwhile to >>expend time on adding these optimizations. > > > I always thought these small optimizations could lead Python to be > faster overall. I remember about this every time I see CPython vs. > IronPython benchmarks (.NET and Mono do some nice optimizations at > compile and run times). > Indeed it is true that on some benchmarks IronPython is faster than CPython. I suspect this was helped by the fact that IronPython is Jim's third implementation of Python (I believe he was familiar with CPython before he started on Jython, formerly known as JPython). The fact remains that until someone writes the code it can't be included in the implementation. Performance optimization, unfortunately, doesn't have the same glamorous cachet as more esoteric language features. > >>>Also, IIRC Psyco does optimize these constant expressions. Or am I >>>wrong? >>> >> >>Psyco does some very advanced things, but it does them all at run-time. >>Unless I misunderstand (not unheard of), there are no circumstances >>under which Psyco will improve run-time for a piece of code that is only >>executed once. > > > Sorry, I think I should have been clearer. Yes, Psyco only helps at > runtime (when the function is called), but those constant folds only > practically help on parts of the code that are called many times anyway, > right? > Right. Technically constant folding is a win for a single execution, but only if you don't take the slightly-increased compile time into account :-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From gh at ghaering.de Tue Feb 21 05:15:39 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 21 Feb 2006 11:15:39 +0100 Subject: Little tool - but very big size... :-( In-Reply-To: <43FAE06E.3090301@gmail.com> References: <1140513852.240140.144160@f14g2000cwb.googlegroups.com> <43FAE06E.3090301@gmail.com> Message-ID: <43FAE84B.7060703@ghaering.de> Durumdara wrote: > Hi ! > > Yes, it is. But that tool is designed for USB PenDrive usage. > The assessor is collect all tools it needed to see a machine(s) in the > checked corporation. > He/she needs little programs, because he need to store the results of > the checkings too, not the tools only. [...] Additional Python or wxPython tools packed using py2exe will only need a few kilobytes if you all copy them to the same directory on the pen drive. All these tools can share the same .pyd and .dll files. -- Gerhard From ivoras at __yahoo__.com_ Tue Feb 7 14:51:59 2006 From: ivoras at __yahoo__.com_ (Ivan Voras) Date: Tue, 07 Feb 2006 20:51:59 +0100 Subject: threads and memory In-Reply-To: References: Message-ID: Lee Leahu wrote: > However, I have encountered the following error after I have started my 381st thread: This number (actually, ~380) is suspicious when seen with threads because it almost always means running out of process address space. As threads are part of a single process, and that process has (usually today) 32bit address space, and modern Linux systems allocate huge amounts of memory per-thread (8 MB for threads' stack!), and the kernel reserves ~1MB in the address space for itself, you can easily reach > 4GB of total allocated memory. This *doesn't* mean you are actually using 4GB of memory (i.e. storing values to it), only that the process gets "assigned" this memory. Python doesn't support specifying thread attributes AFAIK, so you should find a way to specify default thread stack size, possibly with an environment variable (see manual page for "pthread" library calls). Try 64k - your task seems simple enough :) From oliphant.travis at ieee.org Mon Feb 6 13:29:49 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Mon, 06 Feb 2006 11:29:49 -0700 Subject: Scientific Computing with NumPy In-Reply-To: References: <1139229403.024321.215780@o13g2000cwo.googlegroups.com> Message-ID: Tim Hochberg wrote: > mclaugb wrote: > > > No, Scientific Python is "a collection of Python modules that are useful > for scientific computing" written by Konrad Hinsen. I'm not a user, but > you can find information here: > > http://starship.python.net/~hinsen/ScientificPython/ > > SciPy is, I believe, a more recent and more ambitious project. In any > event it is not directly related to ScientficPython. Information here: > SciPy's been around since 2001. ScientificPython since about 1998, I think. > Numeric: This is the origingal array package. > > Numarray: This was written as a replacement for Numeric. It has improved > performance for large arrays. The internals were also simplified and > many other improvements were made (arrays were subclassable, numeric > signal handling vastly improved, etc). Unfortunately, a side effect of > the changes was that small array performance got worse. There was a > signifigant chunk of the numeric community for whom this was a deal > breaker and as a result there ended up being a split between the Numeric > and Numarray communities. Just to be clear, small array performance was only 1 of the "deal-breaker" problems with numarray. Anothber big problem for SciPy was that the Numeric C-API was never fully supported (in particular the Ufunc C-API). This made it more difficult to convert to numarray. Thus, porting never happened. The small-array speed issue just made porting that much less enticing. > > Numpy: This is a rewrite of Numeric that incorporates most of the > improvements in Numarray. The goal is to incorporate *all* of the improvements (unless being written in Python is one of the improvements). If there are missing improvements we need to know about them. Thanks to Tim for spreading some light on the issue. There will no doubt be continued confusion for new users over the coming months. Hopefully, with time the confusion will fade as more people use NumPy and any remainging issues get resolved. -Travis From lists at nabble.com Fri Feb 3 14:31:14 2006 From: lists at nabble.com (gilcneth (sent by Nabble.com)) Date: Fri, 3 Feb 2006 11:31:14 -0800 (PST) Subject: Python - python-list Message-ID: <2746115.post@talk.nabble.com> Hello, I am trying to automate my personal website logons and recently discovered cPamie, which looks like it may be a very handy tool indeed. But, so far, I have not had any luck using it for website logons. This may or may not be a cPamie issue, so please bear with me. The site I am trying to log on to automatically displays my username, but I must feed it my password in order to log on. No problem. I can get my password in the textbox, just fine. Where I have problems, however, is with the invocation of the log on itself. I am no HTML guru and am much more familiar with Python than any of the more accepted web languages, but I can read it well enough to sort of partially diagnose the problem. It appears that the buttonname itself is hidden--which means (I think) that I cannot call a method requiring the input of a buttonname. I have tried a number of methods from cPamie in order to try to log on, in lieu of the buttonname, but so far I have been unsuccessful. Does anyone know of a solution to this problem? (Incidently, I can log on by pressing the button with my mouse, but it is key and mouse strokes I am trying to eliminate, of course) Thanking you in advance, Chris N. -- View this message in context: http://www.nabble.com/Python---python-list-t1055356.html#a2746115 Sent from the Python - python-list forum at Nabble.com. -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Sun Feb 5 12:33:56 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 05 Feb 2006 11:33:56 -0600 Subject: NumPy error In-Reply-To: References: <44mgs1F2to82U1@uni-berlin.de> Message-ID: jason wrote: > Thanks. > > After executing the first line, I now get: > >>>>from scipy.optimize import fmin > > Overwriting fft= from scipy.fftpack.basic (was > from numpy.dft.fftpack) > Overwriting ifft= from scipy.fftpack.basic (was > from numpy.dft.fftpack) > > And then I get the following result: > >>>>xopt = fmin(rosen, x0) > > Optimization terminated successfully. > Current function value: 0.000066 > Iterations: 141 > Function evaluations: 243 > >>>>print xopt > > [ 0.99910115 0.99820923 0.99646346 0.99297555 0.98600385] > > Two questions: > 1. does the "overwriting..." message make sense? It's replacing the fft() and ifft() functions in numpy with the optimized functions in scipy. I don't think we're doing that anymore in SVN scipy. > I uninstalled scipy and numpy and re-installed them. > > 2. has the algorithm (accuracy level) changed? the result seems different > from that reported in > http://www.scipy.org/Wiki/Documentation?action=AttachFile&do=get&target=scipy_tutorial.pdf > on page 12. It is different. We're not really sure why. The simplex method is not an algorithm known for its robustness. Sorry about the confusion with dtypechar. Our releases of numpy and scipy got out of sync. -- Robert Kern robert.kern at gmail.com "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From sullivanz.pku at gmail.com Sun Feb 19 01:18:20 2006 From: sullivanz.pku at gmail.com (sullivanz.pku at gmail.com) Date: 18 Feb 2006 22:18:20 -0800 Subject: Any Tkinker based rich text widget? Message-ID: <1140329900.341774.175600@f14g2000cwb.googlegroups.com> Hi all I am using the standard python GUI Tkinter as my program's main interface. Although I know wxPython has some widget to support rich text widget, but I do not have time to shift to wx---- series. Does anyone know any Tkinter based widget that support: 1. Blod, Italic, Underline and their combinations. 2. Several most commonly used fonts, like Times New Roman and Arial 3. Multiline text 4. Cross platform support. Available in Linux-RedHat and Mac OS series and Windows 2000 or above. 5.Image embedding. Support jpeg, gif, bmp. The more the better. and better support: Hyperlink, Text color, the more the better. Thank you so much for help! From fakeaddress at nowhere.org Fri Feb 10 05:31:50 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 10 Feb 2006 10:31:50 GMT Subject: Question about idioms for clearing a list In-Reply-To: References: <1139231464.914400.37100@g44g2000cwa.googlegroups.com> <43E7F59B.9070009@REMOVEMEcyber.com.au> <1139300825.858426.12680@o13g2000cwo.googlegroups.com> Message-ID: Magnus Lycka wrote: > Bryan Olson wrote: > >> Magnus Lycka wrote: >> >>> Do you really have a usecase for this? It seems to me that your >>> argument is pretty hollow. >> >> >> Sure: >> >> if item_triggering_end in collection: >> handle_end(whatever) >> collection.clear() >> >> Or maybe moving everything from several collections into >> a single union: >> >> big_union = set() >> for collection in some_iter: >> big_union.update(t) >> collection.clear() > > > I don't understand the second one. Where did 't' come from? Cut-and-past carelessness. Meant to update with 'collection'. > Anyway, tiny code snippets are hardly usecases. The task is the usecase. [...] > I still don't see any convincing usecase for the kind of > ducktyping you imply. I didn't say I could convince you. I said that when different types can support the same operation, they should also support the same interface. That's what enables polymorphism. -- --Bryan From bradfordh at gmail.com Tue Feb 14 18:02:17 2006 From: bradfordh at gmail.com (Tempo) Date: 14 Feb 2006 15:02:17 -0800 Subject: Python and ASP Message-ID: <1139958137.733403.33640@g44g2000cwa.googlegroups.com> I recently uploaded a sample ASP-Python page to my web server and it didn't show up correctly. Before I explain what it did, I should mention that I got the same result when I tried to view the page from my desktop (winxp user). So when I tried to view the sample ASP with Python page from my desktop and web server, all that showed up was the source code. I'm not sure exactly what this means since I know that python 2.4 is installed on my computer and the ASP page still didn't show up correctly. Here's the sample ASP-Python code, courtesy of http://www.4guysfromrolla.com/webtech/082201-1.shtml : ASP-Python Test Page <%@ Language=Python %> <% Response.Write("Python lives in the ASP delimeters!") %>

Any ideas about what I am doing wrong? Thanks. From infini.g at gmail.com Wed Feb 1 20:39:40 2006 From: infini.g at gmail.com (GazaM) Date: 1 Feb 2006 17:39:40 -0800 Subject: cgi - secure sessions In-Reply-To: <7x8xsuczxz.fsf@ruckus.brouhaha.com> References: <1138842390.012855.107610@g44g2000cwa.googlegroups.com> <7x8xsuczxz.fsf@ruckus.brouhaha.com> Message-ID: <1138844380.094365.223840@g44g2000cwa.googlegroups.com> wow, those were some seriously quick replies, thanks. I understand that cookies is the best way to do things, but I didn't explain my problem well, sorry. Basically, I have a blog in the works and I want to have an online interface for posting. What I have is a cgi script run through a server side include line in the html, which looks for the session cookie, if it is present will say 'logged in as "user"' and if the cookie isn't there will display a login form. Now, the big showstopper here is that, because session cookies are stored in http headers sent by the client (afaik) the cgi script can't get any, because the http headers are passed onto the html file and any cgi scripts inside don't get anything... is there a workaround possible? I need to use an include line instead of pointing to the script and making it output full html as there are various other scripts run in the html as well, plus I am hoping to use the cookie-detection script in other ways than just the home page... Again, any help is appreciated. GazaM From skip at pobox.com Sun Feb 12 13:05:12 2006 From: skip at pobox.com (skip at pobox.com) Date: Sun, 12 Feb 2006 12:05:12 -0600 Subject: Is Forth for real? In-Reply-To: References: <1139690972.344818.136870@f14g2000cwb.googlegroups.com> <1139754010.067582.214830@z14g2000cwz.googlegroups.com> <1v44c3-geo.ln1@lairds.us> Message-ID: <17391.30936.143514.842617@montanaro.dyndns.org> Roy> If you like Forth, take a look at PostScript. I miss NeWS... :-( Skip From jrivero at latinux.org Tue Feb 21 13:45:40 2006 From: jrivero at latinux.org (Jesus Rivero (Neurogeek)) Date: Tue, 21 Feb 2006 14:45:40 -0400 Subject: html parser , unexpected '<' char in declaration In-Reply-To: References: <1140473997.262973.149260@f14g2000cwb.googlegroups.com> <1140488536.933840.65530@o13g2000cwo.googlegroups.com> Message-ID: <43FB5FD4.2060601@latinux.org> Oopss! You are totally right guys, i did miss the closing '>' thinking about maybe errors in the use of ' or ". Jesus Tim Roberts wrote: >"Jesus Rivero - (Neurogeek)" wrote: > > >>hmmm, that's kind of different issue then. >> >>I can guess, from the error you pasted earlier, that the problem shown >>is due to the fact Python is interpreting a "<" as an expression and not >>as a char. review your code or try to figure out the exact input you're >>receving within the mta. >> >> > >Well, Jesus, you are 0 for 2. Sakcee pointed out what the exact problem >was in his original message. The HTML he is being given is ill-formed; the > tag >which it thinks is inside the > > >>>well probabbly I should explain more. this is part of an email . after >>>the mta delivers the email, it is stored in a local dir. >>>After that the email is being parsed by the parser inside an web based >>>imap client at display time. >>> >>>I dont think I have the choice of rewriting the message!? and I dont >>>want to reject the message alltogether. >>> >>>I can either 1-fix the incoming html by tidying it up >>>or 2- strip only plain text out and dispaly that you have spam, 3 - or >>>ignore that mal-formatted tag and display the rest >>> >>> > >If this is happening with more than one message, you could check for it >rather easily with a regular expression, or even just ''.find, and then >either insert a closing '>' or delete everything up to the before >parsing it. > > From peter at engcorp.com Tue Feb 21 10:46:07 2006 From: peter at engcorp.com (Peter Hansen) Date: Tue, 21 Feb 2006 10:46:07 -0500 Subject: Pyserial never read In-Reply-To: <1140302110.028540.176210@g43g2000cwa.googlegroups.com> References: <1140105936.408387.88130@z14g2000cwz.googlegroups.com> <1140219414.143448.234450@z14g2000cwz.googlegroups.com> <1140302110.028540.176210@g43g2000cwa.googlegroups.com> Message-ID: luca72 wrote: > Thanks for your help, but it don't solve the problem. > I receive only the echo and full stop. If you want help, you'll do better to post small pieces of code that you are actually using, rather than making us guess or imagine what you are doing. There are perhaps a dozen things that can go wrong with serial communications, and it's not efficient for us to start suggesting them one at a time... -Peter From steve at holdenweb.com Sun Feb 12 23:51:33 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Feb 2006 23:51:33 -0500 Subject: ordered sets operations on lists.. In-Reply-To: <1139805374.7547.24.camel@kenshin> References: <1139592166.993686.212000@f14g2000cwb.googlegroups.com> <1139599834.975607.77180@f14g2000cwb.googlegroups.com> <1halbdx.dd0p1l1obawfkN%aleaxit@yahoo.com> <43ef8e5f.625119424@news.oz.net> <1hana3d.1bwbt4c1esela5N%aleaxit@yahoo.com> <43F007F9.3090103@holdenweb.com> <1139805374.7547.24.camel@kenshin> Message-ID: Felipe Almeida Lessa wrote: > Em Dom, 2006-02-12 ?s 23:15 -0500, Steve Holden escreveu: > >>Given that Python 2.4 doesn't even perform simple constant folding for >>arithmetic expressions >>[snip] > > > May I ask why doesn't it perform such optimization? Is there any special > difficulties in doing so with the Python compiler? > As well to ask why the sky is blue, and has those little white things in it (unless you live in Arizona) :-) The basic answer is that so far no developer has felt it worthwhile to expend time on adding these optimizations. > Also, IIRC Psyco does optimize these constant expressions. Or am I > wrong? > Psyco does some very advanced things, but it does them all at run-time. Unless I misunderstand (not unheard of), there are no circumstances under which Psyco will improve run-time for a piece of code that is only executed once. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From http Sat Feb 11 02:18:35 2006 From: http (Paul Rubin) Date: 10 Feb 2006 23:18:35 -0800 Subject: is there a better way? References: <1139594221.696053.7360@g47g2000cwa.googlegroups.com> Message-ID: <7xk6c2fjn8.fsf@ruckus.brouhaha.com> "markscala at gmail.com" writes: > But this seems ugly to me, and using "while" give me the heebies. Is > there a better approach? Note that "list" is the name of a built-in type; I used "mylist". Alex Martelli described how to do it in log n time using the bisect module. Here's a dumb linear time method that might be faster for small n (of course you should time the different methods for your particular Python implementation, if the speed matters): del mylist[len(mylist) - mylist.count(0):] The above an example of where the natural del mylist[-mylist.count(0):] does totally the wrong thing if there are no 0's in the list. There was a huge thread a while back about ways to fix that. Another way, might be faster, esp. there's more than a few 0's: try: del mylist[mylist.index(0)] except ValueError: pass # no 0's in the list From simon at brunningonline.net Wed Feb 8 07:15:01 2006 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 8 Feb 2006 12:15:01 +0000 Subject: Question about idioms for clearing a list In-Reply-To: References: <43E7F59B.9070009@REMOVEMEcyber.com.au> Message-ID: <8c7f10c60602080415y584ac1b4x73e1293ff780619c@mail.gmail.com> On 2/8/06, Fredrik Lundh wrote: > you seem to be missing that we're talking about a programming language > here. nothing is obvious if you don't know anything about the language; > a lot of things are obvious once you've learned a little about it. a little is > all it takes. why is that so hard to understand ? "The only 'intuitive' user interface is the nipple. After that, it's all learned." - Bruce Ediger -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From bradfordh at gmail.com Tue Feb 7 12:09:48 2006 From: bradfordh at gmail.com (Tempo) Date: 7 Feb 2006 09:09:48 -0800 Subject: Is Python good for web crawlers? In-Reply-To: References: <1139330008.270988.227170@g44g2000cwa.googlegroups.com> Message-ID: <1139332188.851343.20580@g14g2000cwa.googlegroups.com> Why do you say that the bottleneck of the crawler will always be downloading the page? Is it becasue there isn't already a modual to do this and I will have to start from scratch? Or a bandwidth issue? From seb.haase at gmail.com Fri Feb 17 17:01:05 2006 From: seb.haase at gmail.com (seb.haase at gmail.com) Date: 17 Feb 2006 14:01:05 -0800 Subject: Python 3000 deat !? Is true division ever coming ? References: <1139810036.943598.229030@g47g2000cwa.googlegroups.com> Message-ID: <1140213665.105188.103450@o13g2000cwo.googlegroups.com> Thank you very much, Magnus ! This is the answer I had been waiting for: > A problem as I see it today, is that this behaviour is > not actively encouraged. The tutorial, which is maintained > and updated, still describes old style classes, and the > old division behaviour. My main point was/is: why is there not more discussion about "true division" !!? Just like the second answer to my posting clearly showed: PEOPLE THINK TRUE DIVISION IS "ONLY IN MATLAB" !! As you pointed out: the "true division" part of "Python3000" might be one of the "scariest" and should therefore be pointed out already in the tutorial !! (It would look quite ugly to newcomers, though) Having said that: I would vote against EVER introducing true division as default - because it will just PISS too many (long time python) people OFF. ;-) Thanks, Sebastian Haase Magnus Lycka wrote: > seb.haase at gmail.com wrote: > > Hi, > > Is it true that that "Python 3000" is dead ? > > I think you should view Python 3000 as a metaphor for > "Python as it would look if we didn't have to care about > backward compatibility". > > Before this name appeared, Guido used to talk about > Python 3.0 as a version where bad things in Python could > go away, but it seems many people got worried about that, > assuming that Python 3.0 would happen soon and cause a lot > of changes in already written code. Thus the less scary > label Python 3000. There has never been any concrete plans > as far as I know to actually release a real software product > called Python 3000. It's rather a long term design target > for Python. > > A lot of these language changes can be introduced step > be step. A new feature can be introduced first as an > experimental feature, accessible via "from __future__ > import XYZ", in the next minor release, it might be > enabled by default. If a feature or module is going away, > the first step is to document it as deprecated. The next > minor release will issue a PendingDeprecationWarning, and > the minor release after that will issue a DeprecationWarning > and the next minor release (2.4 -> 2.5 etc) will remove > the feature. This will give developers a period of many > years to adapt from the time the feature is documented as > deprecated until maintenace ends for the last Python where > the deprecated feature works. > > For an example of such a transition plan, see > http://www.python.org/peps/pep-0352.html > > Changing the behaviour of int/int is worse, since there > is no obvious way for Python to determine whether the > programmer expects an int result, a float result or either. > Also, the typical consequence of this change is not that > code breaks with a big bang, but rather that it produces > somewhat different results. That means that a bug due to > this feature change might go unnoticed for a long time, > and cause a lot of problems. Imagine some kind of system > that calculates how much pension you'll get when you > retire, based on your monthly payments. A bug caused by > changed division behaviour might have serious consequences. > > It seems reasonable to wait until the next major release, > 3.0, before this feature is introduced. In the mean time > it seems that the strategy should be to encourage people > to adopt the new behaviour in all new code, i.e. to use > "from __future__ import division" and to explicitly use > interger division a//b when this is needed. > > In the same way, people should be encouraged to always > use new style classes, "class X(object):" in new code, > since old style classes are going away, and they behave > differently in some ways. > > A problem as I see it today, is that this behaviour is > not actively encouraged. The tutorial, which is maintained > and updated, still describes old style classes, and the > old division behaviour. > > http://docs.python.org/dev/tut/node5.html#SECTION005110000000000000000 > http://docs.python.org/dev/tut/node11.html#SECTION0011300000000000000000 > > I don't see any reason to use old style classes in new code, > so I think all "class X:" should be changed to > "class X(object):", but I can understand that it would be > confusing to explain the use of "from __future__ import division" > before we introduce simple arithmetics. Still, we should > get this message through! > > As it is now, when people aren't actively moving their code > towards this expected change, the impact of such a change > would be almost as strong as if this "from __future_..." > feature didn't exist. > > So, if I finally try to answer your question: Float division > will hardly be enabled by default until most Python programmers > have adopted the feature, i.e. enabled it through the > __future__ switch and started to use // when they want floor > division. > > This will hardly happen until it's documented as the way people > should do it. Perhaps a start could be a FutureProofPython page > in the Python wiki, with suggested coding guidelines. From enterr at gmail.com Tue Feb 14 22:39:41 2006 From: enterr at gmail.com (Atanas Banov) Date: 14 Feb 2006 19:39:41 -0800 Subject: Soduku References: <1139967167.960780.171360@o13g2000cwo.googlegroups.com> Message-ID: <1139974781.396430.108910@g14g2000cwa.googlegroups.com> you dont measure single run, you measure multiple runs using the "timeit" module (for me 1000 repeats was about right). here are some results which i recorded when i was implementing Sudoku solver (on AMD Athlon 1.25GHz, using the sample shown on www.sudoku.com front page): brute: 1000 for 83 sec smart: 1000 for 21 sec brute, bitset: 1000 for 29 sec smart, bitset: 1000 for 7.0 sec smart, bit+que: 1000 for 5.3 sec so you see the algorithm makes big difference... and so does the data structure used. i got 15x speed-up that way. i guess i can claim that my solver runs the sample for 5.3s/1000 = 5.3 ms! a friend was also implementing sudoku - this time in C - and his program solves the sample 10000 times for 3.4sec (i.e. for 0.34ms) on slightly faster machine - so let's say his **highly optimized** C code is about 10x faster than mine. - Nas From ilias at lazaridis.com Tue Feb 21 06:27:59 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Tue, 21 Feb 2006 13:27:59 +0200 Subject: - Copy dictionary entries to attributes In-Reply-To: <1hazako.13jtm8o1u3h0z7N%aleaxit@yahoo.com> References: <1140319945.169944.31940@g14g2000cwa.googlegroups.com> <1hazako.13jtm8o1u3h0z7N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Ben Wilson wrote: > >> Perhaps: >> >> def dictionary_make_attributes(self, settings): >> for k,v in settings: >> setattr(self, k, v) for k,v in settings.items() > This is a very general solution and will work for all kinds of objects > with settable attributes, even if some of the attributes are properties, > slots or weirder descriptors yet. > > For plain vanilla class instances, though, > self.__dict__.update(settings) > may be sufficient. > > Alex this is the construct I was looking for. see it active: http://pudge.lesscode.org/trac/changeset/118 http://pudge.lesscode.org/trac/ticket/16 . -- http://lazaridis.com From Lucabrocci at aol.com Sat Feb 11 16:05:09 2006 From: Lucabrocci at aol.com (Lucabrocci at aol.com) Date: Sat, 11 Feb 2006 16:05:09 EST Subject: Hi reliability files, writing,reading,maintaining Message-ID: <291.57f34fb.311fab85@aol.com> Who said you could have my name? Get ur own ,I know it's a great name but u still cant have it! So start practicing your new signature. Jokingly....... John J. Pote PS:.... "Good Luck in Prison!" -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Feb 10 07:31:49 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 10 Feb 2006 07:31:49 -0500 Subject: a second TKinter In-Reply-To: <1d987df30602100425n38faccefpaa4e6a2a3e8b568f@mail.gmail.com> References: <1d987df30602100253x33aece59u425dd7d61c0ffa3f@mail.gmail.com> <6f4025010602100256m5f390357o@mail.gmail.com> <1d987df30602100320t4c61673ewfa6cd0f685a24bab@mail.gmail.com> <1d987df30602100425n38faccefpaa4e6a2a3e8b568f@mail.gmail.com> Message-ID: linda.s wrote: > On 2/10/06, Steve Holden wrote: > >>linda.s wrote: >> >>>On 2/10/06, Michael Foord wrote: >>> >>> >>>> >>>>On 10/02/06, linda.s wrote: >>>> >>>> >>>>>I found if I opened a second TKinter, Python will go out of work. But >>>>>I need two graph outputs at the same time. What to do? >>>>>Linda. [...] > > so run from the terminal? Yes, but wouldn't just trying that have been easier than asking me? ;-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From nakpac at gmail.com Thu Feb 23 18:24:52 2006 From: nakpac at gmail.com (nak) Date: 23 Feb 2006 15:24:52 -0800 Subject: Concantenation and string slicing References: <1140735316.752278.298490@v46g2000cwv.googlegroups.com> Message-ID: <1140737092.542387.178050@i39g2000cwa.googlegroups.com> add a dash like shown below >>> print newMessage, From hancock at anansispaceworks.com Wed Feb 15 17:05:34 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 15 Feb 2006 16:05:34 -0600 Subject: Python, Forms, Databases In-Reply-To: <1140030788.083799.45060@f14g2000cwb.googlegroups.com> References: <1140030788.083799.45060@f14g2000cwb.googlegroups.com> Message-ID: <20060215160534.40cde874@samwise.anansi> On 15 Feb 2006 11:13:08 -0800 "Tempo" wrote: > Pyton and ASP together. The next solution I stumbled upon > was to use Zope. However, I wasn't sure if I should spend > more of my time looking into this or not, and I found a > possible way around this, which is by using the CGI > module. CGI, "ick!" :-P Zope, "mmm" :-) Actually, it's a bit of a pain to get Zope installed on your server (or conversely, to get a server you're allowed to put Zope on). But if you're willing to do that, it is going to be *so* much easier to manage. *If* you can do that, then it's a really simple way to do what you want. This kind of thing is child's play once you have a Zope site set up (you'll have to install a MySQL Zope product, and possibly some helpful Zope products for managing forms, if you don't want to do it the old-fashioned way -- after that though, it's just "throught-the-web" scripting). But Zope is kind of a culture onto itself, so you may not necessarily want to buy into it, if you don't do this kind of thing often. Just my two cents, of course, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From vinjvinj at gmail.com Fri Feb 17 14:55:51 2006 From: vinjvinj at gmail.com (vinjvinj) Date: 17 Feb 2006 11:55:51 -0800 Subject: ANN: Release of NumPy 0.9.5 In-Reply-To: References: <45ljqdF7706gU1@individual.net> <1140203632.748504.138390@g47g2000cwa.googlegroups.com> Message-ID: <1140206151.184715.175950@o13g2000cwo.googlegroups.com> I read some of the earlier threads which essentially said that numpy is about 3-4 times slower then Numeric for smaller arrays. I'm assuming that applies only to operations that apply to the whole arrays. I was curious how the performance of the following operations would compare though: 1. Copying arrays 2. Creating arrays 3. Slicing Arrays In the mean time I'll install numpy and give it a spin. >>Most, if not all, of the functions in scipy_base have been moved into numpy. That's great. it would be great if I could remove the scipy_base dependency. VJ From jjreavis at gmail.com Thu Feb 16 10:48:18 2006 From: jjreavis at gmail.com (Jeff Reavis) Date: 16 Feb 2006 07:48:18 -0800 Subject: Python, Forms, Databases In-Reply-To: <1140030788.083799.45060@f14g2000cwb.googlegroups.com> References: <1140030788.083799.45060@f14g2000cwb.googlegroups.com> Message-ID: <1140104898.035867.203730@g14g2000cwa.googlegroups.com> You should check out Spyce: http://spyce.sourceforge.net/ It will work under CGI as well as Fast CGI, ModPython, or its own built in server. It also has an ASP/JSP like syntax: http://spyce.sourceforge.net/docs/doc-lang_asp.html If you plan on getting a new hosting company you might also want to look at TurboGears and Django. -jjr From deets at nospam.web.de Fri Feb 24 12:23:54 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 24 Feb 2006 18:23:54 +0100 Subject: Exception not raised References: <43ff3fc8$0$29105$5fc30a8@news.tiscali.it> Message-ID: <468ttdF9vr9mU1@uni-berlin.de> Michele Petrazzo wrote: > Simple example extract from my code: > > #code > def test(): > print type(t_fields), 11 in t_fields > print t_fields[11] > print "I'm here" > > print "ok" > test() > print "ok" > #end code > > Output: > > ok > False > > Here I see only one "ok" and not the "I'm here". The interpreter stop to > run here, but the application continue to work! Not here: t_fields = {} #code def test(): print type(t_fields), 11 in t_fields print t_fields[11] print "I'm here" print "ok" test() print "ok" #end code Gives me python2.4 /tmp/test.py ok False Traceback (most recent call last): File "/tmp/test.py", line 9, in ? test() File "/tmp/test.py", line 5, in test print t_fields[11] KeyError: 11 So - whatever you do, there must be some other code capturing that exception. Maybe you don't use dict, but a subclass of it? Diez From roy at panix.com Mon Feb 20 17:01:06 2006 From: roy at panix.com (Roy Smith) Date: Mon, 20 Feb 2006 17:01:06 -0500 Subject: Is inifinite loop not a good practice? References: <43F9DF68.5020301@gmail.com> Message-ID: In article , "Terry Reedy" wrote: > "Alvin A. Delagon" wrote in message > news:43F9DF68.5020301 at gmail.com... > > I've been hearing comments that infinite loop is a bad programming > > practice. > > What is bad is an *unintended* loop that goobles cpu time while outputting > nothing. Example: > > def fact(n): > res = 1 > while n != 0: > res *= n > n -= 1 > return res > > fact(-1) > > Now imagine that you are paying $360/hr ($.10/sec) (for IBM mainframe time) > and you should understand the bad reputation (and why jobs were submitted > with a time limit!). ;-) > > Terry Jan Reedy Could be worse. You could have written: def fact(n): if n == 0: return 1 else: return n * fact (n-1) then you would have not only gotten zonked on CPU charges, but on memory charges as well :-) From codecraig at gmail.com Thu Feb 16 12:53:34 2006 From: codecraig at gmail.com (abcd) Date: 16 Feb 2006 09:53:34 -0800 Subject: Win32_Process.Create -- not starting process In-Reply-To: References: Message-ID: <1140112414.375181.294460@f14g2000cwb.googlegroups.com> Tim Golden wrote: > BTW, I would recommend you either to use a raw string > for that command line (r"c:\python\python.exe c:\xx.py") or > to double up your slashes ("c:\\python\\python.exe c:\\xx.py"). > As it happens \p has no special meaning that I'm > aware of, but better safe than sorry... ....i used double slashes, i guess i didn't type it correctly here. Thanks for the reminder though. From claudio.grondi at freenet.de Thu Feb 23 05:25:32 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 23 Feb 2006 11:25:32 +0100 Subject: =?ISO-8859-1?Q?Re=3A_=27rar=27_is_not_recognized_as_?= =?ISO-8859-1?Q?an_internal_or_external_command=A3=BF=A3=BF=A3=BF?= =?ISO-8859-1?Q?=A3=BF?= In-Reply-To: References: Message-ID: ???????? wrote: > 'rar' is not recognized as an internal or external command, > operable program or batch file. > > > import os > import time > source = [r'e:\temp\code',r'e:\temp\domains'] > target_dir = r'e:\temp\bak' > target = target_dir+time.strftime('%Y%m%d%H%M%S')+'.rar' > rar_cmd = "rar a -idcdp %s %s" % (target,' '.join(source)) > print rar_cmd > if os.system(r'cd D:\Program Files\WinRAR') == 0: > if os.system(rar_cmd) == 0: > print 'Successful backup to',target > else: > print 'Backup Failed!' > else: > print 'FAILED!!!' > > 'rar' is not recognized as an internal or external command, > operable program or batch file. > > rar a -idcdp e:\temp\bak20060222191139.rar e:\temp\code e:\temp\domains > Backup Failed! It is always a good idea to use full path file location specs like: rar_cmd = r"D:\Program Files\WinRAR\rar.exe a -idcdp %s %s" % (target,' '.join(source)) . Have not tested it, but I suppose it will do the job. Claudio > > > but......................... > > D:\>cd D:\Program Files\WinRAR > > D:\Program Files\WinRAR>rar a -idcdp e:\temp\bak20060222191139.rar > e:\temp\code > e:\temp\domains > > Creating archive e:\temp\bak20060222191139.rar > > Adding e:\temp\Code\Code\.classpath OK > Adding e:\temp\Code\Code\.project OK > Adding e:\temp\Code\Code\common\Code.class OK > Adding e:\temp\Code\Code\common\Code.java OK > Adding e:\temp\Code\Code\common OK > Adding e:\temp\Code\Code OK > Adding e:\temp\Code OK > Adding e:\temp\domains\examples.jar OK > Adding e:\temp\domains\medrec.jar OK > Adding e:\temp\domains\wls.jar OK > Adding e:\temp\domains\wlw.jar OK > Adding e:\temp\domains OK > > D:\Program Files\WinRAR> > > > > why? > > > > From martin at v.loewis.de Mon Feb 13 13:34:37 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 13 Feb 2006 19:34:37 +0100 Subject: Encoding In-Reply-To: <1139853781.611888.60230@g44g2000cwa.googlegroups.com> References: <1139853781.611888.60230@g44g2000cwa.googlegroups.com> Message-ID: <43F0D13D.2070407@v.loewis.de> Lad wrote: > I have a script that uses utf-8 encoding. Now I would like to send some > data to an application ( on another server) that uses 1250 encoding. > How can I tell the server that the coming data will be in utf-8 code? You can't, normally. In theory, you should put Content-type: text/plain;charset=utf-8 into the individual *part*. However, many implementations will ignore the charset= argument on a part. Instead, the convention is that the data must be transmitted in the encoding of the *HTML page* which contained the form you are submitting. So most likely, you need to recode your data. Regards, Martin From fredrik at pythonware.com Mon Feb 13 03:25:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Feb 2006 09:25:24 +0100 Subject: How To Call A DLL? References: Message-ID: "Anand" wrote: > Can I get a code snippet of how to call a DLL and it's functionalities from > Python? start here: http://starship.python.net/crew/theller/ctypes/ (there's no standard mechanism in Python for calling functions in DLLs, unless they're explicitly designed for Python, in which case you can simply import them) From tdelaney at avaya.com Tue Feb 7 18:11:40 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 8 Feb 2006 10:11:40 +1100 Subject: Too Many if Statements? Message-ID: <2773CAC687FD5F4689F526998C7E4E5F07433B@au3010avexu1.global.avaya.com> Terry Reedy wrote: > The OP did not specify whether all of his if-tests were sequential as > in your test or if some were nested. I vaguely remember there being > an indent limit (40??). I'm pretty sure the OP has hit the python script line limit (32767?). Goggle searches haven't turned up the actual limit for me unfortunately. I suppose I could go check the code ... Tim Delaney From aleaxit at yahoo.com Sun Feb 5 20:36:15 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Feb 2006 17:36:15 -0800 Subject: Reverse of map()? References: <1139187820.735831.240570@f14g2000cwb.googlegroups.com> Message-ID: <1haardm.1krozue1esby5dN%aleaxit@yahoo.com> Phillip Sitbon wrote: > Hello there, > > I have a situation where a list of functions need to be called with a > single set of parameters and the result constructed into a tuple. I > know there's simple ways to do it via list comprehension: > > Result = tuple( [ fn(* Args, ** Kwds) for fn in fn_list ] ) > > I'd hope there's a more efficient way to do this with a built-in > function, so that I could call: > > Result = rmap( fn_list, * Args, ** Kwds ) > > and have it constructed as a tuple from the get-go. > > Is there a built-in function that would allow me to do this, or do I > have to go with the list comprehension? A genexp is probably going to be more efficient than the list comprehension: just omit the brackets in your first snippet. map(apply, fn_list, ...) may work, but I doubt it's going to be either simple or speedy since the ... must be replaced with as many copies of Args and Kwds as there are functions in fn_list, e.g.: map(apply, fn_list, len(fn_list)*(Args,), len(fn_list)*(Kwds)) There's no built-in that calls many functions with identical args and kwds, since it's a rare need. Also, map returns a list, not a tuple, so it's bordering on the absurd to think that your dreamed-for rmap would be designed to return a tuple rather than a list -- you still have to call tuple on the result, any way you build it. Alex From aleaxit at yahoo.com Thu Feb 2 23:05:14 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 2 Feb 2006 20:05:14 -0800 Subject: How do I dynamically create functions without lambda? References: <1138389517.896043.7450@g47g2000cwa.googlegroups.com> <1138436008.628882.126510@g44g2000cwa.googlegroups.com> <1ha3g79.1gcm6x1yziggyN%aleaxit@yahoo.com> Message-ID: <1ha5e9r.gs34le12dm1luN%aleaxit@yahoo.com> Benji York wrote: > Alex Martelli wrote: > > Disagree -- far more people THINK they're clever, than really ARE > > clever. According to a recent article in the Financial Times, over 40% > > of a typical financial firm's employees firmly believe they are among > > the 5% best employees of the firm -- and the situation, believe me, is > > no different in programming. > > It's apparently no different anywhere: > http://www.phule.net/mirrors/unskilled-and-unaware.html Tx. Maybe it's a genetically adaptive trait: the FT points out that while there is little correlation between an employee's opinion of their skills, and the employee's actual performance, there IS positive correlation between said opinion and the employee's career advancement. One way to explain the correlation is: if you truly (albeit perhaps mistakenly) believe you're great, you project that and are more likely to get promotions or raises, than is somebody else, perhaps objectively better, who's torn by self-doubt and projects THAT. My working hypothesis would be that this effect would be far stronger in fields where it's hard to get hard quantitative measures of performance, so the managers (or clients, etc) rely to a large extent on subjective judgment which can be influenced by such "projections"... Alex From rschroev_nospam_ml at fastmail.fm Wed Feb 1 08:41:33 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 01 Feb 2006 13:41:33 GMT Subject: triple quoted strings as comments In-Reply-To: References: <1138667355.631379.249770@o13g2000cwo.googlegroups.com> Message-ID: Roy Smith schreef: > Magnus Lycka wrote: >> An editor that adds/removes '# ' in the beginning of each >> marked line is fairly bullet proof. Adding e.g. /* to the >> beginning of a block you want to comment out, & */ to the >> end, breaks if you have /* */ style comments in the block! > > /* */ also allows for some truly spectacularly bad coding practices. Not > long ago, I ran into some real-life code where a previous developer had > commented out about 50 lines of C++ code by just putting a /* at the top > and a */ at the bottom. I was tearing my hair out trying to figure out how > the code worked until I noticed what he had done. That happened to me a few times. These days I use an editor with syntax highlighting that shows comments in another color than code. That helps tremendously. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From ruby at no.spam Sun Feb 26 21:56:24 2006 From: ruby at no.spam (Michal Kwiatkowski) Date: Mon, 27 Feb 2006 03:56:24 +0100 Subject: Local variables initialization In-Reply-To: References: <1hbdjrw.1lrbcv8k3kcbsN%aleaxit@yahoo.com> Message-ID: Michal Kwiatkowski wrote: > def init_arguments(fun): > def new_f(self): > var_one = self.attr_one > var_two = self.attr_two.another_attr > empty_list = [] > > fun(self, var_one, var_two, empty_list) > > return new_f > > @init_arguments > def method(self, var_one, var_two, empty_list): > # significant code goes here > # ... > > But the bad thing about this approach is that actual method doesn't > really look like its definition, because of different number of arguments. I've come up with a solution that don't have this disadvantage. Here we go: def wrap_method(self, do): var_one = self.attr_one var_two = self.attr_two.another_attr empty_list = [] return do(self, var_one, var_two, empty_list) def method(self): def do(self, var_one, var_two, empty_list): # significant code goes here # ... return self.wrap_method(do) All is implicit and have an advantage of being clear in < 2.4, where there are no nice @ decorator syntax. Again, simple things proved to be better. :) mk -- . o . >> http://joker.linuxstuff.pl << . . o It's easier to get forgiveness for being wrong o o o than forgiveness for being right. From duncanm255 at hotmail.com Tue Feb 28 14:31:12 2006 From: duncanm255 at hotmail.com (D) Date: 28 Feb 2006 11:31:12 -0800 Subject: Thread Question Message-ID: <1141155072.500444.215130@v46g2000cwv.googlegroups.com> I have a client application that I want (behind the scenes) to check and make sure a remote host is up (i.e. by ping or TCP connect). I'm assuming that, since I want this to go on "unknowingly" to the user, that I would put this in a thread. My question is, how would I go about creating the thread? I have seen examples that used classes, and other examples that just called one thread start command - when should you use one over another? Thanks in advance. Doug From s323 at mail.ru Mon Feb 20 04:55:44 2006 From: s323 at mail.ru (Sergey) Date: Mon, 20 Feb 2006 12:55:44 +0300 Subject: module time Message-ID: There is function mktime() -- convert local time tuple to seconds since Epoch in module time. But how about to convert *GMT time tuple* to seconds since Epoch? Is there such function? From saint.infidel at gmail.com Fri Feb 17 09:08:04 2006 From: saint.infidel at gmail.com (infidel) Date: 17 Feb 2006 06:08:04 -0800 Subject: Print a PDF transparently In-Reply-To: <1140184955.674138.275010@o13g2000cwo.googlegroups.com> References: <1140184955.674138.275010@o13g2000cwo.googlegroups.com> Message-ID: <1140185284.869720.297830@o13g2000cwo.googlegroups.com> Daniel Crespo wrote: > Hi to all, > > I want to print a PDF right from my python app transparently. With > "transparently" I mean that no matter what program handles the print > petition, the user shouldn't be noticed about it. > > For example, when I want to print a PDF, Adobe Acrobat fires and keep > opened. This is what I don't want to happen (and I thing there are a > lot of people who want this too). So I just want to send the PDF to the > right handler and print it. That's all. > > I've seen some things like Adobe's Postscript driver that can read a > PDF, or Ghostscript, but I still don't know how to use it. > > Any help for printing a PDF transparently? The only way I was able to find to do it (for free) was to install GhostScript and GSView. GSView comes with GSPrint.exe, which you can call with a regular command line to send PDF files to a printer. It uses GhostScript for you behind the scenes because GhostScript is not exactly the friendliest program to work with. From larry.bates at websafe.com Sat Feb 25 10:56:59 2006 From: larry.bates at websafe.com (Larry Bates) Date: Sat, 25 Feb 2006 09:56:59 -0600 Subject: Multiple threaded download streams? In-Reply-To: <1140867665.749334.210370@v46g2000cwv.googlegroups.com> References: <1140867665.749334.210370@v46g2000cwv.googlegroups.com> Message-ID: gjzusenet at gmail.com wrote: > Hello. > Though Python supports threading, I think it is limited to python code > - as soon as you issue a command that uses an external (C?) module, all > of your python threads hang until this command returns. > Is that true? > I'm using urllib2 to download many files, and I have a double problem: > 1. downloading all of them is painfully slow since it's serial - one > has to finish before the next request gets sent. > 2. my GUI becomes non responsive during the downloads - major problem! > > Is there any way to work around that? > I want to run multiple download streams, in parallel, and while keeping > my program responsive. > Are there alternative modules that I can use for that? > > Any ideas? > Thanks a lot! > Others have spoken to the specifics of threads, etc. What I wanted to ask was why you think that parallel downloads will be faster? Unless you are downloading from multiple and different sites and your Internet download bandwidth is much greater than any individual site you wish to download from, you won't speed things up. If you wish to download several files from the SAME site, I doubt that threading is going to help. Most likely you are limited by the upload bandwidth of that site. Now if the site you are downloading from has some throttling turned on to limit the speed of an individual download, you could gain some benefit. You can't push bits through the pipes faster than their upper bandwidth. Just some thoughts to consider. -Larry Bates From mrstephengross at hotmail.com Wed Feb 22 12:51:58 2006 From: mrstephengross at hotmail.com (mrstephengross) Date: 22 Feb 2006 09:51:58 -0800 Subject: How to force creation of a .pyc? Message-ID: <1140630718.197661.104730@o13g2000cwo.googlegroups.com> I would like to distribute a python program, but only in .pyc form (so that people cannot simply look at my code). Is there a way to do this? I've read up a little on the logic by which python creates .pyc's, and it sounds like python requires the main executed program to be in .py format. Any ideas? Thanks --Steve (mrstephengross at hotmail.com) From exarkun at divmod.com Sat Feb 18 22:43:32 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 18 Feb 2006 22:43:32 -0500 Subject: Multiplication optimization In-Reply-To: <1140310118.365847.111120@g14g2000cwa.googlegroups.com> Message-ID: <20060219034332.6122.1302410015.divmod.quotient.2406@ohm> On 18 Feb 2006 16:48:38 -0800, Paul McGuire wrote: >Does Python's run-time do any optimization of multiplication >operations, like it does for boolean short-cutting? Here's the beginning of int_mul from Objects/intobject.c: static PyObject * int_mul(PyObject *v, PyObject *w) { long a, b; long longprod; /* a*b in native long arithmetic */ double doubled_longprod; /* (double)longprod */ double doubleprod; /* (double)a * (double)b */ CONVERT_TO_LONG(v, a); CONVERT_TO_LONG(w, b); longprod = a * b; doubleprod = (double)a * (double)b; doubled_longprod = (double)longprod; I think the rest of the function is probably irrelevant, as far as your question goes. Jean-Paul From bdesth.quelquechose at free.quelquepart.fr Mon Feb 13 21:50:11 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 14 Feb 2006 03:50:11 +0100 Subject: invert the order of a string In-Reply-To: <7xek26erf0.fsf@ruckus.brouhaha.com> References: <7xek26erf0.fsf@ruckus.brouhaha.com> Message-ID: <43f125ba$0$1742$636a55ce@news.free.fr> Paul Rubin a ?crit : > rtilley writes: > >>s = list('some_random_string') >>print s >>s.reverse() >>print s >>s = ''.join(s) >>print s >> >>Surely there's a better way to do this, right? > > > In Python 2.4, just say > s = reversed('some_random_string') Python 2.4.1 (#1, Jul 23 2005, 00:37:37) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> reversed('some_random_string') >>> Yes, that was my first take too - but I jumped to my Python shell before posting !-) From sam at nuevageorgia.com Tue Feb 28 12:38:05 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 28 Feb 2006 09:38:05 -0800 Subject: Python and Flash In-Reply-To: <1141136533.215656.290800@i39g2000cwa.googlegroups.com> References: <1139230361.675896.241920@z14g2000cwz.googlegroups.com> <1139235297.903689.244030@z14g2000cwz.googlegroups.com> <1139407620.948877.5820@g14g2000cwa.googlegroups.com> <1141101898.725832.104260@e56g2000cwe.googlegroups.com> <1141102008.086764.24550@j33g2000cwa.googlegroups.com> <1141136533.215656.290800@i39g2000cwa.googlegroups.com> Message-ID: <1141148285.499150.325180@j33g2000cwa.googlegroups.com> By the way Sybren, if you don't mind, what kinda computer and browser were you using, trying to figure out which browsers get redirected to html and which get the Flash Site. If you have Flash plugin, what version was it? Thanks, Sam the Gardener From MrJean1 at gmail.com Sun Feb 12 04:10:07 2006 From: MrJean1 at gmail.com (MrJean1) Date: 12 Feb 2006 01:10:07 -0800 Subject: PySizeof: almost useful In-Reply-To: References: Message-ID: <1139735407.024752.179620@g14g2000cwa.googlegroups.com> Check the sizeof() method in the mxTools package from eGenix: /Jean Brouwers From modelnine at bit-bukket.org Thu Feb 16 11:10:43 2006 From: modelnine at bit-bukket.org (Heiko Wundram) Date: Thu, 16 Feb 2006 17:10:43 +0100 Subject: pythonic way of 'b = list(a); b.append(4)" References: <1140105883.069632.262530@g43g2000cwa.googlegroups.com> Message-ID: szabi wrote: > a = [1, 2, 3] > f(*a, 4) f(*(a+[4])) --- Heiko. From vania.smirk at gmail.com Tue Feb 14 09:15:22 2006 From: vania.smirk at gmail.com (VSmirk) Date: 14 Feb 2006 06:15:22 -0800 Subject: hard disk activity In-Reply-To: References: <1139850420.902979.71620@o13g2000cwo.googlegroups.com> <1139857505.376840.37440@g43g2000cwa.googlegroups.com> <1139859890.407497.124870@o13g2000cwo.googlegroups.com> <1139863885.755813.324450@g47g2000cwa.googlegroups.com> <7xfymn0yda.fsf@ruckus.brouhaha.com> <1139864840.300396.170070@o13g2000cwo.googlegroups.com> <7xbqxb0xo0.fsf@ruckus.brouhaha.com> Message-ID: <1139926522.747947.69080@o13g2000cwo.googlegroups.com> Terry, Yeah, I was sketching out a scenario much like that. It does break things down pretty well, and that gets my file sync scenario up to much larger files. Even if many changes are made to a file, if you keep track of the number of bytes and checksum over from 1 to the number of bytes different by shifting the sequence ( that is [abcd]ef, a[bced]f, ab[cdef]), until a checksum is a match again, you should be able to find some point where the checksums match again and you can continue up (or down) doing only the checksums again without all the overhead. The question in my mind that I will have to test is how much overhead this causes. One of the business rules underlying this task is to work with files that are being continuously written to, say by logging systems or database servers. This brings with it some obvious problems of file access, but even in cases where you don't have file access issues, I am very concerned about race conditions where one of the already-handled blocks of data are written to. The synched copy on the remote system now no longer represents a true image of the local file. This is one of the reasons I was looking into a device-level solution that would let me know when a hard disk write had occurred. One colleagues suggested I was going to have to write assembler to do this, and I may have to ultimately just use the solutions described here for files that don't have locking and race-condition issues. Regardless, it's a fun project, and I have to say this list is one of the more polite lists I've been involved with. Thanks! V From ptmcg at austin.rr._bogus_.com Thu Feb 2 13:50:51 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 02 Feb 2006 18:50:51 GMT Subject: learning python, using string help References: <1138906062.727850.177960@g14g2000cwa.googlegroups.com> Message-ID: wrote in message news:1138906062.727850.177960 at g14g2000cwa.googlegroups.com... > hi all, > > I have a simple snippet I am trying to keep the format the same as > plain text, though I want to embed it in html ... > > basically, > > print "Content-type:text/plain\n\n"; > getrup = os.popen('ruptime').read() > print getrup > > is the same format as if I ran 'ruptime' from the command line. > > If I use... > > print "Content-type:text/html\n\n"; > getrup = os.popen('ruptime').read() > print getrup > > I can just split the lines and loop through it ... but I am not sure > how to keep the tab spacing the same > I'm sure its something so simple I am missing .... > > thanks for helping someone learning.. > --mike > What about : print "Content-type:text/html\n\n"; print "
"
getrup = os.popen('ruptime').read()
print getrup
print "
" The
 tags indicate that the enclosed text has been pre-formatted.
Otherwise your tabs will get collapsed out by HTML.

-- Paul




From nas-usenet at arctrix.com  Sat Feb  4 22:31:24 2006
From: nas-usenet at arctrix.com (Neil Schemenauer)
Date: Sun, 05 Feb 2006 03:31:24 GMT
Subject: Generators vs. Functions?
References: <0001HW.C00ABC2B000323A6F0335550@news.individual.de>
	<43E50E73.40504@kzoo.edu>
	
Message-ID: 

Peter Hansen  wrote:
> More precisely, the state of the function is *saved* when a yield 
> occurs, so you certainly don't *recreate* it from scratch, but merely 
> restore the state, and this should definitely be faster than creating it 
> from scratch in the first place.

Right.  Resuming a generator is faster than calling a function.

  Neil


From lee at example.com  Wed Feb  1 16:48:36 2006
From: lee at example.com (Lee Harr)
Date: Wed, 01 Feb 2006 21:48:36 GMT
Subject: load module named "datetime" and change the directory of output
	file?
References: 
Message-ID: <_%9Ef.13064$qg.11955@news01.roc.ny>

> 1. How can I add a standard module named "datetime" in
> Jython when the error happens :"Traceback (innermost
> last):
>   File "C:\python\test.py", line 3, in ?
> ImportError: no module named datetime "
>  The line 3 is writen: "from datetime import datetime,
> tzinfor"
>

The datetime module was added with Python 2.3. I think
that Jython is still at the 2.1 or 2.2 level of Python.

I believe that the Jython team is pretty far along the
path to Python 2.4, but that is probably a question best
asked on one of their lists.



> 2. I hope test.py outputs a file like test.txt, but I
> want to change the directory of the result file named
> test.txt. for example, the result is in
> c:\python\test.txt, but I want to put it in
> c:\python\result\test.txt. How can I change the
> directory in java?
>


Sort of depends on how you are writing the output.
You could do something like ...

fh = open(r"c:\python\result\test.txt", "w")
fh.write("something")

right?

What does your code look like now? It is easier to
help you fix it than to start fresh....


From steve at REMOVETHIScyber.com.au  Thu Feb 23 17:04:05 2006
From: steve at REMOVETHIScyber.com.au (Steven D'Aprano)
Date: Fri, 24 Feb 2006 09:04:05 +1100
Subject: Unexpected timing results
References: 
	<43FDDDB2.7050703@websafe.com>
Message-ID: 

On Thu, 23 Feb 2006 10:07:14 -0600, Larry Bates wrote:

>> Of course I expect timer2 should take longer to execute in total,
>> because it is doing a lot more work. But it seems to me that all that
>> extra work should not affect the time measured, which (I imagine) should
>> be about the same as timer1. Possibly even less as it isn't timing the
>> setup of the for loop.

...

> In timer2 you are making a million extra calls to timer()
> function and doing a million additions and a million
> subtractions that are not being done in timer1() function.
> I think that is where your "extra" time is located.

But those extra additions, subtractions, etc. are not being timed, because
they are outside the part where the stopwatch is ticking, in a manner of
speaking.

I know that timer2 will take longer to execute than timer1. That's not
the surprising bit. But I'm not measuring all the execution time, only
part of it, and not all that execution time is being timed.

The only extra work I can see is a call to timer() each loop. The first
call shouldn't count, because it happens before the clock starts. Is
calling time.time() really such as expensive operation, especially when
I've rebound the name so as to avoid a name lookup?

I guess it is: I've run two more tests, both going back to the form of
timer1, but changing the function being timed. The first uses math.sin.
The second uses time.timer.

Here is the code:

def timer3():
    timer = time.time
    func = math.sin
    itr = [None] * 1000000
    t0 = timer()
    for _ in itr:
        func(0.1)
    t1 = timer()
    return t1 - t0

def timer4():
    timer = time.time
    func = timer
    itr = [None] * 1000000
    t0 = timer()
    for _ in itr:
        func()
    t1 = timer()
    return t1 - t0

And the results:

>>> timer.timer3()
0.64760088920593262
>>> timer.timer4()
5.2274949550628662



It looks like the time function under Linux at least is very slow.


-- 
Steven.



From andy at nospam.com  Fri Feb  3 06:13:01 2006
From: andy at nospam.com (Andy Sy)
Date: Fri, 03 Feb 2006 19:13:01 +0800
Subject: fixedint.py enhanced for auto-coercion (fixed-width python integers)
Message-ID: <43E33ABD.2030403@nospam.com>

Hi Dan,

I find that when doing bit-twiddling in pure Python,
fixed-width integer support is an extremely handy
capability to have in Python regardless of what
the apologists (for its absence) say.


I added some stuff to fixedint.py to make

>>> x=SByte(80)
>>> x+200
fixedint.SignedType(8)(24)

the above work.  Perhaps you can review the
code to see if there are any major flaws in it?


Right after I started using it, I realized
there has to be a lot more thought put into
the conventions for the coecion rules.  What
should

>>> x=SByte(80)
>>> 200+x

return for example... ?





-----  START OF CODE -----


import operator

def _toFixedUnsigned(n, b):
   "Truncate n to a b-bit unsigned long."
   return n & ((1L << b) - 1)    # bitmask of b 1's

def _toFixedSigned(n, b):
   "Truncate n to a b-bit signed long."
   result = _toFixedUnsigned(n, b)
   if result >= (1L << b - 1):   # More than "maxint"?
      result -= 1L << b          # Then wrap around.
   return result

class _Integer(object):
   "Abstract base class for SignedType and UnsignedType."
   # Numeric conversions
   def __long__(self):
      return self._value
   def __int__(self):
      return int(self._value)
   def __float__(self):
      return float(self._value)
   def __nonzero__(self):
      return self._value != 0
   # String conversions.
   def __str__(self):
      return str(self._value)
   # Arithmetic
   def __pos__(self):
      return self
   def __neg__(self):
      return type(self)(-self._value)
   def __add__(self, other):
      if isinstance(other, type(self)):
        return type(self)(self._value + other._value)
      else:
        return type(self)(self._value + self.__class__(other)._value)
   def __sub__(self, other):
      if isinstance(other, type(self)):
        return type(self)(self._value - other._value)
      else:
        return type(self)(self._value - self.__class__(other)._value)
   def __mul__(self, other):
      if isinstance(other, type(self)):
        return type(self)(self._value * other._value)
      else:
        return type(self)(self._value * self.__class__(other)._value)
   def __floordiv__(self, other):
      if isinstance(other, type(self)):
        return type(self)(self._value // other._value)
      else:
        return type(self)(self._value // self.__class__(other)._value)
   def __mod__(self, other):
      if isinstance(other, type(self)):
        return type(self)(self._value % other._value)
      else:
        return type(self)(self._value % self.__class__(other)._value)
   def __divmod__(self, other):
      return self // other, self % other
   # Relational
   def __cmp__(self, other):
      return cmp(long(self), other)
   # Bit-bashing
   def __lshift__(self, other):
      return type(self)(self._value << other)
   def __rshift__(self, other):
      return type(self)(self._value >> other)
   def __invert__(self):
      return type(self)(~self._value)
   def __and__(self, other):
      if isinstance(other, type(self)):
        return type(self)(self._value & other._value)
      else:
        return type(self)(self._value & self.__class__(other)._value)
   def __or__(self, other):
      if isinstance(other, type(self)):
        return type(self)(self._value | other._value)
      else:
        return type(self)(self._value | self.__class__(other)._value)
   def __xor__(self, other):
      if isinstance(other, type(self)):
        return type(self)(self._value ^ other._value)
      else:
        return type(self)(self._value ^ self.__class__(other)._value)

_utypes = {}

def UnsignedType(bits):
   "Returns a fixed-width unsigned int type with the given number of bits."
   if bits in _utypes:
      return _utypes[bits]
   else:
      class unsigned(_Integer):
        __doc__ = '%d-bit unsigned integer type' % bits
        def __init__(self, value):
          self._value = _toFixedUnsigned(value, bits)
        def __repr__(self):
          return 'fixedint.UnsignedType(%d)(%d)' % (bits, self._value)
      return unsigned

Byte = UnsignedType(8)
UShort = UnsignedType(16)
UInt = UnsignedType(32)
ULong = UnsignedType(64)

_stypes = {}

def SignedType(bits):
   "Returns a fixed-width signed int type with the given number of bits."
   if bits in _stypes:
      return _stypes[bits]
   else:
      class signed(_Integer):
        __doc__ = '%d-bit signed integer type' % bits
        def __init__(self, value):
          self._value = _toFixedSigned(value, bits)
        def __repr__(self):
          return 'fixedint.SignedType(%d)(%d)' % (bits, self._value)
      return signed

SByte = SignedType(8)
Short = SignedType(16)
Int = SignedType(32)
Long = SignedType(64)



From DavidPorterHolt at acm.org  Tue Feb 21 12:27:49 2006
From: DavidPorterHolt at acm.org (DavidPorterHolt)
Date: 21 Feb 2006 09:27:49 -0800
Subject: Exceptions
In-Reply-To: 
References: <1140540154.522838.193020@g14g2000cwa.googlegroups.com>
	<1140540525.032755.209460@g47g2000cwa.googlegroups.com>
	
Message-ID: <1140542869.048735.201040@z14g2000cwz.googlegroups.com>

That's good to know. Thanks.



From fuzzyman at gmail.com  Wed Feb  8 05:27:43 2006
From: fuzzyman at gmail.com (Fuzzyman)
Date: 8 Feb 2006 02:27:43 -0800
Subject: module with __call__ defined is not callable?
In-Reply-To: 
References: 
	
Message-ID: <1139394463.255902.168960@f14g2000cwb.googlegroups.com>


Steven D'Aprano wrote:
> On Wed, 08 Feb 2006 13:58:13 +1100, Delaney, Timothy (Tim) wrote:
>
> > adam johnson wrote:
> >
> >> Hi All.
> >> I was wondering why defining a __call__ attribute for a module
> >> doesn't make it actually callable.
> >
> > For the same reason that the following doesn't work
> [snip example]
> > The __call__ attribute must be defined on the class (or type) - not on
> > the instance. A module is an instance of .
>
> That's not a _reason_, it is just a (re-)statement of fact. We know that
> defining a __call__ method on a module doesn't make it callable. Why not?
> The answer isn't "because defining a __call__ method on a module or an
> instance doesn't make it callable", that's just avoiding the question.
>
> Someone had to code Python so that it raised an error when you try to call
> a module object. Is there a reason why module() should not execute
> module.__call__()? I would have thought that by the duck typing principle,
> it shouldn't matter whether the object was a class, a module or an int, if
> it has a __call__ method it should be callable.
>

It would nice if you could make modules callable.

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> 
> -- 
> Steven.



From paddy3118 at netscape.net  Tue Feb 14 03:06:38 2006
From: paddy3118 at netscape.net (Paddy)
Date: 14 Feb 2006 00:06:38 -0800
Subject: how do you pronounce 'tuple'?
In-Reply-To: 
References: 
	
	
	
Message-ID: <1139904398.126243.11020@z14g2000cwz.googlegroups.com>


(dupple, supple, zupple) = (2,1,0) # :-)



From blair.houghton at gmail.com  Wed Feb  1 23:56:33 2006
From: blair.houghton at gmail.com (Blair P. Houghton)
Date: 1 Feb 2006 20:56:33 -0800
Subject: webbrowser module + urls ending in .py = a security hole?
References: <1138593557.824516.116400@g14g2000cwa.googlegroups.com>
	<1138626217.999480.153140@g43g2000cwa.googlegroups.com>
	<1138651762.673682.192210@g43g2000cwa.googlegroups.com>
	
Message-ID: <1138856193.857136.196670@g47g2000cwa.googlegroups.com>

>Would it be sufficient in your case merely to allow only .html files to
>be loaded?  Or URLs without .extensions?  Or even just permit only the
>http: protocol?

Personally, I'm just noodling around with this right now.
So "my case" is the abstract case.  I think the solution if
one was needed would be to look at how something like
Firefox implements script detection and warns about it,
so all forms of scripts would be rejected.

I did try loading the .py file over a remote connection, and
it does seem to work as expected that way; i.e., I get a
browser window with the text of the script.  So the
webbrowser.py module's handling of http:// accesses
is definitely different from its handling of  file://  accesses.

--Blair



From bencvt at gmail.com  Tue Feb 21 20:28:38 2006
From: bencvt at gmail.com (Ben Cartwright)
Date: 21 Feb 2006 17:28:38 -0800
Subject: a little more help with python server-side scripting
In-Reply-To: <59edncmGm6g2LmbeRVn-pw@rcn.net>
References: <59edncmGm6g2LmbeRVn-pw@rcn.net>
Message-ID: <1140571718.278297.105080@f14g2000cwb.googlegroups.com>

John Salerno wrote:
> I contacted my domain host about how Python is implemented on their
> server, and got this response:
>
> -------------------
> Hello John,
>
> Please be informed that the implementation of python in our server is
> through mod_python integration with the apache.
>
> These are the steps needed for you to be able to run .py script directly
> from browser for your webpage:
>
> 1. Please use the below mentioned path for python:
> #!/usr/bin/env python
>
> Furthermore, update us with the script path, so that we can set the
> appropriate ownership and permissions of the script on the server.
>
> If you require any further assistance, feel free to contact us.
> -----------------------
>
> Unfortunately, I don't completely understand what it is I need to do
> now. Where do I put the path they mentioned? And what do they mean by my
> script path?


The Python tutorial should fill in the blanks
(http://www.python.org/doc/tut/node4.html):
> 2.2.2 Executable Python Scripts
>
> On BSD'ish Unix systems, Python scripts can be made directly executable,
> like shell scripts, by putting the line
>
>   #! /usr/bin/env python
>
> (assuming that the interpreter is on the user's PATH) at the beginning
> of the script and giving the file an executable mode. The "#!" must be
> the first two characters of the file. On some platforms, this first line
> must end with a Unix-style line ending ("\n"), not a Mac OS ("\r") or
> Windows ("\r\n") line ending. Note that the hash, or pound, character,
> "#", is used to start a comment in Python.

This answers your first question.  Put the #! bit at the top of your
.py script.  This way the web server will know how to run the script.

> The script can be given a executable mode, or permission, using the
> chmod command:
>
>   $ chmod +x myscript.py

And this answers your second.  Your host needs to know the path to your
script so they can use chmod to make it executable.

--Ben



From bonono at gmail.com  Mon Feb 20 04:33:36 2006
From: bonono at gmail.com (bonono at gmail.com)
Date: 20 Feb 2006 01:33:36 -0800
Subject: Quesion about the proper use of __slots__
In-Reply-To: 
References: <1140424508.393412.79140@o13g2000cwo.googlegroups.com>
	<43f9825e$0$4777$636a55ce@news.free.fr>
	<1140426860.033363.237150@o13g2000cwo.googlegroups.com>
	
Message-ID: <1140428016.170547.315710@g47g2000cwa.googlegroups.com>


Peter Otten wrote:
> Zefria wrote:
>
> > Also, I don't generally do any optimization at all yet (as a highschool
> > student projects get trashed often enough no to bother over), but in
> > this special case I'm expecting each "carrier" to have up to 150
> > fighters, and 3 to 5 carriers for each of the two teams, which comes
> > out to be quite large.
>
> However, 'large numbers' are more likely to start (picture me looking out of
> the window) at 100,000 than 10,000 in this context -- and you are at 750...
>
He could be working on a machine with < 1M RAM or some other
constraints.



From steve at REMOVETHIScyber.com.au  Thu Feb 23 10:40:38 2006
From: steve at REMOVETHIScyber.com.au (Steven D'Aprano)
Date: Fri, 24 Feb 2006 02:40:38 +1100
Subject: formatted string like--->  u'720 S'
References: 
Message-ID: 

On Thu, 23 Feb 2006 08:00:16 -0700, Bell, Kevin wrote:

> I'm building a dictionary from values a database and upon print the
> dictionary I see key value pairs like this:
> 
> u'Briarcliff' : [u'2500 E'],
> u'Shumway' : [ u'2600 E']
> 
> do I need to slice off the "u", or anything?  I know it has something to
> do with unicode but I don't know how to treat it.

No. The u is part of the display of the string, just like the quote marks. 

Ordinary strings are printed with ' ' delimiters.
Unicode strings are printed with u' ' delimiters.



-- 
Steven.



From scott.daniels at acm.org  Sun Feb 26 20:54:09 2006
From: scott.daniels at acm.org (Scott David Daniels)
Date: Sun, 26 Feb 2006 17:54:09 -0800
Subject: Memory allocation in for loops
In-Reply-To: 
References: <1134298072.537702.158870@g49g2000cwa.googlegroups.com>
	 
Message-ID: <44025a09$1@nntp0.pdx.net>

invitro81 wrote:
> Which one is better w.r.t. memory allocation but also w.r.t. speed:
> ## 1.1 ##
> def forloop(a,b):
>     for idx in range(a,b):
>         ...
Above preferred to next (for readability) using xrange may help speed 
depending.

> ## 1.2 ##
> def whileloop(a,b):
>     idx = a
>     while idx < b:
>         ...
>         idx += 1

> def forloop(a,b,lst):
>     for idx in lst.sort():
>         ...
This one just doesn't work.  the sort method on a list causes a
side-effect of sorting the list, and then returns None to remind you.

   def forloop(a,b,lst):
       lst = list(lst) # if you don't want to mangle the original)
       lst.sort()
       for idx in lst:
           ...

With the new-fangled (2.4 or greater) Python, you could use sorted:
   def forloop(a,b,lst):
       for idx in sorted(lst):
           ...

Your other questions were correctly answered elsewhere


--Scott David Daniels
scott.daniels at acm.org


From nospam at yahoo.com  Wed Feb 15 09:29:31 2006
From: nospam at yahoo.com (Grant Griffin)
Date: Wed, 15 Feb 2006 08:29:31 -0600
Subject: how do you pronounce 'tuple'?
In-Reply-To: 
References: 	<11v032ii4gvik72@corp.supernews.com>	<1139816300.706181.79250@f14g2000cwb.googlegroups.com>
	
Message-ID: <87d36$43f33ac1$4088dbc7$20582@EVERESTKC.NET>

Tim Peters wrote:
...
> "tuhple" is a girly-man affectation.  That's why Guido and I both say
> the manly "toople".
...

Yes, but doesn't Guido say 'Guido' with some sort of strange faux-manly 
'H'-ish sortta sound?

methinks-the-lady-doth-protest-too-much-ly y'rs,

=g2
-- 
_____________________________________________________________________

Grant R. Griffin
Publisher of dspGuru                           http://www.dspguru.com
Iowegian International Corporation            http://www.iowegian.com
See http://www.iowegian.com/img/contact.gif for e-mail address


From cjw at sympatico.ca  Sun Feb 19 15:52:02 2006
From: cjw at sympatico.ca (Colin J. Williams)
Date: Sun, 19 Feb 2006 15:52:02 -0500
Subject: editor for Python on Linux
In-Reply-To: 
References: 
	
Message-ID: <43F8DA72.8040808@sympatico.ca>

Rene Pijlman wrote:
> Mladen Adamovic:
> 
>>I wonder which editor or IDE you can recommend me for writing Python 
>>programs.
> 
> 
> vi
> 
Scite is a good editor.  It is available for both Windows and Linux.
Boa-Constructor is an IDE rather than an editor.  Although it focuses
on wxPython, it has a good editor.

Colin W


From godoy at ieee.org  Sun Feb  5 10:44:58 2006
From: godoy at ieee.org (Jorge Godoy)
Date: Sun, 05 Feb 2006 13:44:58 -0200
Subject: Importing a class, please help...
References: 
Message-ID: <87fymxolmt.fsf@ieee.org>

"anon"  writes:

> to do an Import on it.  This is where things fail.  I cannot see the 
> contents of my Jar.  What am I missing here?

That JARs are for Java and yo're using Python?


-- 
Jorge Godoy      

"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.


From luismgz at gmail.com  Wed Feb 22 13:36:04 2006
From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=)
Date: 22 Feb 2006 10:36:04 -0800
Subject: Python vs. Lisp -- please explain
References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com>
	
	<43f8ba1e$0$2895$626a54ce@news.free.fr>
	
	<43f8cb3f$0$4225$626a54ce@news.free.fr>
	<87bqx3glb1.fsf@wilson.homeunix.com>
	<43f984dc$0$27151$626a54ce@news.free.fr>
	<873bienwlx.fsf@wilson.homeunix.com> <43fbc788@usenet01.boi.hp.com>
	<87u0ar3gba.fsf@wilson.homeunix.com>
	
	<1140612537.685150.68330@o13g2000cwo.googlegroups.com>
	<7xu0arbkwd.fsf@ruckus.brouhaha.com>
	
Message-ID: <1140633364.333444.241520@g43g2000cwa.googlegroups.com>

Carl Friedrich Bolz wrote:
> Paul Rubin wrote:
> Well. "... the PyPy team works on ..." is definitively much too strong.
> It is more like "... the PyPy team is thinking about ...". It is very
> unclear whether it will work on a technical level and whether the EU
> will allow us to allocate resources accordingly.

In this thread
http://groups.google.com/group/comp.lang.python/msg/5132f0d48c9e7be9
Christian Tismer said that he would work on this, even if this is not
pursued by the Pypy team, because he has personal reasons for doing it.

So I'm confident that sooner or later, it will be possible to create
extension modules written in Rpython.



From steve at REMOVETHIScyber.com.au  Sat Feb 18 10:02:31 2006
From: steve at REMOVETHIScyber.com.au (Steven D'Aprano)
Date: Sun, 19 Feb 2006 02:02:31 +1100
Subject: commenting out blocks of code
References: <20060217231846.87613.qmail@web36708.mail.mud.yahoo.com>
	
	
	
Message-ID: 

On Sat, 18 Feb 2006 03:14:49 +0000, Neil Hodgson wrote:

>     I am the developer responsible for SciTE and the Ctrl+Q decision.
> Ctrl+Q is not reserved for Quit on every platform. 

[snip]


Thank you for your thoughtful response. Although I'm not convinced by your
reasoning, I will concede that perhaps my post was a little hasty.


-- 
Steven.



From om at oliviermigeon.com  Thu Feb 16 12:17:12 2006
From: om at oliviermigeon.com (Olivier)
Date: Thu, 16 Feb 2006 18:17:12 +0100
Subject: mod_python help!
In-Reply-To: <1140099406.395361.293670@z14g2000cwz.googlegroups.com>
References: <1140099406.395361.293670@z14g2000cwz.googlegroups.com>
Message-ID: <43f4b2d4$0$27142$626a54ce@news.free.fr>

treelife a ?crit :
> I'm getting and internal server error when | run the following
> mod_python script.  I am actually trying to run Django.
> 
> Script:
> 
> from mod_python import apache
> 
> def handler(req):
>     req.content_type = 'text/plain'
>     req.write("Under Construction")
>     return apache.OK



You just cant't import mod_python.apache from the command line.
To run your scripts, you usually do things like (not tested):

try:
     from mod_python import apache
     APACHE = True
except ImportError:
     # for when I'm outside Apache
     APACHE = False


class DummyRequest:
     """Simulates a request object"""

     def write(self, mstr):
         print mstr

     # you may need some other things...


def handler(req):
     req.content_type = 'text/plain'
     req.write("Under Construction")
     if APACHE:
         return apache.OK


######################
if __name__ == "__main__":
     req = DummyRequest()
     handler(req)


HTH,
	Olivier


From python at hope.cz  Sat Feb 25 06:17:19 2006
From: python at hope.cz (Lad)
Date: 25 Feb 2006 03:17:19 -0800
Subject: How to send an email with non-ascii characters in Python
References: <1140775736.341876.314070@t39g2000cwt.googlegroups.com>
	
	<1140777219.636561.47960@e56g2000cwe.googlegroups.com>
	
Message-ID: <1140866239.019528.183190@t39g2000cwt.googlegroups.com>

Finally I have the working version,It looks like this
#############
from email.Message import Message
from email.MIMEText import MIMEText
from email.Header import Header
import smtplib
msg = Message()
Body='R?d?c?ch M?rinka a ?kol?k K?ja
Mar?k'.decode('utf8').encode('windows-1250')# I use the text written
in my editor with utf-8 coding, so first I decode and then encode to
windows-1250
msg = MIMEText(Body,'plain', 'windows-1250')#add body to email and with
 proper coding
h = Header('Cesk? knihy - made by Czech
Republic'.decode('utf8').encode('windows-1250'), 'windows-1250')#Also
subject should be a proper coding with
msg['Subject'] = h# add the header to the message
s = smtplib.SMTP() # and send
s.connect()
s.sendmail('e..ort at h.pe.cz', 'ex..ort at h.pe.cz', msg.as_string())
s.close()
#############
Hope it may be useful to others



From novin01 at gmail.com  Fri Feb 17 05:52:20 2006
From: novin01 at gmail.com (novin01 at gmail.com)
Date: 17 Feb 2006 02:52:20 -0800
Subject: Add a month
Message-ID: <1140173540.686250.205760@g44g2000cwa.googlegroups.com>

Hi, this is probably a really simple question but...
How do you add a month to a datetime date in python? It would be nice
if  you could do something like:

d = datetime.date(2006,2,17)
dm = datetime.timedelta(months=1)
d_new = d + dm

but timedelta doesn't have a 'months' setting. Am I missing some easy
method or do I have to code a work around myself??

Thanks in advance for the help!



From kay.schluehr at gmx.net  Wed Feb 22 08:28:31 2006
From: kay.schluehr at gmx.net (Kay Schluehr)
Date: 22 Feb 2006 05:28:31 -0800
Subject: Python vs. Lisp -- please explain
In-Reply-To: <7xu0arbkwd.fsf@ruckus.brouhaha.com>
References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com>
	
	<43f8ba1e$0$2895$626a54ce@news.free.fr>
	
	<43f8cb3f$0$4225$626a54ce@news.free.fr>
	<87bqx3glb1.fsf@wilson.homeunix.com>
	<43f984dc$0$27151$626a54ce@news.free.fr>
	<873bienwlx.fsf@wilson.homeunix.com> <43fbc788@usenet01.boi.hp.com>
	<87u0ar3gba.fsf@wilson.homeunix.com>
	
	<1140612537.685150.68330@o13g2000cwo.googlegroups.com>
	<7xu0arbkwd.fsf@ruckus.brouhaha.com>
Message-ID: <1140614911.243300.67200@g47g2000cwa.googlegroups.com>


Paul Rubin wrote:
> "Kay Schluehr"  writes:
> > I talked to Richard Emslie recently and he told me that the PyPy team
> > works on a mechanism to create CPython-extension modules written in
> > RPython i.e. a statically translateable subset of Python. So even
> > without dynamic code specialization there will be an optimization path
> > based on the PyPy toolchain that is amazing.
>
> Sounds great but is that a whole lot different from pyrex?

RPython is Python code not a different language. In a sense RPython
consists of a set of rules usual Python has to conform to make complete
type-inference feasible. Here is an overview of those rules.

http://codespeak.net/pypy/dist/pypy/doc/coding-guide.html#restricted-python

Kay



From g.brandl-nospam at gmx.net  Fri Feb 17 16:26:55 2006
From: g.brandl-nospam at gmx.net (Georg Brandl)
Date: Fri, 17 Feb 2006 22:26:55 +0100
Subject: Does python have an internal data structure with functions
	imported from a module?
In-Reply-To: 
References: 
Message-ID: <45mtcvF7erbvU1@individual.net>

Carl J. Van Arsdall wrote:
> Alright, I attempted to post this question yesterday but I don't see it 
> as showing up, so I apologize in advance if this is a double post.
> 
> Python Gurus:
> 
> Let me elaborate a bit more on this question.  Basically, I want to know 
> if there is some data structure in python that maps a string function 
> name to an address of a function or something to that nature.
> 
> If this is confusing, let me describe what I want to do and see if 
> anyone has any ideas.
> 
> basically we have:
> 
>  >>>def functA():
> ...  pass
> 
>  >>> functA
> 
> 
> And what I'd like to do is:
> 
>  >>>__internalFuncDict__['functA']
> 

Read about globals(), dir() and module.__dict__.

Georg


From lycka at carmen.se  Tue Feb 14 05:01:31 2006
From: lycka at carmen.se (Magnus Lycka)
Date: Tue, 14 Feb 2006 11:01:31 +0100
Subject: Newbie
In-Reply-To: 
References: 
Message-ID: <43F1AA7B.40700@carmen.se>

LittlePython wrote:
> Is this a good place to post python questions from newbie's, or would you
> suggest another board?

The best place to ask newbie questions is the Tutor mailing list.
Go to http://mail.python.org/mailman/listinfo/tutor to subscribe.
Check out the archives and you'll see how great it is. Besides
the fact that there are several guys who are both very good at
Python, good at explaining, and tolerant with newbie questions
and mistakes, you'll see much less of those sidetracking long
threads you often see in comp.lang.python.


From steve at holdenweb.com  Mon Feb 20 02:54:33 2006
From: steve at holdenweb.com (Steve Holden)
Date: Mon, 20 Feb 2006 02:54:33 -0500
Subject: Is inifinite loop not a good practice?
In-Reply-To: <43F9DF68.5020301@gmail.com>
References: <43F9DF68.5020301@gmail.com>
Message-ID: 

Alvin A. Delagon wrote:
> Greetings,
> 
> I have to write a python script that would continously monitor and 
> process a queue database. Once the script sees an unprocessed record it 
> will create a thread to process it otherwise it will do nothing. I've 
> been planning to do an infinite loop within the script to do this but 
> I've been hearing comments that infinite loop is a bad programming 
> practice. I'm opted to run the script via crontab but I consider it as 
> my last resort. Do you have any suggestions on the design? Thanks in 
> advance!

Clearly no process written as an infinite look is expected to run 
forever - it will be brought down by system reboots, for example, 
without going into end-of-life issues.

The classic network server process is pretty much an infinite loop, 
though perhaps with a break condition actioned when the operator sets 
some flag with a command, and there's no real reason why you shouldn't 
cast your application as such a loop. You will need to do so with care, 
however.

The danger is that you will spend time that should really be allocated 
to other processes on the system checking for database updates. So you 
need to design your polling mechanism fairly carefully - perhaps it 
could sleep five seconds once it found there were no more records that 
needed processing before looking again, or some similar mechanism to 
ensure that the system doesn't spend too much time looking for changes.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/



From webraviteja at gmail.com  Fri Feb  3 07:05:18 2006
From: webraviteja at gmail.com (Ravi Teja)
Date: 3 Feb 2006 04:05:18 -0800
Subject: Server side newbie
In-Reply-To: <1138552847.103899.302880@g14g2000cwa.googlegroups.com>
References: <1138552847.103899.302880@g14g2000cwa.googlegroups.com>
Message-ID: <1138968318.121755.97100@g47g2000cwa.googlegroups.com>


swisscheese wrote:
> I have a simple python desktop app with several edit controls and a
> couple of buttons. It just does some math. What's the simplest way to
> make it a server-side app so visitors to my site can run the app via
> their browser?

If the math is simple, you can just use JavaScript. No need to bother
running it on the server.



From grig.gheorghiu at gmail.com  Wed Feb  1 10:02:57 2006
From: grig.gheorghiu at gmail.com (Grig Gheorghiu)
Date: 1 Feb 2006 07:02:57 -0800
Subject: Test driven programming, was Re: VB to Python migration
References: 
	<1138421531.231633.41140@z14g2000cwz.googlegroups.com>
	
	<1138566539.478552.113180@g49g2000cwa.googlegroups.com>
	 
	 
	
Message-ID: <1138805691.431379.250290@z14g2000cwz.googlegroups.com>

Magnus,

I've been writing TextTest tests lately for an application that will be
presented at a PyCon tutorial on "Agile development and testing". I
have to say that if your application does a lot of logging, then the
TextTest tests become very fragile in the presence of changes. So I had
to come up with this process in order for the tests to be of any use at
all:

1) add new code in, with no logging calls
2) run texttest and see if anything got broken
3) if nothing got broken, add logging calls for new code and
re-generate texttest golden images

I've been doing 3) pretty much for a while and I find myself
regenerating the golden images over and over again. So I figured that I
won't go very far with this tool without the discipline of going
through 1) and 2) first.

>From what I see though, there's no way I can replace my unit tests with
TextTest. It's just too coarse-grained to catch subtle errors. I'm
curious to know how exactly you use it at Carmen and how you can get
rid of your unit tests by using it.

Grig



From steve at holdenweb.com  Tue Feb 21 15:05:40 2006
From: steve at holdenweb.com (Steve Holden)
Date: Tue, 21 Feb 2006 15:05:40 -0500
Subject: Python vs. Lisp -- please explain
In-Reply-To: <4866bea60602210948x10bff91elbff376bc8ec116f8@mail.gmail.com>
References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com>	<87bqx3glb1.fsf@wilson.homeunix.com>	<43f984dc$0$27151$626a54ce@news.free.fr>	<873bienwlx.fsf@wilson.homeunix.com>		<1140454473.335788@jetspin.drizzle.com>		<1140490302.639049@jetspin.drizzle.com>		<1140539404.440390.172350@g44g2000cwa.googlegroups.com>
	<4866bea60602210948x10bff91elbff376bc8ec116f8@mail.gmail.com>
Message-ID: 

Chris Mellon wrote:
[...]
> Torstens definition isn't useful for quantifying a difference between
> interpeted and compiled - it's a rough sort of feel-test. It's like
> how much of a naked body you can expose before before it changes from
> art to pornography - it's not something that is easily quantified.
> 
[...]

Possibly, but if your aim is exposing as much flesh as possible without 
being labeled pornography I think I'd conclude you were in the 
pornography business from the start, albeit masquerading as an "art dealer".

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/



From plahey at alumni.caltech.edu  Thu Feb 23 00:56:57 2006
From: plahey at alumni.caltech.edu (plahey at alumni.caltech.edu)
Date: 22 Feb 2006 21:56:57 -0800
Subject: What's up with this code?
In-Reply-To: <43fd08cf$1@nntp0.pdx.net>
References: <1140649331.924736.128420@g43g2000cwa.googlegroups.com>
	<43fd08cf$1@nntp0.pdx.net>
Message-ID: <1140674217.868665.5000@z14g2000cwz.googlegroups.com>

Scott,

this was a really clever catch, but I don't agree with the solution.
The problem is your assumption of how zip/izip _must_ work.  I don't
think there is any contract that states that they will always advance
the first argument first and the second argument second... that is an
implementation detail (the end result, ignoring iterator state, is the
same regardless of the order in which you advance things).  Given this,
I think using izip is simply a bad idea.

How about something like this:

    def __add__(self, other):
        rcoefs1 = reversed(self.coefs)
        rcoefs2 = reversed(other.coefs)
        minlen = min(len(rcoefs1), len(rcoefs2))
        coefs = [rcoefs1.next()+rcoefs2.next() for i in xrange(minlen)]
        coefs.extend(rcoefs1)
        coefs.extend(rcoefs2)
        if coefs[-1] != 0:
            return Polynomial(reversed(coefs), False, False)
        else:
            return Polynomial(reversed(coefs), False)



From egbert.bouwman at hccnet.nl  Mon Feb 20 06:55:42 2006
From: egbert.bouwman at hccnet.nl (egbert)
Date: Mon, 20 Feb 2006 12:55:42 +0100
Subject: Pythonpath and gnome panel
In-Reply-To: <1140434782.384240.254110@g44g2000cwa.googlegroups.com>
References: <1140335502.110014.35870@g47g2000cwa.googlegroups.com>
	
	<1140434782.384240.254110@g44g2000cwa.googlegroups.com>
Message-ID: <20060220115542.GA6432@hccnet.nl>

My pygtk gui can not be started from a gnome panel, 
because, apparently, the panel doesn't know about my
modified PYTHONPATH. So how can I instruct the panel ?
-- 
Egbert Bouwman - Keizersgracht 197 II - 1016 DS  Amsterdam - 020 6257991
========================================================================


From claird at lairds.us  Sun Feb 19 12:08:38 2006
From: claird at lairds.us (Cameron Laird)
Date: Sun, 19 Feb 2006 17:08:38 GMT
Subject: define loop statement?
References: 
	
	<%50Kf.1181$p13.791@trnddc08>
Message-ID: 

In article <%50Kf.1181$p13.791 at trnddc08>,
David Isaac  wrote:
			.
			.
			.
>Admiration wins out over revulsion.  ;-)
>Thanks,
>Alan Isaac
>
>PS Here's the motivation.  Python closely resembles pseudocode.  With
>a very little LaTeX hacking, it is often possible to write algorithms is
>Python that typeset as reasonable pseudocode.  A simple repetitive
>loop is a bit of a sticking point.
>
>

Wow.  Innovative.


From bearophileHUGS at lycos.com  Sun Feb 26 14:10:38 2006
From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com)
Date: 26 Feb 2006 11:10:38 -0800
Subject: sort one list using the values from another list
In-Reply-To: 
References: 
	
Message-ID: <1140981038.788111.93500@j33g2000cwa.googlegroups.com>

Your solution Steven Bethard looks very intelligent, here is a small
speed test, because sorting a list according another one is a quite
common operation.
(Not all solutions are really the same, as Alex has shown).


from itertools import izip, imap
from operator import itemgetter
from random import randint, choice, randint, shuffle
from string import lowercase

def timeit(function, *arg1, **arg2):
    """timeit(function, *arg1, **arg2): given a function and its
parameters, calls it
    and computes its running time, in seconds. It result is
discarded."""
    t1 = clock()
    function(*arg1, **arg2)
    t2 = clock()
    return round(t2-t1, 2)

def psort1(s1, s2):
    s1[:] = [a for b,a in sorted(zip(s2, s1))]

def psort2(s1, s2):
    aux = zip(s2, enumerate(s1))
    aux.sort()
    s1[:] = [a for b, (i, a) in aux]

def psort3(s1, s2):
    _indices = range(len(s1))
    _indices.sort(key=s2.__getitem__)
    s1[:] = [s1[i] for i in _indices]

def psort4(s1, s2):
    _indices = range(len(s1))
    _indices.sort(key=s2.__getitem__)
    s1[:] = map(s1.__getitem__, _indices)

def psort5(s1, s2):
    s1[:] = zip(*sorted(zip(s2, s1)))[1]

def psort6(s1, s2):
    s1[:] = map(itemgetter(0), sorted(zip(s1, s2), key=itemgetter(1)))

def psort7(s1, s2):
    s1[:] = [a for b,a in sorted(izip(s2, s1))]

def psort8(s1, s2):
    s1[:] = zip(*sorted(izip(s2, s1)))[1]

def psort9(s1, s2):
    s1[:] = map(itemgetter(0), sorted(izip(s1, s2), key=itemgetter(1)))


n = 100000
s1 = ["".join(choice(lowercase) for i in xrange(randint(2,8))) for k in
xrange(n)]
s2 = range(n)
shuffle(s2)

for psort in sorts:
    s1c = list(s1)
    print timeit(psort, s1c, s2), "s"


Timings on my PC, Python 2.4, PIII 500 MHz:
2.87
3.82
1.6
1.56
4.35
2.49
2.75
4.29
2.35

psort4 is my variant of your solution, and it seems the faster one.
Note: one liners are bad, and expecially bad in Python that is designed
to be a readable language, so let's avoid them as much as possible. I
have used one of them to generate s1, but I'll not use them in
production code or in my libraries, etc.

Bye,
bearophile



From cdc at maxnet.co.nz  Mon Feb 13 21:42:47 2006
From: cdc at maxnet.co.nz (Carl Cerecke)
Date: Tue, 14 Feb 2006 15:42:47 +1300
Subject: how do you pronounce 'tuple'?
In-Reply-To: 
References: 	
	
	
Message-ID: <43f143a8@usenet01.boi.hp.com>

Erik Max Francis wrote:
> Terry Hancock wrote:
> 
>> I doubt that helps much: I pronounce all of those words
>> (when I use them, which is not too often) as "-toopel". The
>> only tuple I pronounce with the "-uh-" is "couple", and I
>> usually call that a "two-tuple" when dealing with Python.
> 
> 
> I prefer the name _pair_ :-).
> 
>> I suspect that even those who would pronounce 'quintuple'
>> "kwintuhpel" would say 'quintuplicate' as "kwinTOOPlikuht".
>> (that's the noun, not the verb, which is "kwintoopliKATE").
> 
> 
> Yeah.  The short form is that both are right and which one is more 
> common is probably regional more than anything.  I've heard people say 
> _toople_ vs. _tuhple_, but I've never heard anyone say _quintoople_ vs. 
> _quintuhple_ (granted, not that the situation arises all that often).
> 
> But come to think of it, it kind of does.  I've heard _quintuhplet_ and 
> _sextuhplet_ and the like plenty of times, and I've never heard it 
> pronounced the other way (in General American).  m-w.com shows something 
> interesting here -- the first listed pronunciation for _quintuple_ is oo 
> with uh being an alternate, but the first listed pronunciation for 
> _quintuplet_ is uh with oo being an alternate.  Which probably goes to 
> emphasize that that it's just whatever you're used to and there's no 
> rhyme or reason to any of it.
> 
>> So what's a 1-element tuple, anyway? A "mople"?  "monople"?
>> It does seem like this lopsided pythonic creature (1,) ought
>> to have a name to reflect its ugly, newbie-unfriendly
>> nature.

> Of course that's still a completely valid construct in Python so the 
> question stands.  If a 4-tuple is a quadruple, a 3-tuple is a triple, a 
> 2-tuple is an pair, then I guess a 1-tuple would be a single.  Granted 
> that's not nearly as gruesome enough a name to go with the special 
> lopsided Pythonic creature mentioned above.  I suggest we name it a 
> hurgledink.
> 

So, ahhh, what about zero-tuples? zuple? uple? Surely it would be better 
for 2,1, and 0-tuples to be called 2,1, and 0-tuples.

And, BTW, in New Zealand, I've only ever heard the pronunciation 
'tupple'. toople sounds kind-of stoopid.

Cheers,
Carl.


From danb_83 at yahoo.com  Sat Feb 18 03:02:25 2006
From: danb_83 at yahoo.com (Dan Bishop)
Date: 18 Feb 2006 00:02:25 -0800
Subject: Python 3000 deat !? Is true division ever coming ?
References: <1139810036.943598.229030@g47g2000cwa.googlegroups.com>
	<1139928242.726349.221080@g44g2000cwa.googlegroups.com>
	
	
	
	
Message-ID: <1140249745.275343.283900@g14g2000cwa.googlegroups.com>

Magnus Lycka wrote:
> Gregory Pi?ero wrote:
> > I knew about that approach.  I just wanted less typing :-(
>
> It's enough to introduce one float in the mix.
> 1.*a/b or float(a)/b if you don't want one more
> multiplication.

That doesn't work if either a or b is a Decimal.  What *could* work is


def is_integer(num):
   return isinstance(num, (int, long))

def divide(a, b):
   if is_integer(a) and is_integer(b):
      return 1.0 * a / b
   else:
      return a / b

But why bother when you could just put "from __future__ import
division" at the top of the file?



From steve at REMOVETHIScyber.com.au  Sun Feb 12 09:03:39 2006
From: steve at REMOVETHIScyber.com.au (Steven D'Aprano)
Date: Mon, 13 Feb 2006 01:03:39 +1100
Subject: Is python very slow compared to C
References: <1139690972.344818.136870@f14g2000cwb.googlegroups.com>
	<1139694723.857673.263750@z14g2000cwz.googlegroups.com>
	
	<1139742200.155197.245490@g14g2000cwa.googlegroups.com>
Message-ID: 

On Sun, 12 Feb 2006 03:03:20 -0800, bearophileHUGS wrote:

> Steven D'Aprano>Very slow to do what, compared to what? The decay time
> of the tau meson?<
> 
> Probably every answer I can give you is wrong for you, so answering is
> almost useless... 

We do actually agree. You did explain why the speed of the language itself
is rarely the critical factor. My criticism is that whatever good your
post would have done was nullified by your opening comment stating that
Python is very slow -- a comment which I think is not only harmful, but
wrong, benchmarks like the one you linked to not withstanding.

I think it is wrong to call Python "very slow" just because it is slower
than some other language or languages, for the same reason it would be
wrong to describe the population of the UK as "very low" because 60
million people is a smaller number than China or India's one billion plus.
Doing so merely reinforces the premature optimizer's message that any
language that isn't C (and sometimes Lisp) is "not fast enough".

The benchmark you pointed to are of limited use for application
developers. (Their value to language designers is another story.) Given
that Ocaml is (say) 200 times faster than Python on average, it tells the
application developer virtually nothing about the performance of his
application. And that's what user's care about -- they couldn't care less
about binary trees or partial sums, they care about how long it takes to
render a JPEG, open an email, save their files, query the database,
display a window, and so forth. Few application level tasks are limited by
the speed of the language, not these days.

You don't believe me? Consider the following:

When you drag your mouse over text in a graphical text editor, the text
highlights. How much money would you be prepared to pay to make that
highlighting occur 200 times faster? $100? $1? One cent? Chances are you
wouldn't pay a thing, because it is already fast enough, and making it
faster is of zero value to you -- even if highlighting ten gigabytes of
text might be uncomfortably slow.

What about opening an email? How much would you pay to reduce the time it
takes to open and display an email from a hundredth of a second to
virtually instantaneously? I suggest that most people would consider 0.01s
to already be be "virtually instantaneously".

The important question isn't "is Python fast or slow?", it is "is Python
fast enough?". That's a question that doesn't have a simple answer,
because it depends. Fast enough to do what?

But, in general, more often than not, Python is fast enough. The extra
value of using something like Lua or Ocaml or even C is just not enough to
make up for the disadvantages of using those languages. 

Of course Python isn't always fast enough. Please don't waste your time
coming up with practical examples where pure Python is objectively too
slow for a certain task, because you won't be telling me anything I don't
already know. 

But the developer doesn't have to write pure Python, he can call a module
written in C, or change the algorithm, or find another way to accomplish
the same end result. Or even decide that for this specific task, Python is
not the language to use. These are all good solutions, but they don't mean
that Python is "very slow" in general. Even C is not always fast enough,
but we wouldn't say C is "very slow" just because it can't calculate the
first million Mersenne Primes in twenty milliseconds.


-- 
Steven.



From johnmc at velseis.com.au  Wed Feb 22 22:01:12 2006
From: johnmc at velseis.com.au (John McMonagle)
Date: Thu, 23 Feb 2006 13:01:12 +1000
Subject: Tix, spinboxes, and 1>=5
In-Reply-To: <1140662257.514090.170510@g47g2000cwa.googlegroups.com>
References: <1140662257.514090.170510@g47g2000cwa.googlegroups.com>
Message-ID: <1140663672.31572.9.camel@cornell>

On Wed, 2006-02-22 at 18:37 -0800, cjbackhouse at gmail.com wrote:
> This odd bug has been annoying me for several days now. I finally got
> round to making this, frankly hilarious, testcase:
> 
> 
> from Tix import *
> 
> def sayfive(num):
>     if num<5: print num,"< 5"
>     else: print num,">= 5"
> 
> sayfive(4)
> sayfive(6)
> rootwnd=Tk()
> Control(rootwnd,command=sayfive).pack()
> rootwnd.mainloop()
> 
> 
> So, our program starts, the first two lines executed write "4<6" "6>=5"
> as expected. Now the user changes the value in the spinner, and we get
> output like "1>=5". What magic is Tix pulling, and more importantly how
> the hell do I stop it?

This should fix your problem:

from Tix import *

def sayfive(num):
    num = int(num)
    if num<5: print num,"< 5"
    else: print num,">= 5"

sayfive(4)
sayfive(6)
rootwnd=Tk()
Control(rootwnd,command=sayfive).pack()
rootwnd.mainloop()


The entry in the spinbox is a string.




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.



From dstark7 at gmail.com  Sat Feb 18 15:40:55 2006
From: dstark7 at gmail.com (dmsbox2000-list1@yahoo.com)
Date: 18 Feb 2006 12:40:55 -0800
Subject: Tkinter / Aqua (OS X) question (canvas borders)
Message-ID: <1140295255.361958.82510@o13g2000cwo.googlegroups.com>

This is a beginner question.  I am using a Mac running OS X.  I have
TclTkAqua installed.  If I type:

import Tkinter

r = Tkinter.Tk()
c = Tkinter.Canvas(r)
c.pack()
c.create_line(0,0,100,0)

the line is not visible.  If I type:

c.create_line(3,4,100,4)

the line is visiable.  There appears to be an asymmetric "border"
around the inside of the canvas.  If I type

print c.cget('padx'), c.cget('pady')

I get zero.  How do I find out the size of the border?  Is this
specific to the Aqua version of Tk?

I have X Windows installed.  Would I be better off if I down loaded the
Unix version of Tk and Tkinter/python and compiled it for X?



From dananrg at yahoo.com  Sat Feb 25 08:54:55 2006
From: dananrg at yahoo.com (dananrg at yahoo.com)
Date: 25 Feb 2006 05:54:55 -0800
Subject: A bit off topic, but good web hosting for PostgreSQL/Python?
Message-ID: <1140875695.053987.158710@t39g2000cwt.googlegroups.com>

Seems like most web hosting providers support MySQL, but not
PostgreSQL. I need a web hosting account that supports PostgreSQL for a
particular personal project I'm working on (as well as Python, natch),
since PostGIS runs only on PostgreSQL. PostGIS is a nice open source
spatial database extension to PostgreSQL that allows you to store
geometry in the database.

Couldn't find a good PostgreSQL newsgroup so I thought I'd ask here.
Did find one weird one named Mailing something or other, but that may
be a gateway to a e-mail distribution list.



From __peter__ at web.de  Thu Feb  9 08:02:51 2006
From: __peter__ at web.de (Peter Otten)
Date: Thu, 09 Feb 2006 14:02:51 +0100
Subject: removing characters before writing to file
References: <1139452501.421306.44080@f14g2000cwb.googlegroups.com>
Message-ID: 

eight02645999 at yahoo.com wrote:

> i have some output that returns a lines of tuples eg
> 
> ('sometext1', 1421248118, 1, 'P ')
> ('sometext2', 1421248338, 2, 'S ')
> and so on
> ....
> 
> I tried this
> re.sub(r" '() ",'',str(output)) but it only get rid of the ' and not
> the braces. I need to write the output to a file such that
> 
> sometext1, 1421248118, 1, P
> sometext2, 1421248338, 2, S
> 
> I also tried escaping , re.sub(r" '\(\) ",'',str(output)) but also did
> not work
> How can i get rid of the braces before writing to file? thanks

I'd use a csv.writer:

>>> import csv, sys
>>> data = [
... ('sometext1', 1421248118, 1, 'P '),
... ('sometext2', 1421248338, 2, 'S ')
... ]
>>> w = csv.writer(sys.stdout)
>>> w.writerows(data)
sometext1,1421248118,1,P
sometext2,1421248338,2,S

Peter



From siv.hansen at gmail.com  Mon Feb 27 18:38:05 2006
From: siv.hansen at gmail.com (Cruella DeVille)
Date: 27 Feb 2006 15:38:05 -0800
Subject: Catch exceptions
Message-ID: <1141083485.798371.188440@u72g2000cwu.googlegroups.com>

In my application of bookmarks I get a filename as a parameter in one
of my methods. I want to catch the "FileNotFoundException" if the user
types an invalid filename. My code (that doesn't do what I want it to
do - namely print a nicely formatted error message, and no stack trace)

def openFile(self):
        try:
            return open(self.fileName, self.mode)
        except IOError:
            print("%s" %("The file was not found"))

But this one never occurs even if I write the name of a non-existing
file.

I also assign a variable, filePointer to a filename (the result of
openFile(self)), with a AttributeError
 if self.filePointer is None:
           raise AttributeError, "Assignment failed"

But I still get this stack trace (or trackback?)

How do I implement a try- except? Is it in my method where i open the
file or when I try to open the file in my "main-method"?



From sam at nuevageorgia.com  Mon Feb 27 23:44:58 2006
From: sam at nuevageorgia.com (SamFeltus)
Date: 27 Feb 2006 20:44:58 -0800
Subject: Python and Flash
In-Reply-To: <1139407620.948877.5820@g14g2000cwa.googlegroups.com>
References: <1139230361.675896.241920@z14g2000cwz.googlegroups.com>
	<1139235297.903689.244030@z14g2000cwz.googlegroups.com>
	<1139407620.948877.5820@g14g2000cwa.googlegroups.com>
Message-ID: <1141101898.725832.104260@e56g2000cwe.googlegroups.com>

Why not just have the Python on the server send a JSON string to the
Flash ap?  Easy easy.  Just use LoadVars on the Flash side.

All that SOAP and XML-RPC sounds might be an needless overcomplication.

Sam the Gardener

http://sonomasunshine.com



From "jay\" at (none)  Sat Feb 25 11:14:01 2006
From: "jay\" at (none) (none)
Date: Sat, 25 Feb 2006 09:14:01 -0700
Subject: Problem with Property
In-Reply-To: <95079633.aiQev8x7lQ@news.perlig.de>
References: 
	<95079633.aiQev8x7lQ@news.perlig.de>
Message-ID: 

Andr? Malo wrote:
> * none wrote:
> 
> 
>>classMyObject:
> 
> [...]
> 
> 
>>As you can see, the _getProperty() method gets called properly when I do
>>  'o.value'  but 'o.value = 123' does not seem to use the property
>>stucture.   I can't figure out why 'o.value=123' does not call
>>_setProperty()
>>
>>Any ideas?
> 
> 
> property only works as intended with new style classes.

duh.. I changed that to
	class MyObject(object):
and it worked fine

Thanks

Take care,
Jay


From R.Brodie at rl.ac.uk  Wed Feb 22 08:46:20 2006
From: R.Brodie at rl.ac.uk (Richard Brodie)
Date: Wed, 22 Feb 2006 13:46:20 -0000
Subject: Python CGI not working in Firefox but does in IE
References: <1140615651.847586.258300@f14g2000cwb.googlegroups.com>
Message-ID: 


"Harlin Seritt"  wrote in message 
news:1140615651.847586.258300 at f14g2000cwb.googlegroups.com...

> [CODE]
> print 'Content-type: text/plain\n'

That's your problem. You've said text/plain when you meant text/html.





From johnjsal at NOSPAMgmail.com  Mon Feb 13 16:03:07 2006
From: johnjsal at NOSPAMgmail.com (John Salerno)
Date: Mon, 13 Feb 2006 21:03:07 GMT
Subject: cyclic data structures
In-Reply-To: 
References: 
	
Message-ID: 

Peter Decker wrote:

> 'L' is a pointer to a list. You are now adding that pointer to the
> very list it points to.

I understand that, but I guess I just don't see how this creates 
anything other than a list that refers to [1, 2], and then refers again 
to [1, 2], to create [1, 2, [1, 2]].

L.append(L) basically creates this, I think:

[1, 2, L]

Now, assuming that's correct, and since L points to the list [1, 2], why 
can't '[1, 2]' be substituted for the 'L' and then the list is closed?


From peter at engcorp.com  Mon Feb 13 20:08:15 2006
From: peter at engcorp.com (Peter Hansen)
Date: Mon, 13 Feb 2006 20:08:15 -0500
Subject: Jedit
In-Reply-To: 
References: 
Message-ID: 

ziggy wrote:
> Just wondering if there is something out there like Jedit, but written 
> in python ( not just supporting, but actually written in it.. )
> 
> Nothing large like Stanzi's or Boa.. Just something quick and simple, 
> with code completion, and a debugger..

Is that last part a joke?  "Quick and simple", but with a debugger too?

Anyway, peruse http://wiki.python.org/moin/PythonEditors and see if any 
meet your requirements.

-Peter



From lycka at carmen.se  Fri Feb  3 06:00:52 2006
From: lycka at carmen.se (Magnus Lycka)
Date: Fri, 03 Feb 2006 12:00:52 +0100
Subject: Another try at Python's selfishness
In-Reply-To: <1138918102.863033.298700@o13g2000cwo.googlegroups.com>
References: <1138918102.863033.298700@o13g2000cwo.googlegroups.com>
Message-ID: 

n.estner at gmx.de wrote:
> What do you think?

The impression I get from your suggestion is that you
haven't really understood Python. I'm sure that some
things could be better designed or better documented,
but your suggestions would actually make things worse.
Sorry.

Today, Python has a syntactic shortcut. If 'a' is an
instance of class 'A', a.f(x,y,z) is a shortcut for
A.f(a,x,y,z). If you don't use the shortcut, there is
no magic at all, just the unusual occurence of a type
check in Python! If you use the shortcut, Python code
looks just like most other OO languages. This isn't
very magical.

What you suggest doesn't remove magic, but it introduces
a bunch of inconsistencies!

> But:
>     Foo.__dict["bar"]__(1,2,3)
> Does work.

I agree that this isn't completely clean, and there are
some other ways in which the distinction between functions,
unbound methods and bound methods seem a bit quirky to me.
I don't think the problem is in the syntax though, and if
it had been a real problem, it would had been solved.

>     class Foo:
>         def self.bar(a,b):
>             return a+b
>     Foo().bar(1,2) => 3

First of all, you are using a really poor example of a "method",
since it doesn't use any attributes of the Foo instance. That
function doesn't seem to belong in that class at all. If it
should be in the class, it should be a static method, so self
should not be involved at all. In modern Python it would look
like this:

class Foo(object):
     @staticmethod
     def bar(a, b):
         return a+b

Anyway, my impression is that you haven't fully understood how
namespaces work in Python, at least not the distinction between
class namespaces and instance namespaces. Please study this a
bit more. Hopefully, you'll find enlightenment and things will
fall into place for you.

You are really giving "self" a magic meaning with your suggestion
which isn't needed at all. So far, the existence of x.y somewhere
in Python always implied that x was already introduced explicitly
in the program, and you suggest that we violate that both in the
"def self.x"-row, and inside the methods when we access attributes.

Provoking a language can be a way of learning it, and provoking
people can sometimes lead to new insights, but it's important to
have an open mind. When learning a new language, it's probably
better to try to adapt oneself to it, rather than the other way
around.


From bonono at gmail.com  Fri Feb 10 05:22:52 2006
From: bonono at gmail.com (bonono at gmail.com)
Date: 10 Feb 2006 02:22:52 -0800
Subject: Question about idioms for clearing a list
In-Reply-To: 
References: 
	<1139231464.914400.37100@g44g2000cwa.googlegroups.com>
	
	
	<43E7F59B.9070009@REMOVEMEcyber.com.au>
	
	<1139300825.858426.12680@o13g2000cwo.googlegroups.com>
	
	
	
	
	
	
	
	
Message-ID: <1139566972.110582.247310@g43g2000cwa.googlegroups.com>


Magnus Lycka wrote:
>  >>> class BryansList(list):
> ...     add=list.append
> ...     def clear(self):
> ...         del self[:]
> ...
>  >>> b = BryansList([1,2,3,4,5])
>  >>> b
> [1, 2, 3, 4, 5]
>  >>> b.add(6)
>  >>> b.clear()
>  >>> b
> []
>
> Happy now? You can keep it, I don't need it. :)
> Most of us consider minimal interfaces a virtue.

What kind of performance penalty are we talking about here ? list being
such a fundamental thing, no one would like to use a slower version
just for the clear/add method. And if it is a "use when you really need
to", it would make the code harder to understand as it would be
"sometimes it is BryansList, sometimes it is builtin list".

That said, I don't find clear() to be useful as unless one needs to
pass around a single copy of list object around and saved them for
future use(which can be a source of subtle bug), just lst=[] is usually
good enough for localized usage.



From paulgeeleher at gmail.com  Sun Feb  5 16:57:19 2006
From: paulgeeleher at gmail.com (sophie_newbie)
Date: 5 Feb 2006 13:57:19 -0800
Subject: Strange behavior with os call in cgi script
In-Reply-To: <43e665f1$1@news.uni-ulm.de>
References: <1139171873.431432.195080@f14g2000cwb.googlegroups.com>
	<43e665f1$1@news.uni-ulm.de>
Message-ID: <1139176638.972414.19590@g47g2000cwa.googlegroups.com>

OK, interesting, but just how dow I print he environment in the
program??



From venkatbo at yahoo.com  Tue Feb 28 20:21:47 2006
From: venkatbo at yahoo.com (venkatbo at yahoo.com)
Date: 28 Feb 2006 17:21:47 -0800
Subject: Cross compile generation of .pyc from .py files...
Message-ID: <1141176107.234667.93210@e56g2000cwe.googlegroups.com>

Hi all,

We've managed to cross-compile (from i686 targeting ppc) python (2.4.2)
binaries and
extension modules.

However we cannot figure out how to cross-compile the .py (of
distribution) files and
generate the .pyc files for the target ppc from an i686 system.  Is it
possible to cross
compile .pyc files from .py files?

Some of the errors we get when we run 'python -v' on the target system
include:
....
# /usr/lib/python2.4/site.pyc has bad magic
import site # from /usr/lib/python2.4/site.py

# /usr/lib/python2.4/types.pyc has bad magic
import types # from /usr/lib/python2.4/types.py
.....

Thanks,
/venkat



From dejan.wirusrodiger at ck.t-com.hr  Thu Feb 23 05:53:56 2006
From: dejan.wirusrodiger at ck.t-com.hr (Dejan Rodiger)
Date: Thu, 23 Feb 2006 11:53:56 +0100
Subject: =?ISO-8859-2?Q?Re=3A_=27rar=27_is_not_recognized_as_?=
	=?ISO-8859-2?Q?an_internal_or_external_command=A3=BF=A3=BF=A3=BF?=
	=?ISO-8859-2?Q?=A3=BF?=
In-Reply-To: 
References: 
Message-ID: 

???????? said the following on 23.02.2006 10:03:
> rar_cmd = r'"D:\Program Files\WinRAR\rar.exe" a -idcdp %s %s' % (target,' '.join(source))

You can't cd to d:\Program Files\WinRAR and then call rar

You have to call rar with full path.

from subprocess import *
retcode = call([r'"D:\Program Files\WinRAR\rar.exe"', 'a', '-idcdp', target,
' '.join(source)])
if retcode == 0:
	print "everything OK"
-- 
Dejan Rodiger - PGP ID 0xAC8722DC
Delete wirus from e-mail address


From fredrik at pythonware.com  Mon Feb 27 12:21:14 2006
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Mon, 27 Feb 2006 18:21:14 +0100
Subject: Unicode and MoinMoin
References: <1141017252.469296.139410@v46g2000cwv.googlegroups.com>
	<6qwMf.17099$yK1.13214@news-server.bigpond.net.au>
Message-ID: 

Neil Hodgson wrote:

> > The only issue I'm having relates to Unicode. MoinMoin and python are
> > pretty unforgiving about files that contain Unicode characters that
> > aren't included in the coding properly. I've spent hours reading about
> > Unicode, and playing with different encoding/decoding commands, but at
> > this point, I just want a hacky solution that will ignore the
> > improperly coded characters or replace them with placeholders.
>
>     Call the codec with the errors argument set to "ignore" or "replace".
>
>  >>> unicode('AUTHOR: blahblah\n\nTITLE: Reading Course Readings... G.
> A. \x96 For references see blahblah.\n\n\n-----\n\n', 'utf8')
> Traceback (most recent call last):
>    File "", line 1, in ?
>    File "c:\python24\lib\encodings\utf_8.py", line 16, in decode
>      return codecs.utf_8_decode(input, errors, True)
> UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 58:
> unexpected code byte
>  >>> unicode('AUTHOR: blahblah\n\nTITLE: Reading Course Readings... G.
> A. \x96 For references see blahblah.\n\n\n-----\n\n', 'utf8', 'replace')
> u'AUTHOR: blahblah\n\nTITLE: Reading Course Readings... G. A. \ufffd For
> references see blahblah.\n\n\n-----\n\n'
>
>     BTW, its probably in Windows-1252 where it would be a dash.
> Depending on your context it may pay to handle the exception instead of
> using "replace" and attempt interpreting as Windows-1252.

here's one way to explicitly deal with 1252 gremlins:

    http://effbot.org/zone/unicode-gremlins.htm







From fredrik at pythonware.com  Fri Feb 17 03:57:36 2006
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Fri, 17 Feb 2006 09:57:36 +0100
Subject: file.read problem
References: <1140158220.388409.87650@g47g2000cwa.googlegroups.com>
	<1140159632.758960.318580@g44g2000cwa.googlegroups.com>
Message-ID: 

"wscrsurfdude" wrote:

> >Try opening the file in 'rbU' mode. This will use universal newline mode
> >and convert all carriage returns to line feeds.
>
> I tried this, but as you say, now there are 0x0A bytes extra in my
> files, is there also a possibility to let all these things out, and
> just get the file.
>
> I am working on a script to get parts of raw data out of a file, and
> the data I read has to be the data written in the file without CR or
> LF.

what kind of file are you reading?  if it's a text file, it's supposed to have
LF in it (or CR LF if you read it in binary mode); the LF:s are there to tell
you where each line ends.

if it's a binary file, open with mode "rb".







From f.heleno at netcabo.pt  Thu Feb  2 08:30:58 2006
From: f.heleno at netcabo.pt (Silva)
Date: 2 Feb 2006 05:30:58 -0800
Subject: Resources
Message-ID: <1138887058.068827.69260@o13g2000cwo.googlegroups.com>

As requested:
www.guardyannet.com.br
www.tra.web.pt
http://www.cita.es/veracidad/expolingua/Brasil
http://www.collegeboard.com/csearch/majors_careers/profiles/careers/105464.html
http://www.guardyannet.com.br/
http://www.guiagratis.com.br/
http://www.clubedoprofessor.com.br/traduz/
http://poloclup.linguateca.pt/artur/
http://baixaki.ig.com.br/categorias/cat18_1.htm
http://www.jucergs.rs.gov.br/sitejucergs/Site/juc-trd_1.htm
http://www.abrates.com.br/
http://www.servicosgratis.com.br/categoria.php?id=30



From martin at v.loewis.de  Sun Feb 12 16:59:08 2006
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Sun, 12 Feb 2006 22:59:08 +0100
Subject: Single-file executables
In-Reply-To: 
References: 	<43EE7C2A.3040102@v.loewis.de>
	
Message-ID: <43EFAFAC.9080200@v.loewis.de>

Thomas Heller wrote:
> I wonder if anyone is actually using freeze on Windows, with scripts 
> that use, say, pywin32 and wxPython.

Interesting question. I've never done so myself (only on Linux and
Solaris), and given the relatively small interest in having a static
Python library on Windows, I guess the answer is no (or: everybody
doing that has managed to deal with the build process themselves).

I would probably go for a mingw static build if I had to attempt this.

Regards,
Martin


From peter at engcorp.com  Tue Feb 14 06:04:45 2006
From: peter at engcorp.com (Peter Hansen)
Date: Tue, 14 Feb 2006 06:04:45 -0500
Subject: Python / Apache / MySQL
In-Reply-To: <0001HW.C01772E1000952B1F0407550@news.individual.de>
References: <1139907519.427789.188760@g14g2000cwa.googlegroups.com>		<0001HW.C01764D700060858F0407550@news.individual.de>	<43f1aebb$0$1728$636a55ce@news.free.fr>
	<0001HW.C01772E1000952B1F0407550@news.individual.de>
Message-ID: 

Kalle Anke wrote:
> I always thought that a SQLlite database "belonged" to a single process, can 
> a database be used by several processes?

Depending on what you mean by "belong", that's either true or false. 
Certainly multiple processes can access a SQLite database, although as 
the documentation clearly describes if those processes are making 
_frequent updates_ it's not the best solution and another database might 
be more suitable.

> Let's say I would build a small web application that would be used by a small 
> number of people/processes and it wouldn't be anything fancy just basic 
> "selects". What would be the choice for this?

SQLite.  (As but one option, but "just basic selects" is certainly 
included in the set of suitable conditions for SQLite use.)

> What about speed? I've always had the impression that while PostgreSQL is 
> more complete than MySQL it's also slower.

Don't optimize prematurely?  If you use something like SQLObject, or any 
other means of abstracting yourself away from the details of a specific 
datbase, you won't be particularly tied to it if you decide you need 
improved performance, or sophistication, or whatever.

> Sorry, if these are really stupid questions but ...

They're not.



From __peter__ at web.de  Fri Feb 10 03:53:41 2006
From: __peter__ at web.de (Peter Otten)
Date: Fri, 10 Feb 2006 09:53:41 +0100
Subject: breaking from loop
References: <1139557074.938577.281250@f14g2000cwb.googlegroups.com>
Message-ID: 

Ritesh Raj Sarraf wrote:

> Following is the code:
> 
> def walk_tree_copy(sRepository, sFile, sSourceDir, bFound = None):
>     try:
>         if sRepository is not None:
>             for name in os.listdir(sRepository):
>                 path = os.path.join(sRepository, name)
>                 if os.path.isdir(path):
>                     walk_tree_copy(path, sFile, sSourceDir, bFound)
>                 elif name.endswith('.foo') or name.endswith('.bar'):
>                     if name == sFile:

Pick /one/ the conditions

- file name must be ...
- file must end with ... or ...

>                         try:
>                             shutil.copy(path, sSourceDir)
>                         except IOError, (errno, errstring):
>                             errfunc(errno, errstring)
>                         except shutil.Error:
>                             print name + " is available in " +
> sSourceDir + "Skipping Copy!"
>                         bFound = True
>                         break
>                         return bFound
>     except OSError, (errno, strerror):
>         print errno, strerror
> 
> This function allows me to walk into a directory based tree and search
> for files ending with .foo and .bar. My requirement is to copy
> .foo/.bar.
> Say in directory temp=>test=>test.bar is found. So shutil.copy will
> copy it. I want that once the copy is done, it should make bFound =
> True and get out.
> But since test directory is under temp, work_tree_copy makes two calls
> of the same function _but_ break only is able to get out from the inner
> call.
> 
> Where am I wrong in this code ? Is there a better way to implement it ?

An implementation on top of os.walk() can simplify things a bit:

import os
import shutil

def files(root):
    for path, folders, files in os.walk(root):
        for file in files:
            yield path, file

def copy_first_match(repository, filename, dest_dir): # aka walk_tree_copy()
    for path, file in files(repository):
        if file == filename:
            shutil.copy(os.path.join(path, file), dest_dir)
            return True
    return False

files() and os.walk() take care of the recursion, and you can just break or
return from the loop in copy_first_match(). 

Peter



From rzantow at gmail.com  Thu Feb 23 15:39:38 2006
From: rzantow at gmail.com (Rick Zantow)
Date: Thu, 23 Feb 2006 15:39:38 -0500
Subject: "Temporary" Variable
References: <1140665472.203495.7570@g44g2000cwa.googlegroups.com>
	<43FD6645.3020201@REMOVEMEcyber.com.au>
	<1140725159.143882.202630@j33g2000cwa.googlegroups.com>
Message-ID: 

darthbob88 at gmail.com wrote in news:1140725159.143882.202630
@j33g2000cwa.googlegroups.com:

> 
> Steven D'Aprano wrote:
>> You could try this:
>>
>> while 1:
>>      var = raw_input("Give me some data! ")
>>      if var == "some data":
>>          print "Success!"
>>          break
>>      else:
>>          print "No good, try again."
> That works fine with strings and when "some_data" is hardcoded. I run
> into trouble when "some data" is replaced with a number, unquoted. It
> simply says "No good, etc"

Raw_input isn't giving you what you think it is. You're comparing it to 
an integer, not a string. Does that help?



From bblais at bryant.edu  Thu Feb 16 18:40:47 2006
From: bblais at bryant.edu (Brian Blais)
Date: Thu, 16 Feb 2006 18:40:47 -0500
Subject: calculating on matrix indices
Message-ID: <43F50D7F.8010108@bryant.edu>

Hello,

In my attempt to learn python, migrating from matlab, I have the following problem. 
Here is what I want to do, (with the wrong syntax):

from numpy import *

t=arange(0,20,.1)
x=zeros(len(t),'f')

idx=(t>5)
tau=5
x[idx]=exp(-t[idx]/tau)  # <---this line is wrong (gives a TypeError)

#------------------

what is the best way to replace the wrong line with something that works: replace all 
of the values of x at the indices idx with exp(-t/tau) for values of t at indices idx?

I do this all the time in matlab scripts, but I don't know that the pythonic 
preferred method is.



			thanks,

				bb


-- 
-----------------

             bblais at bryant.edu
             http://web.bryant.edu/~bblais


From jimlewis at miclog.com  Sat Feb 11 05:03:46 2006
From: jimlewis at miclog.com (swisscheese)
Date: 11 Feb 2006 02:03:46 -0800
Subject: Shortest prime number program
Message-ID: <1139652226.869102.310180@g14g2000cwa.googlegroups.com>

I figured someone out there must have written a minimal code size prime
number generator. I did not find one after a bit of searching around.
For primes up to 100 the best I could do was 70 characters (including
spaces):

r=range(2,99)
m=[x*y for x in r for y in r]
[x for x in r if not x in m]



From fuzzyman at gmail.com  Wed Feb 15 05:45:52 2006
From: fuzzyman at gmail.com (Fuzzyman)
Date: 15 Feb 2006 02:45:52 -0800
Subject: [ANN] Movable Python 1.0.1
Message-ID: <1140000352.656993.266690@g43g2000cwa.googlegroups.com>

I'm pleased to be able to announce the release of `Movable Python 1.0.1
`_. This includes the
release of **Movable Python** for Python 2.2.

To obtain it, visit the `Movable Python Shop
`_.

Existing users of Movable Python can go to the groups area and simply
download an updated copy.

.. note::

    For a heads up about possible features in the *next* version of a
Movable Python, visit the `Voidspace Techie Blog
`_.

What's New ?
==========

Added support for the ``-m`` command line option. This works for
modules contained within the ``library.zip``, as well as other modules
on ``sys.path``.

**Movable Python** now *ignores* (with warnings) the unsupported Python
command line options.

Error messages are now printed to ``sys.stderr``.

Can run '.pyc' and '.pyo' files.

``customize.py`` now run when launching an interactive interpreter.

Renamed the function to go interactive to ``interactive_mode``.

New variable available in ``customize.py``. ``interactive``, this is
``True`` if launching an interactive interpreter. This allows you to
customize the environment differently for interactive sessions.

Add the ``lib`` directory (etc) to ``sys.path`` before entering
interactive mode. (BUGFIX)

``pywin32`` extensions now import properly (even on machines that don't
have them installed). (BUGFIX) {sm;:oops:}

Added the extra files for `Firedrop2 Macros
`_.

Changes for Python 2.2 compatibility. Distribution for Python 2.2
built.

What is Movable Python ?
===================

**Movable Python** is a distribution of Python for Windows that doesn't
need to be installed. It easily fits onto a USB memory stick. Python on
a stick.

It is integrated with SPE, the Python IDE, to make **Movable Python** a
portable Build, Test, and Run environment. It has a nice GUI to launch
programs and control its behaviour.

Movable Python is useful in the following situations:

* Machines where you can't install programs.
* Where you need a portable 'Build, Test, and Run' Python environment.
* Having several versions of Python on the same machine for
forward/backward compatibility testing.
* Easily deploying Python scripts without having to install Python.
* Try before you buy - test Python without having to install it,
including new versions .
* 'Python Runtime Environment'. '``.py``' files can be associated with
movpy.

For more information, see `An Introduction to Movable Python
`_.


Known Issues
==========

* There are problems with the ``pywin32`` extensions and Python 2.2.
They are included but may not all function correctly.
* ``-m`` doesn't work with modules in ``library.zip`` under Python 2.2.
This may or may not be resolvable.
* **Movable Python** doesn't yet handle ``from __future__ import ...``
statements in scripts that are run. This will be fixed.



From FASTedob at XXhomemail.YEScom.OZau  Wed Feb  8 02:27:29 2006
From: FASTedob at XXhomemail.YEScom.OZau (Eddie)
Date: Wed, 08 Feb 2006 07:27:29 GMT
Subject: RPy / R
In-Reply-To: 
References: 
Message-ID: <43e99d61@news.comindico.com.au>

Hi Jason

I had more success, being able to run a few test programs.
Not sure why yours would be crashing - I have a similar setup (Win XP 
SP2 with all updates) - my version of Python is the Activestate download 
(ActivePython-2.4.2.10-win32-x86.msi). Have you installed Numeric?
If all else fails might be worth trying to unistall Python and 
installing the Activestate version (which includes the Win32 extensions).

Good luck

Eddie

jason wrote:
> Hello:
> 
> I installed the following:
> 
> python-2.4.2.msi
> pywin32-207.win32-py2.4.exe
> R-2.2.1-win32.exe
> rpy-0.4.6-R-2.0.0-to-2.2.1-py24.win32.exe
> 
> on a Windows XP (SP2) box.
> 
> [SNIP]
> 
> Is this a setup issue? Thanks for your help.
> 
> 


From jcoleman at franciscan.edu  Sat Feb 25 14:30:45 2006
From: jcoleman at franciscan.edu (John Coleman)
Date: 25 Feb 2006 11:30:45 -0800
Subject: Is Python a Zen language?
In-Reply-To: <9o1Mf.39804$H71.16633@newssvr13.news.prodigy.com>
References: <1140876556.080086.252390@e56g2000cwe.googlegroups.com>
	<9o1Mf.39804$H71.16633@newssvr13.news.prodigy.com>
Message-ID: <1140895845.832636.269460@e56g2000cwe.googlegroups.com>


Bryan Olson wrote:
> John Coleman wrote:
> >    I have a rough classification of languages into 2 classes: Zen
> > languages and tool languages. A tool language is a language that is,
> > well, a *tool* for programming a computer. C is the prototypical tool
> > language. Most languages in the Algol family are tool languages. Visual
> > Basic and Java are also tool languages. On the other hand, a Zen
> > language is a language which is purported to transform your way of
> > thinking about programming. Lisp, Scheme, Forth, Smalltalk and (maybe)
> > C++ are Zen languages.
>
> I think that's a horrible classification. Every language is both.
> "Transform your way of thinking" from what? There is no
> distinguished canonical view of what a programming language looks
> like, from which all others must be strange and wondrous
> transformations.
>
> Lisp and Forth are not tools for programming a computer? Of course
> they are. Algol and Java don't transform people's thinking about
> programming? Nonsense.
>
>
> --
> --Bryan

You seem to have completly overlooked both the hedge word "rough" in my
first sentence and the qualifications in my third paragraph. I probably
was not sufficiently clear that I was describing some fairly sunjective
impressions.  It is a simple observation that devotees of the Scheme
language view their language as more than *just* a tool for programming
computers. To quote from the introduction to the first edition of SICP:

"we want to establish the idea that a computer language is not just a
way of getting a computer to perform operations but rather that it is a
novel formal medium for expressing ideas about methodology"
(http://mitpress.mit.edu/sicp/full-text/book/book.html).
It is also a simple observation that experts in VBScript *don't* walk
around talking like that. Scheme and VBScript are of course both Turing
complete, but they seem to have radically different cultures. Do you
disagree? Or, if you agree that there is a difference but don't like
the words "Zen" vs. "tool" to describe it, how would you articulate the
difference?

Again, just curious.

-John Coleman



From tim.golden at viacom-outdoor.co.uk  Wed Feb 15 06:37:25 2006
From: tim.golden at viacom-outdoor.co.uk (Tim Golden)
Date: Wed, 15 Feb 2006 11:37:25 -0000
Subject: choose and open a folder in Windows
Message-ID: <9A28C052FF32734DACB0A288A3533991044D2567@vogbs009.gb.vo.local>

[palo]

| But I didn't find how to make windows to open
| a given directory in file expolorer)
| P.

At the risk of suggesting the obvious, have you tried:


import os
os.system ("explorer.exe c:\\temp")


or 


import os
os.startfile ("c:\\temp")


or something similar?

TJG

________________________________________________________________________
This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
________________________________________________________________________


From reply.in.the.newsgroup at my.address.is.invalid  Thu Feb  2 06:57:11 2006
From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman)
Date: Thu, 02 Feb 2006 12:57:11 +0100
Subject: redirect and python
References: <1138865526.286565.282150@g14g2000cwa.googlegroups.com>
Message-ID: <5rs3u1t6g1rpeqj1179kui3pgbaakpksf6@4ax.com>

questions?:
>os.system("wget http://blah blah blah")

Why don't you use urllib(2) directly in Python?

-- 
Ren? Pijlman


From trentm at ActiveState.com  Mon Feb 20 18:50:33 2006
From: trentm at ActiveState.com (Trent Mick)
Date: Mon, 20 Feb 2006 15:50:33 -0800
Subject: Activestate python installation
In-Reply-To: <87r760n3tv.fsf@bigfoot.com>
References: <1140243666.990365.131220@f14g2000cwb.googlegroups.com>
	<87r760n3tv.fsf@bigfoot.com>
Message-ID: <20060220235033.GB13482@activestate.com>

[Chris Smith wrote]
> >>>>> "mik3" == mik3   writes:
> 
>     mik3> hi this is a question regarding installing Activestate
>     mik3> python whenever i try to install the latest Activestate
>     mik3> Python on WinXP SP2, it gives me error saying "The wizard
>     mik3> was interrupted before Activestate 2.4.2 could be completely
>     mik3> installed. Your system has not been modified ....."  any
>     mik3> ideas why this is going on?  thanks
> 
> Administrator?
> Writeable drive?
> Is there an install log file you could locate?

As "David" mentioned on activepython at listserv.activestate.com, could
this be due to an anti-virus program aborting the install on you?

You could generate an install log to see if that yields some clues:
    http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/installnotes.html#install_logging

Cheers,
Trent

-- 
Trent Mick
TrentM at ActiveState.com


From gregtech at wp.pl  Mon Feb 20 18:02:54 2006
From: gregtech at wp.pl (Grzegorz Smith)
Date: Tue, 21 Feb 2006 00:02:54 +0100
Subject: decorator and function local variable
Message-ID: <21b0qx59zcqo$.5dmxxfkxl7h3$.dlg@40tude.net>

Hi all. I have got situation that I need make parameter injection into
function and I want that parametet be a local variable of that function.
eg. something like
def decorator():
	
@decorator
def myfun():
   a = 20

and in myfun i can use b wariable like that:
b = "ok it's working"
I try to use sample decorators from:
http://www.python.org/moin/PythonDecoratorLibrary 
but unsuccesfully. Does anyone know hot to achieve this? Or is it possible?
Thanks for any help


From deets at nospam.web.de  Sun Feb 26 15:11:20 2006
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sun, 26 Feb 2006 21:11:20 +0100
Subject: Do I need to convert string to integer in python?
In-Reply-To: <1140983754.000103.104710@i40g2000cwc.googlegroups.com>
References: <1140983754.000103.104710@i40g2000cwc.googlegroups.com>
Message-ID: <46egb9FanujjU1@uni-berlin.de>

Allerdyce.John at gmail.com schrieb:
> Do I need to convert string to integer in python? or it will do it for
> me (since dynamic type)?
> 
> In my python script, I have this line:
>     x /= 10;
> 
> when i run it, I get this error:
> TypeError: unsupported operand type(s) for /=: 'unicode' and 'int'
> 
> I want to divide x by 10 and assign that value back to x.

Yes, you have to convert beforehand. Dynamic typing and weak typing (as in perl or php) aren't the same thing.

Dynamic typing means that you can rebind a variable (or better name) at runtime to contain a value with a new type. Weak 
typing means that an object is reinterpreted as a value of another type when needed - and (often) leads to difficult errors.


Regards,

Diez


From ptmcg at austin.rr._bogus_.com  Tue Feb 21 23:37:50 2006
From: ptmcg at austin.rr._bogus_.com (Paul McGuire)
Date: Wed, 22 Feb 2006 04:37:50 GMT
Subject: Basic coin flipper program - logical error help
References: <1140567243.251982.255620@g14g2000cwa.googlegroups.com>
	
	
	<1140578858.586591.243900@g43g2000cwa.googlegroups.com>
Message-ID: 

 wrote in message
news:1140578858.586591.243900 at g43g2000cwa.googlegroups.com...
>
> John Zenger wrote:
> > Also, with the functional programming tools of map, filter, and lambda,
> > this code can be reduced to just six lines:
> >
> > import random
> >
> > flips = map(lambda x: random.randrange(2), xrange(100))
> > heads = len(filter(lambda x: x is 0, flips))
> > tails = len(filter(lambda x: x is not 0, flips))
>
> Or a filter/map/lambda free way:
>
> heads = sum(random.randrange(2) for x in xrange(100))
> tails = 100 - heads
>
sort, then groupby.


import itertools
import random
h,t = [len(list(g)) for k,g in itertools.groupby(sorted([random.randrange(2)
for i in xrange(100)]))]
print h,t





From dickey at saltmine.radix.net  Wed Feb  8 19:16:28 2006
From: dickey at saltmine.radix.net (Thomas Dickey)
Date: Thu, 09 Feb 2006 00:16:28 -0000
Subject: Replacing curses
References: 
	<43E9234B.6030108@v.loewis.de>
	
	<11ujl3ibdh7vne1@corp.supernews.com>
	
Message-ID: <11ul2eskh5q2pab@corp.supernews.com>

Ian Ward  wrote:
> Thomas Dickey wrote:
>> hmm - I've read Urwid, and most of the comments I've read in that regard
>> reflect problems in Urwid.  Perhaps it's time for you to do a little analysis.
>> 
>> (looking forward to bug reports, rather than line noise)

> A fair request.  My appologies for the inflammatory subject :-)

> When trying to check for user input without waiting I use code like:
> window_object.nodelay(1)
> curses.cbreak()
> input = window_object.getch()

> Occasionally (hard to reproduce reliably) the cbreak() call will raise
> an exception, but if I call it a second time before calling getch the
> code will work properly.  This problem might be related to a signal
> interrupting the function call, I'm not sure.

perhaps a more complete test-case would let me test it and see.

> Also, screen resizing only seems to be reported once by getch() even if
> the user continues to resize the window.  I have worked around this by
> calling curses.doupdate() between calls to getch(). Maybe this is by design?

Or perhaps it's some interaction with python - I don't know.
The applications that I use with resizing (and ncurses' test
programs) work smoothly enough.

> Finally, the curses escape sequence detection could be broadened. The
> top part of the curses_display module in Urwid defines many escape
> sequences I've run into that curses doesn't detect.

That's data (terminfo).  ncurses is data-driven, doesn't "detect"
features of the terminal (though it does of course use environment
variables for locale, etc.).

xterm's terminfo lists a lot of function keys, for instance.

The limit for predefined function-key names for terminfo is 60,
but ncurses can accept extended terminfo descriptions (but I like to
limit the length and style of names so it's possible to access them
from termcap).  One could define names like shift_f1, but then termcap
applications couldn't see them.  (The last I knew, slang doesn't either,
but that's a different thread).

That's been true for about 6 years.

Current xterm's terminfo includes these names which apply to your
comment:  The ones on the end are extended names that ncurses' tic
deduces from the terminfo file when it compiles it:

comparing xterm-new to xterm-xf86-v44.
    comparing booleans.
    comparing numbers.
    comparing strings.
        kf49: '\EO3P', NULL.
        kf50: '\EO3Q', NULL.
        kf51: '\EO3R', NULL.
        kf52: '\EO3S', NULL.
        kf53: '\E[15;3~', NULL.
        kf54: '\E[17;3~', NULL.
        kf55: '\E[18;3~', NULL.
        kf56: '\E[19;3~', NULL.
        kf57: '\E[20;3~', NULL.
        kf58: '\E[21;3~', NULL.
        kf59: '\E[23;3~', NULL.
        kf60: '\E[24;3~', NULL.
        kf61: '\EO4P', NULL.
        kf62: '\EO4Q', NULL.
        kf63: '\EO4R', NULL.
        kind: '\E[1;2B', NULL.
        kri: '\E[1;2A', NULL.
        kDN: '\E[1;2B', NULL.
        kDN5: '\E[1;5B', NULL.
        kDN6: '\E[1;6B', NULL.
        kLFT5: '\E[1;5D', NULL.
        kLFT6: '\E[1;6D', NULL.
        kRIT5: '\E[1;5C', NULL.
        kRIT6: '\E[1;6C', NULL.
        kUP: '\E[1;2A', NULL.
        kUP5: '\E[1;5A', NULL.
        kUP6: '\E[1;6A', NULL.

-- 
Thomas E. Dickey
http://invisible-island.net
ftp://invisible-island.net


From steve.horsley at gmail.com  Wed Feb 15 13:59:52 2006
From: steve.horsley at gmail.com (Steve Horsley)
Date: Wed, 15 Feb 2006 18:59:52 +0000
Subject: is socket thread safe?
In-Reply-To: <1139912679.559724.131020@f14g2000cwb.googlegroups.com>
References: <1139912679.559724.131020@f14g2000cwb.googlegroups.com>
Message-ID: 

e2wugui at gmail.com wrote:
> thread1:
>     while 1:
>         buf = s.read()
>         process(buf)
> 
> thread2:
>     while 1:
>         buf = getdata()
>         s.write(buf)
> 

It is safe, but watch out for this gotcha: If thread B calls 
s.close() while thread A is blocked in s.read(), thread A will 
never return from the read. My preferred solution is to set 
socket timeout to a few seconds, and loop checking a status flag 
so I know when to quit.

Steve


From struggleyb at gmail.com  Sat Feb 18 08:40:04 2006
From: struggleyb at gmail.com (Bo Yang)
Date: Sat, 18 Feb 2006 21:40:04 +0800
Subject: How many web framework for python ?
In-Reply-To: <4cldv1pi01vrkmfj7v1adpfhkdffvoa6jv@4ax.com>
References: 
	<4cldv1pi01vrkmfj7v1adpfhkdffvoa6jv@4ax.com>
Message-ID: <43F723B4.80905@gmail.com>

Thank you very much !


From steve at REMOVETHIScyber.com.au  Wed Feb 15 07:14:46 2006
From: steve at REMOVETHIScyber.com.au (Steven D'Aprano)
Date: Wed, 15 Feb 2006 23:14:46 +1100
Subject: Which is faster? (if not b in m) or (if m.count(b) > 0)
References: <1139976842.179801.285400@z14g2000cwz.googlegroups.com>
	
Message-ID: 

On Wed, 15 Feb 2006 08:44:10 +0100, Marc 'BlackJack' Rintsch wrote:

> In <1139976842.179801.285400 at z14g2000cwz.googlegroups.com>, Farel wrote:
> 
>> Which is Faster in Python and Why?
> 
> ``if not b in m`` looks at each element of `m` until it finds `b` in it
> and stops then.  Assuming `b` is in `m`, otherwise all elements of `m` are
> "touched".
> 
> ``if m.count(b) > 0`` will always goes through all elements of `m` in the
> `count()` method.

But the first technique executes in (relatively slow) pure Python, while
the count method executes (relatively fast) C code. So even though count
may do more work, it may do it faster.

The only way to tell for sure is to actually time the code, not try to
guess.



-- 
Steven.



From http  Mon Feb 13 19:05:07 2006
From: http (Paul Rubin)
Date: 13 Feb 2006 16:05:07 -0800
Subject: invert the order of a string
References: 
Message-ID: <7xek26erf0.fsf@ruckus.brouhaha.com>

rtilley  writes:
> s = list('some_random_string')
> print s
> s.reverse()
> print s
> s = ''.join(s)
> print s
> 
> Surely there's a better way to do this, right?

In Python 2.4, just say
  s = reversed('some_random_string')


From duncanm255 at hotmail.com  Tue Feb 28 19:30:14 2006
From: duncanm255 at hotmail.com (D)
Date: 28 Feb 2006 16:30:14 -0800
Subject: Py2exe
In-Reply-To: 
References: <1141160676.947534.123630@t39g2000cwt.googlegroups.com>
	<1141162463.658164.34110@i40g2000cwc.googlegroups.com>
	<1141162697.347464.49420@i40g2000cwc.googlegroups.com>
	
Message-ID: <1141173014.776837.150600@u72g2000cwu.googlegroups.com>

Thanks Larry - that is exactly what I needed!  I do have the program
written to be a service, and now plan to use py2exe and Inno Setup to
package it up. 

Doug



From iainking at gmail.com  Wed Feb  1 04:06:39 2006
From: iainking at gmail.com (Iain King)
Date: 1 Feb 2006 01:06:39 -0800
Subject: wxPython Conventions
In-Reply-To: <1138684467.864196.212400@f14g2000cwb.googlegroups.com>
References: <1138684467.864196.212400@f14g2000cwb.googlegroups.com>
Message-ID: <1138784799.435953.251980@g43g2000cwa.googlegroups.com>


Jared Russell wrote:

> To mess around with it, I decided to create a small app to check my
> Gmail.  I want something that will just sit in my system tray checking
> for new emails every ten minutes or so.

How do you gain access to the system tray?

Iain



From steve at hastings.org  Fri Feb 24 01:22:04 2006
From: steve at hastings.org (Steve R. Hastings)
Date: Thu, 23 Feb 2006 22:22:04 -0800
Subject: PyAtom, a Python module for creating Atom syndication feeds
References: 
	<87mzgicute.fsf@voodoo.myself>
	
	<87hd6qcsgl.fsf@voodoo.myself>
	
Message-ID: 

I have edited PyAtom, and now it should be in better conformance with the
PEP 8 guidelines.  It is available from the same place as before:

http://www.blarg.net/~steveha/pyatom.tar.gz

-- 
Steve R. Hastings    "Vita est"
steve at hastings.org    http://www.blarg.net/~steveha



From codecraig at gmail.com  Tue Feb 28 09:23:54 2006
From: codecraig at gmail.com (abcd)
Date: 28 Feb 2006 06:23:54 -0800
Subject: error: argument after ** must be a dictionary
Message-ID: <1141136634.030745.256120@e56g2000cwe.googlegroups.com>

I have class like this...

import threading
class MyBlah(object):
    def __init__(self):
        self.makeThread(self.blah, (4,9))

    def blah(self, x, y):
        print "X and Y:", x, y

    def makeThread(self, func, args=(), kwargs={}):
        threading.Thread(target=self.blah, args=args,
kwargs=kwargs).start()

When I do...
b = MyBlah()

I am getting this error:
TypeError:  MyBlah object argument after ** must be a dictionary

What am I missing?



From fredrik at pythonware.com  Fri Feb  3 03:39:39 2006
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Fri, 3 Feb 2006 09:39:39 +0100
Subject: How do I dynamically create functions without lambda?
References: <1138389517.896043.7450@g47g2000cwa.googlegroups.com><1138436008.628882.126510@g44g2000cwa.googlegroups.com><1ha3g79.1gcm6x1yziggyN%aleaxit@yahoo.com><1ha5e9r.gs34le12dm1luN%aleaxit@yahoo.com>
	<20060203014442.21daa210@samwise.anansi>
Message-ID: 

Terry Hancock wrote:

> Frankly this paper sounds like a bid for the "Journal of
> Irreproducible Results" that somehow got accidentally
> submitted to a serious journal

    http://www.improbable.com/ig/ig-pastwinners.html#ig2000







From fredrik at pythonware.com  Wed Feb 15 11:59:55 2006
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Wed, 15 Feb 2006 17:59:55 +0100
Subject: Embedding a binary file in a python script
References: <1140021879.698353.324230@o13g2000cwo.googlegroups.com>
Message-ID: 

"mrstephengross" wrote:

> I want to find a way to embed a tar file *in* my python script, and
> then use the tarfile module to extract it. That is, instead of
> distributing two files (extractor.py and archive.tar) I want to be able
> to distribute *one* file (extractor-with-embedded-archive.py). Is there
> a way to do this?

I'm not sure I understand why you think you need to embed a tarfile
(why not just embed the actual files?), but here's an outline:

$ echo hello >hello.txt
$ echo world >world.txt
$ tar cvfz archive.tar hello.txt world.txt
hello.txt
world.txt
$ ls -l archive.tar
-rw-r--r--  1 effbot effbot 151 2006-02-15 17:52 archive.tar

$ python
>>> import base64, sys
>>> base64.encode(open("archive.tar", "rb"), sys.stdout)
H4sIAPlc80MAA+3TwQqDMAzG8Z73FH2CkWqbPs/GFA+FguvYHn8qQ3aaJ3XC/3cJJJeQ8HVNSvlc
XsWsRwbq/VhdDPJdP9Q4qaPXoFIPfVdVTo2VFXeaPe7l0ltrmra95h9XWJofVDf+/7T3FtjLM/fp
9lf5D1P+fST/W5j+T/4BAAAAAAAAAAAAAAAO6w1uw+KBACgAAA==
>>> ^D

$ python
>>> import base64, cStringIO, tarfile
>>> f = cStringIO.StringIO(base64.decodestring("""
... H4sIAPlc80MAA+3TwQqDMAzG8Z73FH2CkWqbPs/GFA+FguvYHn8qQ3aaJ3XC/3cJJJeQ8HVNSvlc
... XsWsRwbq/VhdDPJdP9Q4qaPXoFIPfVdVTo2VFXeaPe7l0ltrmra95h9XWJofVDf+/7T3FtjLM/fp
... 9lf5D1P+fST/W5j+T/4BAAAAAAAAAAAAAAAO6w1uw+KBACgAAA==
... """))
>>> f

>>> tar = tarfile.TarFile.gzopen("dummy", fileobj=f)
>>> tar.list()
-rw-r--r-- effbot/effbot          6 2006-02-15 17:51:36 hello.txt
-rw-r--r-- effbot/effbot          6 2006-02-15 17:51:41 world.txt
>>> tar.extractfile("hello.txt").read()
'hello\n'

hope this helps!







From steve at REMOVEMEcyber.com.au  Tue Feb 21 02:59:40 2006
From: steve at REMOVEMEcyber.com.au (Steven D'Aprano)
Date: Tue, 21 Feb 2006 18:59:40 +1100
Subject: how to break a for loop?
References: <1140476451.649515.127230@g44g2000cwa.googlegroups.com>
	<1140477343.684115.222490@z14g2000cwz.googlegroups.com>
Message-ID: <43FAC86C.4020505@REMOVEMEcyber.com.au>

Petr Jakes wrote:

> zero_list=[0,0,0,0,0,1,2,3,4]
> for x in range(len(zero_list)):
>     if zero_list[x]!=0: break
> nonzero_list=zero_list[x:]
> print nonzero_list
> 
> but some more "pythonic" solutions will be posted from other users I
> guess :)


That looks perfectly Pythonic to me.

You know, just because Python has for loops and 
multi-line blocks of code doesn't mean we shouldn't use 
them *wink*


-- 
Steven.



From steve at REMOVEMEcyber.com.au  Tue Feb 21 04:19:05 2006
From: steve at REMOVEMEcyber.com.au (Steven D'Aprano)
Date: Tue, 21 Feb 2006 20:19:05 +1100
Subject: getting started, .py file
References: <1140471172.783876.80400@g14g2000cwa.googlegroups.com>
	
	<1140476484.581881.230170@o13g2000cwo.googlegroups.com>
Message-ID: <43FADB09.4020408@REMOVEMEcyber.com.au>

Ingrid wrote:

> Thanks everyone. That's exactly what I was looking for, but I still
> can't seem to make it work. I've got the interpreter starting in
> "C:\Program Files\Python2.4", and my code is in "C:\Documents and
> Settings\Ingrid\My Documents". So, I did:
>   import os
>   os.chdir("C:\\Documents and Settings\\Ingrid\\My Documents")
>   from mycode import *

I see that Ingrid found the solution to this problem. 
But I wonder, should Python support importing absolute 
pathnames?

I've trying googling, but either my google skills are 
lacking or nobody has ever thought of doing import 
"C:\directory\module" before.


-- 
Steven.



From onurb at xiludom.gro  Thu Feb 16 17:15:12 2006
From: onurb at xiludom.gro (bruno at modulix)
Date: Thu, 16 Feb 2006 23:15:12 +0100
Subject: embedding python in HTML
In-Reply-To: <8n6Jf.1640$No6.38203@news.tufts.edu>
References: 
	
	<8n6Jf.1640$No6.38203@news.tufts.edu>
Message-ID: <43f4f98e$0$16930$636a55ce@news.free.fr>

John Salerno wrote:
> Rene Pijlman wrote:
> 
>> John Salerno:
>> [Python alternative for PHP]
>>
>>> So to do this with Python, do I simply integrate it into the HTML as
>>> above, with no extra steps? 
>>
>>
>> You'd need something like the PHP engine, that understands Python rather
>> than PHP.
> 
> 
> My web server can run Python, fortunately. Now that they've turned it on
> for me, I wanted to try it out, but I didn't know how to go about
> writing a bit of code to stick into an HTML file.

You've got to understand that Python is *not* a 'ServerPage' language
(-> php, asp, jsp etc) in itself. Your server can now run python, fine,
but *how* ? CGI ? FastCGI ? mod_python ? other ? (hint: it's probably
just plain old CGI...)


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"


From timr at probo.com  Sun Feb 26 23:53:34 2006
From: timr at probo.com (Tim Roberts)
Date: Mon, 27 Feb 2006 04:53:34 GMT
Subject: spaces at ends of filenames or directory names on Win32
References: 
	<1140897423.932377.304640@i39g2000cwa.googlegroups.com>
Message-ID: <4s0502dknn9k07bpa7d80emeno2tkar7p7@4ax.com>

drobinow at gmail.com wrote:

>For example... tell windows to move a file named ' XXX ' (one space
>before and one space after the filename). Windows will complain that
>file 'XXX' does not exist. It's correct of course, 'XXX' does not
>exist,
>but ' XXX ' does indeed exist.
>
>Can anyone rescue me from this madness :(

Use double-quotes on Windows, not single-quotes.  Single-quotes are taken
as just another filename character.
-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.


From finite.automaton at gmail.com  Fri Feb 24 03:00:59 2006
From: finite.automaton at gmail.com (Lonnie Princehouse)
Date: 24 Feb 2006 00:00:59 -0800
Subject: automatic html generation for documentation?
Message-ID: <1140768059.871220.110300@j33g2000cwa.googlegroups.com>

I plan on writing some documentation that will consist of blocks of
commentary with interspersed snippets of syntax-colored Python code and
the occaisional image.

Does anyone know of a package that will take a high level description
of what I just described and auto-generate clean-looking web pages,
including syntax coloring?   I'm already using epydoc for API reference
generation; what I'm looking for here is just something to help out
with the narrative so I don't have to spend lots of time fiddling with
HTML.



From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de  Thu Feb 16 10:38:30 2006
From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian)
Date: Thu, 16 Feb 2006 16:38:30 +0100
Subject: question about scope
In-Reply-To: <9J0Jf.1630$No6.38274@news.tufts.edu>
References: <9J0Jf.1630$No6.38274@news.tufts.edu>
Message-ID: <45jkjnF6q6bcU1@news.dfncis.de>

John Salerno schrieb:
> Here's a sentence from Learning Python:
> 
> "Names not assigned a value in the function definition are assumed to be
> enclosing scope locals (in an enclosing def), globals (in the enclosing
> module's namespace) or built-in (in the predefined __builtin__ names
> module Python provides."
> 
> I have trouble reading this sentence. First, I don't understand if the
> word 'enclosing' is a verb or an adjective. The whole flow of the
> sentence seems convoluted.
> 
> But my real question is this, which is related to the above:
> 
> "Name references search at most four scopes: local, then enclosing
> functions (if any), then global, then built-in."
> 
> I understand what global and built-in are, and I thought I understood
> the concept of local too, but when I got to this sentence (and the
> previous sentence), I became confused about the first two scopes. What's
> the difference between 'local' and 'enclosing functions'? I thought that
> the only way to create a local namespace was if there *was* a function
> definition, so now I'm confused by the apparent difference that the
> authors are referring to. What's an example of a local scope without
> having a function definition? Loops and if statements, perhaps?
> 

Nested functions, I should think. Absolutely silly, but working example:

>>> def outer():
	    arg_in = 2
	    def inner():
		    x = arg_in * 3
		    return x
	    return inner()
>>> outer()
6

Seen from the inside of "inner" x is local, arg_in is in the enclosing
function.



-- 
Dr. Sibylle Koczian
Universitaetsbibliothek, Abt. Naturwiss.
D-86135 Augsburg
e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE


From dprovins at rpcl.com  Wed Feb 22 11:45:12 2006
From: dprovins at rpcl.com (Dean Allen Provins)
Date: Wed, 22 Feb 2006 16:45:12 GMT
Subject: Tkinter canvas size determination
Message-ID: <43FC9532.2050800@rpcl.com>

I need to determine the size of a canvas while the process is running.
Does anyone know of a technique that will let me do that?

Thanks,

Dean


From altis at semi-retired.com  Thu Feb  2 13:12:44 2006
From: altis at semi-retired.com (Kevin Altis)
Date: Thu, 2 Feb 2006 10:12:44 -0800
Subject: ANNOUNCE: OSCON 2006 (Python 14 Conference) Proposals due Feb. 13th
Message-ID: 

OSCON 2006: Opening Innovation
http://conferences.oreillynet.com/os2006/

Save the date for the 8th annual O'Reilly Open Source Convention, happening
July 24-28, 2006 at the Oregon Convention Center in beautiful Portland,
Oregon.



Call For Participation
----------------------

Submit a proposal-fill out the form at:

http://conferences.oreillynet.com/cs/os2006/create/e_sess/

Important Dates:

* Proposals Due: Midnight (PST) February 13, 2006
* Speaker Notification: March 27, 2006
* Tutorial Presentation Files Due: June 12, 2006
* Session Presentation Files Due: June 26, 2006
* Conference: July 24-28, 2006

Proposals
---------

We are considering proposals for 45 minute sessions and 3 hour tutorials.
We rarely accept 90 minute proposals, as most general sessions are 45
minutes in length.  Your proposals are examined by a committee which draws
from them and which also solicits proposals to build the program.  Proposals
are due by midnight (PST), Feb. 13, 2006.  The OSCON Speaker Manager, Vee
McMillen, emails notification of the status of your talk (accepted or
otherwise) by March 27, 2006.  Unless the content of your talk is
particularly timely (e.g., features of a product that will be launched at
OSCON), you are required to send us your slides several weeks before the
conference begins. Submit proposals via the form below.

Some tips for writing a good proposal for a good talk:

* Keep it free of marketing: talk about open source software, but not about
a commercial product--the audience should be able to use and improve the
things you talk about without paying money
* Keep the audience in mind: they're technical, professional, and already
pretty smart.
* Clearly identify the level of the talk: is it for beginners to the topic,
or for gurus?  What knowledge should people have when they come to the talk?
* Give it a simple and straightforward title: fancy and clever titles make
it harder for people (committee and attendees) to figure out what you're
really talking about
* Limit the scope of the talk: in 45 minutes, you won't be able to cover
Everything about Widget Framework X.  Instead, pick a useful aspect, or a
particular technique, or walk through a simple program.
* Pages of code are unreadable: mere mortals can deal with code a line at a
time.  Sometimes three lines at a time.  A page of code can't be read when
it's projected, and can't be comprehended by the audience.
* Explain why people will want to attend: is the framework gaining traction?
Is the app critical to modern systems?  Will they learn how to deploy it,
program it, or just what it is?
* Let us know in your proposal notes whether you can give all the talks you
submitted proposals for
* Explain what you will cover in the talk

NOTE: All presenters whose talks are accepted (excluding Lightning Talks)
will receive free registration at the conference. For each half-day
tutorial, the presenter receives one night's accommodation, a limited travel
allowance, and an honorarium. We give tutors and speakers registration to
the convention (including tutorials), and tutors are eligible for a travel
allowance: up to US$300 from the west coast of the USA, up to US$500 from
the east coast of the USA, up to US$800 from outside the USA.

Registration opens April, 2006. If you would like to be notified by email
when registration opens, please use the form on our main page.



CONFERENCE INFO
===============

The O'Reilly Open Source Convention is where coders, sysadmins,
entrepreneurs, and business people working in free and open source software
gather to share ideas, discover code, and find solutions. At OSCON 2005,
more than 2,400 attendees took part in 241 sessions and tutorials across
eleven technology tracks, learning about the newest features and versions
from creators and experts. A record number of products launches and
announcements were made, and sponsors and exhibitors from a wide range of
companies filled the largest exhibit hall in OSCON's history. We anticipate
that OSCON 2006 will be even more successful, and continue to be the place
for the open source community to meet up, debate, make deals, and connect
face to face. OSCON 2006 will take place at the Oregon Convention Center in
Portland, Oregon July 24-28, 2006.

OSCON 2006 will feature the projects, technologies, and skills that you need
to write and deploy killer modern apps.  We're looking for proposals on
platforms and applications around:

* Multimedia including voice (VoIP) and video
* AI including spam-busting, classification, clustering, and data mining
* Collaboration including email, calendars, RSS, OPML, mashups, IM,
presence, and session initialization
* Project best practices including governance, starting a project, and
managing communities
* Microsoft Windows-based open source projects including .NET, Mono, and
regular C/C++/Visual Basic Windows apps
* Enterprise Java techniques including integration, testing, and scalable
deployment solutions
* Linux kernel skills for sysadmins including virtualization, tuning, and
device drivers
* Device hacking including iPods, Nintendo, PSP, XBox 360, and beyond
* Design including CSS, GUI, and user experience (XP)
* Entrepreneurial topics including management for techies, how to go into
business for yourself, and business models that work
* Security including hardening, hacking, root kits (Sony and otherwise), and
intrusion detection/cleanup
* Fun subjects with no immediate commercial application including retro
computing, games, and BitTorrent

Tracks at OSCON will include:

* Desktop Apps
* Databases, including MySQL, PostgreSQL, Ingres, and others
* Emerging Topics
* Java
* Linux Kernel for SysAdmins
* Linux for Programmers
* Perl, celebrating the 10th year of The Perl Conference!
* PHP
* Programming, including everything that's not specific to a particular
language
* Python
* Security
* Ruby, including Ruby on Rails
* Web Apps, including Apache
* Windows




From mensanator at aol.com  Sun Feb 12 10:06:52 2006
From: mensanator at aol.com (mensanator at aol.com)
Date: 12 Feb 2006 07:06:52 -0800
Subject: Tracking down memory leaks?
In-Reply-To: <1139749861.949765.282310@z14g2000cwz.googlegroups.com>
References: <1139749861.949765.282310@z14g2000cwz.googlegroups.com>
Message-ID: <1139756812.174596.159860@g14g2000cwa.googlegroups.com>


MKoool wrote:
> I have an application with one function called "compute", which given a
> filename, goes through that file and performs various statistical
> analyses.  It uses arrays extensively and loops alot.  it prints the
> results of it's statistical significance tests to standard out.  Since
> the compute function returns and I think no variables of global scope
> are being used, I would think that when it does, all memory returns
> back to the operating system.
>
> Instead, what I see is that every iteration uses several megs more.
> For example, python uses 52 megs when starting out, it goes through
> several iterations and I'm suddenly using more than 500 megs of ram.
>
> Does anyone have any pointers on how to figure out what I'm doing
> wrong?

Are you importing any third party modules? It's not unheard of that
someone else's code has a memory leak.

> 
> Thanks,
> mohan



From steve at REMOVETHIScyber.com.au  Thu Feb 23 10:53:29 2006
From: steve at REMOVETHIScyber.com.au (Steven D'Aprano)
Date: Fri, 24 Feb 2006 02:53:29 +1100
Subject: Using repr() with escape sequences
References: <1140708756.484933.13390@z14g2000cwz.googlegroups.com>
Message-ID: 

On Thu, 23 Feb 2006 07:32:36 -0800, nummertolv wrote:

> Hi,
> 
> My application is receiving strings, representing windows paths, from
> an external source. When using these paths, by for instance printing
> them using str() (print path), the backslashes are naturally
> interpreted as escape characters.
> 
>>>> print "d:\thedir"
> d:	hedir

No. What is happening here is not what you think is happening.

> The solution is to use repr() instead of str():

The solution to what? What is the problem? The way the strings are
DISPLAYED is surely not the issue, is it?

>>>> print repr("d:\thedir")
> 'd:\thedir'


You have created a string object: "d:\thedir"

That string object is NOT a Windows path. It contains a tab character,
just like the print statement shows -- didn't you wonder about the large
blank space in the string?

Python uses backslashes for character escapes. \t means a tab character.
When you enter "d:\thedir" you are embedding a tab between the colon and
the h.

The solutions to this problem are:

(1) Escape the backslash: "d:\\thedir"

(2) Use raw strings that don't use char escapes: r"d:\thedir"

(3) Use forward slashes, and let Windows automatically handle them:
"d:/thedir"

However, if you are receiving strings from an external source, as you say,
and reading them from a file, this should not be an issue. If you read a
file containing "d:\thedir", and print the string you have just read, the
print statement uses repr() and you will see that the string is just
what you expect:

d:\thedir

You can also check for yourself that the string is correct by looking at
its length: nine characters.


-- 
Steven.



From peter at engcorp.com  Fri Feb 10 08:29:38 2006
From: peter at engcorp.com (Peter Hansen)
Date: Fri, 10 Feb 2006 08:29:38 -0500
Subject: Thread Dump of a python process
In-Reply-To: <2868401.post@talk.nabble.com>
References: <2840609.post@talk.nabble.com> 
	<2868401.post@talk.nabble.com>
Message-ID: 

Shanon wrote:
> Thank you for your info. Now I have read that a simple call os.getpid()
> returned the linux identifier of the thread in latest python versions, but
> I'm using Python 2.3 and 2.4 and this call returns always the same id 
> I only want to take the pid of the thread but isn't as easier as it seems.

Oops, please ignore my other reply to this post.  I didn't grab the 
start_new_thread() result, but instead grabbed the result of 
thread.get_ident() and stored that.  The docs claim this is not a value 
that necessarily relates to anything in the outside world ("Return the 
`thread identifier' of the current thread. This is a nonzero integer. 
Its value has no direct meaning; it is intended as a magic cookie ...") 
so if it happens to match the thread id from the OS's point of view, 
it's an implementation detail you couldn't rely on.

So the general idea I gave might be useful, but I don't know precisely 
how to do exactly what you are asking.  Sorry.

-Peter



From siv.hansen at gmail.com  Mon Feb 27 19:31:09 2006
From: siv.hansen at gmail.com (Cruella DeVille)
Date: 27 Feb 2006 16:31:09 -0800
Subject: Catch exceptions
In-Reply-To: <1141085325.698323.297100@v46g2000cwv.googlegroups.com>
References: <1141083485.798371.188440@u72g2000cwu.googlegroups.com>
	<1141085325.698323.297100@v46g2000cwv.googlegroups.com>
Message-ID: <1141086669.334852.80660@u72g2000cwu.googlegroups.com>

I put the try catch in my main-method, and it worked to some extent
(except from when I try to read from a file with no content)

Any idea how to solve that?
And is it a good place to have a try-except in main instead of in the
class methods?

My code is at http://nibbler.no/blog/wp-includes/Bookmarks.py



From kp8 at mac.com  Fri Feb 24 15:14:32 2006
From: kp8 at mac.com (kpp9c)
Date: 24 Feb 2006 12:14:32 -0800
Subject: ls files --> list packer
In-Reply-To: 
References: <1140765792.864556.289820@i40g2000cwc.googlegroups.com>
	<1140767111.490691.42460@e56g2000cwe.googlegroups.com>
	<1140768527.006363.29050@i39g2000cwa.googlegroups.com>
	
Message-ID: <1140812071.998261.92610@i40g2000cwc.googlegroups.com>

that is nice.... but the little further wrinkle, which i have no idea
how to do, would be to have the contents of each directory packed into
a different list.... since you have no idea before hand how many lists
you will need (how many subdirs you will enounter)  ... well that is
where the hairy part comes in...

-kp--



From tim.golden at viacom-outdoor.co.uk  Mon Feb 13 11:13:18 2006
From: tim.golden at viacom-outdoor.co.uk (Tim Golden)
Date: Mon, 13 Feb 2006 16:13:18 -0000
Subject: Execute batch script on remote computer
Message-ID: <9A28C052FF32734DACB0A288A3533991044D254E@vogbs009.gb.vo.local>

[py]

| I am trying to execute a batch script on a remote computer.
| 
| The batch script looks like:
| 
| @echo off
| start c:\python24\python.exe c:\a_script.py
| 
| 
| Here's the setup:
| Computer A (my computer), Computer B (the remote computer).
| 
| So I map "W:" to Computer B and then copy the batch script to Computer
| B.  Then from within Python on Computer A I run:
| import subprocess
| subprocess.Popen("W:\\foo.bat")
| 
| However, when it runs it says it can't find c:\a_script.py.  It seems
| to be trying to look
| at Computer A, not Computer B.  How can I do this?

You're confusing a couple of things here. One is a 
drive mapping, which presents the *filesystem* of a
remote computer as though it were local. The other
is a remote procedure call, which presents the
*processor* (and environment etc.) of a remote 
computer as though it were local.

What you're doing has the effect of running a
remote *file* on a local *processor*.

You could run a remote script -- on the *remote*
processor -- under vanilla Windows using WMI, and
possibly using some other DCOM-based technology, such
as WSH. But you'd run into some security / environment
issues depending on just what your remote script was
trying to do.

You could also -- if you were prepared to invest in
some more software infrastructure -- employ Pyro
(http://pyro.sf.net), Corba, XML-RPC or any one of
several other RPC-type technologies.

Are you even more confused now than you were when
I started? ;)

TJG

________________________________________________________________________
This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
________________________________________________________________________


From albalmer at att.net  Wed Feb 15 14:20:45 2006
From: albalmer at att.net (Al Balmer)
Date: Wed, 15 Feb 2006 14:20:45 -0500
Subject: Xah's Edu Corner: accountability & lying thru the teeth
References: <1134780763.066592.45390@g49g2000cwa.googlegroups.com>
	<1135405908.381150.133190@o13g2000cwo.googlegroups.com>
	<1136236586.734775.212440@f14g2000cwb.googlegroups.com>
	<1137784561.589887.58380@o13g2000cwo.googlegroups.com>
	<1139909629.798938.284160@g47g2000cwa.googlegroups.com>
	<45dmspF66tepU1@individual.net>
	
	
	<9vyIf.8103$lG2.7704@news-wrt-01.rdc-nyc.rr.com>
Message-ID: <2dv6v1hv6914bbfc4a508pkbjf8d2csgkg@4ax.com>

On Wed, 15 Feb 2006 04:55:33 GMT, Kenny Tilton
 wrote:

>> Apparently you've never actually read one of his articles.
>
>Have you read his web page? Like I did? Get back to me after you come up 
>to speed on Xah.

Given the aspect he presents on Usenet, why on earth would I want to
go to his web page?

Why should I want to "come up to speed" on him? I have him filtered,
have for a long time, and I can understand that it would be better if
everyone filtered or ignored him, but I don't see posted complaints
about him being any worse than your complaints about the complainers.
I have no idea why anyone would defend such inane, worthless,
obscenity-laced articles.

-- 
Al Balmer
Sun City, AZ


From nicola.musatti at gmail.com  Mon Feb  6 11:51:56 2006
From: nicola.musatti at gmail.com (Nicola Musatti)
Date: 6 Feb 2006 08:51:56 -0800
Subject: OO conventions
In-Reply-To: 
References: 
	<1139221726.376326.73560@g44g2000cwa.googlegroups.com>
	
Message-ID: <1139244716.125636.237630@z14g2000cwz.googlegroups.com>


Fredrik Lundh wrote:
> Nicola Musatti wrote:
[...]
> > What is important to me is to keep your get_initial_data() function
> > outside Klass if it's task is non trivial, e.g. it has to interact with
> > the OS or a DB.
>
> why ?

Separating the internal logic of an application from its interactions
with the outside world, e.g. retrieval from a file or a database and
presentation to a GUI, makes it easier to reuse the logic in different
contexts and may help make it possible to use highly generic solutions
for those interactions. I'm thinking of code generation or
introspection, which may be applied with very limited knowledge of the
application logic.

In larger projects I find that this separation tends to match the
different areas of expertise that are needed: database experts, GUI
experts, domain experts, etc.

Cheers,
Nicola Musatti



From juho.schultz at helsinki.fi  Fri Feb  3 11:48:54 2006
From: juho.schultz at helsinki.fi (Juho Schultz)
Date: Fri, 03 Feb 2006 18:48:54 +0200
Subject: problems writing tuple to log file
In-Reply-To: <1138980476.469673.254090@g44g2000cwa.googlegroups.com>
References: <1138980476.469673.254090@g44g2000cwa.googlegroups.com>
Message-ID: 

localpricemaps at gmail.com wrote:
> i am having a problem writing a tuple to a text file.  my code is
> below.
> 
> what i end up getting is a text file that looks like this
> 
> burger, 7up
> burger, 7up
> burger, 7up
> 
> and this is instead of getting a list that should look like this
> 
> burger, 7up
> fries ,coke
> cake ,milk
> 
> note that i have print statements that print out the results of the
> scraping and they are fine.  they print out burger, fries, cake and
> then 7up, coke, milk
> 
> however there is something faulty in my writing of the tuple to the
> text file.  perhaps related to the indentation that causes it to write
> the same stuff over and over?
> 
> 
> 
>     for row in bs('div'):

What kind of function is 'bs'? Should you use 'row'
(which you are looping over) inside the loop?
Seems that your code is equal to

for row in range(len(bs('div'))):

> 	for incident in bs('span'):

Just like you use 'incident' here, inside the other loop.


>         	foodlist = []
> 		b = incident.findPrevious('b')
> 		for oText in b.fetchText( oRE):
>             		#foodlist.append(oText.strip() + "',")
> 				foodlist += oText.strip() + "','"
> 		food = ''.join(foodlist)
> 		print food
> 

After "print food" you repeat the loop, overwriting "food" until last 
round. And after you have found the last "food", you put it in "tuple".

>         tuple = (food + drink "\n")

A tip: 'tuple' is a built-in function, just like 'open' you use.
This statement overwrites that function with a string.
It is usually a good idea to leave the built-ins as they are,
and use some other names for variables.


From bonono at gmail.com  Fri Feb 17 14:46:36 2006
From: bonono at gmail.com (bonono at gmail.com)
Date: 17 Feb 2006 11:46:36 -0800
Subject: Print a PDF transparently
In-Reply-To: <1140202841.650774.32920@z14g2000cwz.googlegroups.com>
References: <1140184955.674138.275010@o13g2000cwo.googlegroups.com>
	<11vbpu58sll1b4f@corp.supernews.com>
	<1140190758.951694.231890@f14g2000cwb.googlegroups.com>
	
	<1140202841.650774.32920@z14g2000cwz.googlegroups.com>
Message-ID: <1140205596.648065.237670@f14g2000cwb.googlegroups.com>


Daniel Crespo wrote:
> Yes, I've seen it, but that's it: another program that I have to
> install, which I want to avoid.
>
> I'd be happy if I just do "printer.Print(file.pdf/.ps)" and wal?, the
> printing just starts (in 98,2000,XP... sounds like a dream), without
> having another window opened. If it opens, but then closes, it's
> perfect too.
I have done such thing a few years back, just use the file association
and the "print/printto" action. All you need is to have Acrobat
installed. You can try it by right click on the desktop on a .PDF file
and select print. A modeless dialog would still be visible but would
close itself. This was using ancient Acrobat Reader.

You need to read the WIN32 API(I faintly remembered about Shell
something) that tells you how to do it programmatically(I used C).

>
> All this has to be easilly installed (with InnoSetup, for example),
> because I have to install it on 70 offices. So I can't leave it to
> another installation process. All of these offices have a dot matrix
> printers Epson LX-300, which has PostScript level 3 built-in.
>
> Where can I find how to send a .ps directly to the printer?
Again, in the WIN32 API and unfortunately 98 and NT family has
completely different mechanism.



From mrstephengross at hotmail.com  Wed Feb 15 12:07:12 2006
From: mrstephengross at hotmail.com (mrstephengross)
Date: 15 Feb 2006 09:07:12 -0800
Subject: Embedding a binary file in a python script
References: <1140021879.698353.324230@o13g2000cwo.googlegroups.com>
	
Message-ID: <1140023232.099718.264330@g14g2000cwa.googlegroups.com>

Ok, this looks really cool, but can you explain a little more
step-by-step what's going on? In the end, I need to have a single
python script that (1) contains the archive and (2) can extract that
archive. The example you've given is interesting, but it's not clear to
me how to create the actual python script to do it all.

Thanks again,
--Steve (mrstephengross at hotmail.com)



From MrJean1 at gmail.com  Fri Feb  3 20:04:04 2006
From: MrJean1 at gmail.com (MrJean1)
Date: 3 Feb 2006 17:04:04 -0800
Subject: Best way to determine if a certain PID is still running
In-Reply-To: 
References: <43E2AD80.2000100@ilm.com>
	
Message-ID: <1139015043.970666.210320@g44g2000cwa.googlegroups.com>

Take look at the poll() methods in the subprocess.py source file of
your Python install.

It shows how to use the os.wait_pid(pid, os.WNOHANG) to check whether a
process is still running or has terminated (and how, from the returned
status value).

Btw, on *nix you must call os.wait_pid(pid, ...) to avoid creating
zombie processes.

Using the subprocess module hides and handles all those details for
you, both on *nix and Windows.

/Jean Brouwers



From jeff at schwabcenter.com  Fri Feb 24 07:50:18 2006
From: jeff at schwabcenter.com (Jeffrey Schwab)
Date: Fri, 24 Feb 2006 12:50:18 GMT
Subject: "Temporary" Variable
In-Reply-To: 
References: <1140665472.203495.7570@g44g2000cwa.googlegroups.com>
	<43FD6645.3020201@REMOVEMEcyber.com.au>
	<1140725159.143882.202630@j33g2000cwa.googlegroups.com>
	
	
	
Message-ID: 

Steven D'Aprano wrote:
> On Fri, 24 Feb 2006 00:24:25 +0000, Jeffrey Schwab wrote:
> 
> 
>>Steven D'Aprano wrote:
>>
>>>On Thu, 23 Feb 2006 12:05:59 -0800, darthbob88 wrote:
>>>
>>>My comments inserted inline.
>>>
>>>
>>>
>>>
>>>>#!/usr/bin/python
>>>>#simple guessing game, with numbers
>>>>import random
>>>>spam = random.randint(1, 100)
>>>
>>>
>>>It is bad programming practice to give variables uninformative joke names.
>>
>>Lighten up.  This isn't the middle of a 100-KLOC corporate monstrosity, 
>>it's a 1/2-page usenet post.
> 
> 
> The original poster is also a newbie who was having trouble with the
> difference between strings and ints. If Guido called a variable spam,
> I wouldn't presume to correct him. When Newbie McNew does it, it might
> very well be because he doesn't know any better.

Sorry if I snapped at you.  But you didn't "correct" him, as he what he 
did wasn't wrong.  You just talked down to him.

> Just out of curiosity, when do you think is the right time to begin
> teaching programmers good practice from bad? Before or after they've
> learnt bad habits?

I'm not convinced the OP has a "bad habit."  Frankly, I prefer postings 
that have a sense of humor.  I wouldn't want to see this turned into a 
purely techical forum.

import random
print ", ".join(['spam' for i in range(random.randint(1, 9))] +
	['bacon', 'eggs', 'and']), 'spam'


From aleaxit at yahoo.com  Mon Feb 20 20:21:29 2006
From: aleaxit at yahoo.com (Alex Martelli)
Date: Mon, 20 Feb 2006 17:21:29 -0800
Subject: 2.4.2 + Zone Alarm
References: <1140481575.506191.9980@g47g2000cwa.googlegroups.com>
Message-ID: <1hb2imh.39tehkqjz0nhN%aleaxit@yahoo.com>

DannyB  wrote:
   ...
> IIs there a fix?  I'm pretty sure that this problem started with 2.3.1
> (i'm suing 2.4.2).

Well, good look in court, then...!-)

Seriously, looks like we've omitted a SO_REUSEADDR somewhere in the IDLE
startup code, so that abrupt termination of an IDLE socket keeps the
socket non-reusable for a while; if so, then ZoneAlarm seems innocent
for once (try disconnecting your computer from the net, terminate
ZoneAlarm, and see if you can reproduce the bug).

I can't look into it right now, but if you open a bug on the Python bug
tracker (http://sourceforge.net/bugs/?group_id=5470) somebody will (look
into it, for sure, and hopefully fix it in time for 2.4.3).


Thanks,

Alex


From k.suess at gmx.net  Wed Feb 22 15:37:50 2006
From: k.suess at gmx.net (Katja Suess)
Date: Wed, 22 Feb 2006 21:37:50 +0100
Subject: PyUNO with different Python
In-Reply-To: <43fcad29$0$29099$5fc30a8@news.tiscali.it>
References: 
	<43fcad29$0$29099$5fc30a8@news.tiscali.it>
Message-ID: <43FCCB9E.6080308@gmx.net>

Michele Petrazzo schrieb:
> ? wrote:
> 
>>Hi! maybe somebody can give me an hint to my problem setting up PyUNO
>>on my Mac to work with my Python not the Python delivered with
>>OpenOffice. As said in installation instructions I've set 
>>OPENOFFICE_PATH="/usr/lib/openoffice/program" export
>>PYTHONPATH="$OPENOFFICE_PATH" export
>>LD_LIBRARY_PATH="$OPENOFFICE_PATH" according to my environment.
>>
>>importing uno gives me this error:
>>
>>
>>>>>import uno
>>
>>Traceback (most recent call last): File "", line 1, in ? File
>>"/Applications/OpenOffice.org 
>>2.0.app/Contents/openoffice.org2.0/program/uno.py", line 37, in ? 
>>import pyuno ImportError: No module named pyuno
>>
>>which means python finds uno but not pyuno (pyuno.dylib).
>>
> 
> 
> Do you want to use system python inside OOo (inside a macro, or...), or
> system python outside OOo?
> 
> For the first, follow this:
> http://udk.openoffice.org/python/python-bridge.html#replacing
> 
> for the second:
> http://udk.openoffice.org/python/python-bridge.html#modes
> 
> 
>>Any hints? Regards, Katja
> 
> 
> Michele

Thanks. What I have in mind is to write a Python script to generate PDFs from a set of ODTs.
This script has to run in Zope which brings its own Python. 
My problem is the setup of PyUNO with this Python which is not the OO included one.
Hope to find a Mac user who made/solved similar experience...
Regards, Katja


From gene.tani at gmail.com  Tue Feb 21 14:12:34 2006
From: gene.tani at gmail.com (gene tani)
Date: 21 Feb 2006 11:12:34 -0800
Subject: Augmented assignment
In-Reply-To: 
References: 
	
Message-ID: <1140549154.069649.143160@f14g2000cwb.googlegroups.com>


Terry Hancock wrote:
> On Tue, 21 Feb 2006 10:55:42 +0530
> Suresh Jeevanandam  wrote:

> Seriously,
> I think they are usually equivalent internally,
> at least for immutable objects.
>

yah, but when you do augmented assigns on lists, or mix immutable an
dmutable:

http://zephyrfalcon.org/labs/python_pitfalls.html



From jstroud at ucla.edu  Wed Feb 22 22:00:07 2006
From: jstroud at ucla.edu (James Stroud)
Date: Wed, 22 Feb 2006 19:00:07 -0800
Subject: "configuring" a class
In-Reply-To: <1140658115.672421.207560@g47g2000cwa.googlegroups.com>
References: <1140658115.672421.207560@g47g2000cwa.googlegroups.com>
Message-ID: 

Russ wrote:
> I would like to let the user of one of my classes "configure" it by
> activating or de-activating a particular behavior (for all instances of
> the class).
> 
> One way to do this, I figured, is to have a static class variable,
> along with a method to set the variable. However, I am stumped as to
> how to do that in python. Suggestions welcome.
> 
> The next best thing, I figure, is to just use a global variable.
> Several "methods" of the class then check the value of the global
> variable to determine what to do. The user can then just set the
> variable to get the desired behavior.
> 
> However, I tried this and it does not seem to work. I imported the
> class, then set the global variable. But the new value of the variable
> somehow did not get back into the class methods that need to see it.
> 
> Can anyone give me a clue about this? If there is a better way, please
> let me know. Thanks.
> 

py> class C:
...   doit = 2
...
py> C.doit
2
py> a = C()
py> b = C()
py> c = C()
py> a.doit, b.doit, c.doit
(2, 2, 2)
py> C.doit = 5
py> a.doit, b.doit, c.doit
(5, 5, 5)
py> b.doit = 13
py> a.doit, b.doit, c.doit
(5, 13, 5)

James


From evan.monroig at gmail.com  Mon Feb 13 22:06:40 2006
From: evan.monroig at gmail.com (Evan Monroig)
Date: Tue, 14 Feb 2006 12:06:40 +0900
Subject: listing attributes
In-Reply-To: <1139884643.749492.221140@g43g2000cwa.googlegroups.com>
References: <1139884643.749492.221140@g43g2000cwa.googlegroups.com>
Message-ID: <20060214030640.GA11979@localhost.localdomain>

On Feb.13 18h37, Thomas Girod wrote :
> Hi there.
> 
> I'm trying to get a list of attributes from a class. The dir() function
> seems to be convenient, but unfortunately it lists to much - i don't
> need the methods, neither the built-in variables.

If you do something like this you should have a list of attributes:

l = dir(object)
l = [s for s in l if s[:2] != '__']
l = [s for s in l if not callable(getattr(object, s))]

cheers,

Evan


From onurb at xiludom.gro  Wed Feb 15 09:07:41 2006
From: onurb at xiludom.gro (bruno at modulix)
Date: Wed, 15 Feb 2006 15:07:41 +0100
Subject: Code organization
In-Reply-To: <1140010547.891395.65510@g44g2000cwa.googlegroups.com>
References: <1140010547.891395.65510@g44g2000cwa.googlegroups.com>
Message-ID: <43f335ca$0$1397$626a54ce@news.free.fr>

Thomas Girod wrote:
> Hi.
> 
> I found a lot of documentation about how to code in Python, but not
> much about how you organize your code in various modules / packages ...
> As I am not yet used to python, this puzzle me a bit.
> 
> So, can anyone explain how one should organize and store its code ? the
> uses of __init__.py files ? Maybe my question is not very clear, but I
> hope someone will understand anyway ...

Well... As a starting point relative to Python specific stuff (use of
__init__.py etc), the Fine Manual is your friend:
http://www.python.org/doc/2.4.2/tut/node8.html

Now for best practices and whatnots, this isn't really specific to
Python. Try to have modules with high cohesion and low coupling, and
it'll be fine. Eventually try to provide a facade class or function for
complex packages (this is a current pattern in the standard lib).

Also, python-is-not-java, so don't feel commited to putting everything
in classes when plain functions would do, and avoid the 1:1 class/file
Java plague !-)

My 2 cents...
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"


From john_zenger at yahoo.com  Tue Feb 21 21:06:54 2006
From: john_zenger at yahoo.com (John Zenger)
Date: Tue, 21 Feb 2006 21:06:54 -0500
Subject: Basic coin flipper program - logical error help
In-Reply-To: 
References: <1140567243.251982.255620@g14g2000cwa.googlegroups.com>
	
Message-ID: 

wes weston wrote:
>    Looping is easier with:
> for x in range(100):
>    if random.randint(0,1) == 0:
>       heads += 1
>    else:
>       tails += 1

Also, with the functional programming tools of map, filter, and lambda, 
this code can be reduced to just six lines:

import random

flips = map(lambda x: random.randrange(2), xrange(100))
heads = len(filter(lambda x: x is 0, flips))
tails = len(filter(lambda x: x is not 0, flips))

print "The coin landed on heads", heads, "times."
print "The coin landed on tails", tails, "times."


From siona at chiark.greenend.org.uk  Thu Feb  9 07:59:19 2006
From: siona at chiark.greenend.org.uk (Sion Arrowsmith)
Date: 09 Feb 2006 12:59:19 +0000 (GMT)
Subject: how to remove 
using replace function? References: <1139462640.951603.302830@g44g2000cwa.googlegroups.com> <1139469846.713121.219060@g47g2000cwa.googlegroups.com> <1139472365.378523.141150@g44g2000cwa.googlegroups.com> Message-ID: Duncan Booth wrote: >Although I generally advise against overuse of regular expressions, this is >one situation where regular expressions might be useful: [ ... ] >>>> nobr = re.compile('\W*\W*', re.I) Agreed (on both counts), but r'\s*\s*' might be better (consider what happens with "an unfortunate...
in the middle" if you use \W rather than \s). -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From maketo at ukato.freeshell.org Thu Feb 2 13:42:38 2006 From: maketo at ukato.freeshell.org (Ognen Duzlevski) Date: Thu, 2 Feb 2006 18:42:38 +0000 (UTC) Subject: dynamic class instantiation References: <43de9abc$1_2@newspeer2.tds.net> <43e2494f$1_1@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > Ognen Duzlevski wrote: > > Can you suggest a better approach or did you already do that and I just missed > > it? :) > With the above definitions, an equivalent class is created by calling > page = classFactory( 'page', { 'name' : None, 'caption': None, > 'functions' : []} ) Beautiful. Thank you very much. Cheers, Ognen From sybrenUSE at YOURthirdtower.com.imagination Tue Feb 14 12:29:17 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 14 Feb 2006 18:29:17 +0100 Subject: Python / Apache / MySQL References: <1139907519.427789.188760@g14g2000cwa.googlegroups.com> <0001HW.C01764D700060858F0407550@news.individual.de> <43f1aebb$0$1728$636a55ce@news.free.fr> <0001HW.C01772E1000952B1F0407550@news.individual.de> <86v3v1pvoi514avlbio77t238rpud4ppdi@4ax.com> Message-ID: Dennis Lee Bieber enlightened us with: > I believe that since 4.1, the "default table format" is InnoDB, and > that DOES have some support foreign keys and transactions. Finally they are starting to make more sense. I'd still rather use a database that has had those features for a longer time, though. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From lycka at carmen.se Fri Feb 17 10:20:07 2006 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 17 Feb 2006 16:20:07 +0100 Subject: Python 3000 deat !? Is true division ever coming ? In-Reply-To: <1139810036.943598.229030@g47g2000cwa.googlegroups.com> References: <1139810036.943598.229030@g47g2000cwa.googlegroups.com> Message-ID: seb.haase at gmail.com wrote: > Hi, > Is it true that that "Python 3000" is dead ? I think you should view Python 3000 as a metaphor for "Python as it would look if we didn't have to care about backward compatibility". Before this name appeared, Guido used to talk about Python 3.0 as a version where bad things in Python could go away, but it seems many people got worried about that, assuming that Python 3.0 would happen soon and cause a lot of changes in already written code. Thus the less scary label Python 3000. There has never been any concrete plans as far as I know to actually release a real software product called Python 3000. It's rather a long term design target for Python. A lot of these language changes can be introduced step be step. A new feature can be introduced first as an experimental feature, accessible via "from __future__ import XYZ", in the next minor release, it might be enabled by default. If a feature or module is going away, the first step is to document it as deprecated. The next minor release will issue a PendingDeprecationWarning, and the minor release after that will issue a DeprecationWarning and the next minor release (2.4 -> 2.5 etc) will remove the feature. This will give developers a period of many years to adapt from the time the feature is documented as deprecated until maintenace ends for the last Python where the deprecated feature works. For an example of such a transition plan, see http://www.python.org/peps/pep-0352.html Changing the behaviour of int/int is worse, since there is no obvious way for Python to determine whether the programmer expects an int result, a float result or either. Also, the typical consequence of this change is not that code breaks with a big bang, but rather that it produces somewhat different results. That means that a bug due to this feature change might go unnoticed for a long time, and cause a lot of problems. Imagine some kind of system that calculates how much pension you'll get when you retire, based on your monthly payments. A bug caused by changed division behaviour might have serious consequences. It seems reasonable to wait until the next major release, 3.0, before this feature is introduced. In the mean time it seems that the strategy should be to encourage people to adopt the new behaviour in all new code, i.e. to use "from __future__ import division" and to explicitly use interger division a//b when this is needed. In the same way, people should be encouraged to always use new style classes, "class X(object):" in new code, since old style classes are going away, and they behave differently in some ways. A problem as I see it today, is that this behaviour is not actively encouraged. The tutorial, which is maintained and updated, still describes old style classes, and the old division behaviour. http://docs.python.org/dev/tut/node5.html#SECTION005110000000000000000 http://docs.python.org/dev/tut/node11.html#SECTION0011300000000000000000 I don't see any reason to use old style classes in new code, so I think all "class X:" should be changed to "class X(object):", but I can understand that it would be confusing to explain the use of "from __future__ import division" before we introduce simple arithmetics. Still, we should get this message through! As it is now, when people aren't actively moving their code towards this expected change, the impact of such a change would be almost as strong as if this "from __future_..." feature didn't exist. So, if I finally try to answer your question: Float division will hardly be enabled by default until most Python programmers have adopted the feature, i.e. enabled it through the __future__ switch and started to use // when they want floor division. This will hardly happen until it's documented as the way people should do it. Perhaps a start could be a FutureProofPython page in the Python wiki, with suggested coding guidelines. From fredrik at pythonware.com Mon Feb 20 06:55:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Feb 2006 12:55:39 +0100 Subject: cElementTree encoding woes References: <45tkj3F8d9fpU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > I've got to deal with a pretty huge XML-document, and to do so I use the > cElementTree.iterparse functionality. Working great. > > Only trouble: The guys creating that chunk of XML - well, lets just say they > are "encodingly challanged", so they don't produce utf-8, but only cp1252 > instead, together with some weird name (Windows-1252) for that. That is not > part of the standard codecs module. cp1252 is, of course. > > But that won't work for iterparse. So currently, I manually change the > encoding given to utf-8, and use a stream-recoder. > > However, I was wondering if I could teach cElementTree about that encoding > name. I tried to register cp1252 under the name Windows-1252, but had no > luck - cET won't buy it. you need cET 1.0.5 or later for this to work. for earlier versions, you have to use stream recoding: http://effbot.org/zone/celementtree-encoding.htm From lycka at carmen.se Mon Feb 27 11:33:14 2006 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 27 Feb 2006 17:33:14 +0100 Subject: time.sleep(1) sometimes runs for 200 seconds under windows In-Reply-To: References: Message-ID: Peter Hansen wrote: > Magnus Lycka wrote: > >> With an operating system such as Windows, this is >> probably something you can expect to happen, although >> I'm surprised if such long lag times as 200 s are typical. > > No way. I mean, I'm the biggest critic of Windows operating systems > when used in realtime environments (at least with my customers), but > there's no way you should "probably expect a 200s delay to happen". You know Peter, quotations are typically used when you actually quote someone, not when you make your own interpretation of what they meant. If I write that it would surprise me if you are often hit by meteorites, would the quote then be "you'll probably get hit by meteorites"? From ilias at lazaridis.com Wed Feb 22 08:43:07 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Wed, 22 Feb 2006 15:43:07 +0200 Subject: Komodo - Will it Lock Me In? In-Reply-To: References: Message-ID: Matt Trivisonno wrote: > Hi Everybody, > > If I were to use Komodo to write in Python, would it add a lot of goo to my > code such that I would not be able to switch to another IDE without having to > claw my way out of a tarpit first? > > Any other thoughts on Komodo? I am considering it because I am hoping to find > a solution to the install-packages-until-you-go-blind aspect of Python. > Setting up a serious, cross-platform, gui development environment is quite a > struggle for a newbie. I work myself currently with the Kommodo IDE (but have not done an thorough evaluation of the market before choosing it). The "lock-in" question would be solved, if Active State would go open-source with Kommodo. Even a partial open-source would solve this: If the project-management subsystems would go open-source, other IDE's could adopt them, ensuring a cohesive standard across the dynamic communities. - I have made a compact review of Active State, which will possibly give you some relevant information: http://lazaridis.com/samples/com/ActiveState/index.html Note that some things have changed since the review, which could simplify the process of going open source even more: "Active State, a Division of Sophos" has become "ActiveState Software Inc." http://activestate.com/Corporate/Communications/Releases/Press1140209595.html . -- http://lazaridis.com From john_sips_teaz at yahooz.com Thu Feb 23 02:14:57 2006 From: john_sips_teaz at yahooz.com (John M. Gabriele) Date: Thu, 23 Feb 2006 02:14:57 -0500 Subject: pyFltk-1.1 In-Reply-To: References: <1140617661.603681.12250@z14g2000cwz.googlegroups.com> Message-ID: {fixed top-posting} george williams wrote: > > This is to announce the first official release of pyFltk-1.1, > > the Python bindings for the cross platform GUI toolkit fltk-1.1 > > By god this sounds interesting I wish I > knew what you are talking about fltk (pronounced "full-tick" as in "Cap'n, we're doing warp 9 and the engines are going full tick!" but not as in, "boy, I just checked the dog found one very full tick") is a C++ GUI toolkit. You would use fltk for writing a GUI desktop application. It's like GTK+ or Qt, but much smaller and lighter. pyFltk is a Python binding to fltk. That is, so you can use fltk from Python instead of from C++. ---J -- (remove zeez if demunging email address) From email at christoph-haas.de Mon Feb 20 11:48:25 2006 From: email at christoph-haas.de (Christoph Haas) Date: Mon, 20 Feb 2006 17:48:25 +0100 Subject: preserving POST data In-Reply-To: <20060216213531.57457.qmail@web36502.mail.mud.yahoo.com> References: <20060216213531.57457.qmail@web36502.mail.mud.yahoo.com> Message-ID: <200602201748.26083.email@christoph-haas.de> On Thursday 16 February 2006 22:35, Steve Young wrote: > Lets say that I'm filling out a form and the information gets sent to > another server first for some processing(before the one that it > "should" go to). But from there, I want that intermediate server to be > able to preserve this POST data using python so it can still retrieve > the page that was originally requested (with some modifications from > the intermediate server). Is there a way to do this with python? That's less a python-specific question. The general solution is to store the information on your server and remember who the user was. Many web programmers use a cookie based authentication/identification with a database backend. Which means: - User comes to your website - You send the user a cookie - You create an entry in your database with that cookie - User enters data - You add the data to the database (referring to the cookie) - User comes back later - You can look up the data in your database according to the user's cookie I use that scheme in a more complex way for cookie based authentication (http://workaround.org/pysessions). Kindly Christoph -- ~ ~ ".signature" [Modified] 1 line --100%-- 1,48 All From jrivero at latinux.org Mon Feb 20 21:43:44 2006 From: jrivero at latinux.org (Jesus Rivero - (Neurogeek)) Date: Mon, 20 Feb 2006 22:43:44 -0400 Subject: html parser , unexpected '<' char in declaration In-Reply-To: <1140488536.933840.65530@o13g2000cwo.googlegroups.com> References: <1140473997.262973.149260@f14g2000cwb.googlegroups.com> <1140488536.933840.65530@o13g2000cwo.googlegroups.com> Message-ID: <43FA7E60.6060803@latinux.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 hmmm, that's kind of different issue then. I can guess, from the error you pasted earlier, that the problem shown is due to the fact Python is interpreting a "<" as an expression and not as a char. review your code or try to figure out the exact input you're receving within the mta. Regards, Jesus (Neurogeek) Sakcee wrote: > thanks for the reply > > well probabbly I should explain more. this is part of an email . after > the mta delivers the email, it is stored in a local dir. > After that the email is being parsed by the parser inside an web based > imap client at display time. > > I dont think I have the choice of rewriting the message!? and I dont > want to reject the message alltogether. > > I can either 1-fix the incoming html by tidying it up > or 2- strip only plain text out and dispaly that you have spam, 3 - or > ignore that mal-formatted tag and display the rest > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFD+n5gdIssYB9vBoMRAvIHAJ9H+IQWtaEMa9FBYFvDAQXcIO2SRwCfX3yj BEvNJ6yWht1b+dBc6ohkwYI= =X1JL -----END PGP SIGNATURE----- From apardon at forel.vub.ac.be Fri Feb 24 06:49:31 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Feb 2006 11:49:31 GMT Subject: A C-like if statement References: Message-ID: Op 2006-02-23, Roy Smith schreef : > Bob Greschke wrote: >>I miss being able to do something like this in Python >> >>1f (I = a.find("3")) != -1: >> print "It's here: ", I >>else: >> print "No 3's here" >> >>where I gets assigned the index returned by find() AND the if statement gets >>to do its job in the same line. Then you don't have to have another like >>that specifically gets the index of the "3". Is there a way to do this in >>Python? > > It is a deliberate and fundamental design decision in Python that > assignment is a statement, not an expression with side effects. The only motivation I have heard for this decision is to easily find typo related bugs. I can hardly find that a fundamental design decision. -- Antoon Pardon From btaranto at gmail.com Tue Feb 7 13:02:23 2006 From: btaranto at gmail.com (btaranto at gmail.com) Date: 7 Feb 2006 10:02:23 -0800 Subject: python-ldap In-Reply-To: References: <1139330793.864675.302090@f14g2000cwb.googlegroups.com> Message-ID: <1139335343.546105.237230@g14g2000cwa.googlegroups.com> _)_ From dylan.moreland at gmail.com Wed Feb 15 00:44:05 2006 From: dylan.moreland at gmail.com (Dylan Moreland) Date: 14 Feb 2006 21:44:05 -0800 Subject: how to write a C-style for loop? In-Reply-To: References: Message-ID: <1139982245.088453.241010@g14g2000cwa.googlegroups.com> John Salerno wrote: > I assume this is the way for loops are written in C, but if it helps to > be specific, I'm referring to C# for loops. The Python for loop seems to > be the same (or similar) to C#'s foreach loop: > > foreach int i in X > > But how would you write a C# for loop in Python? Do you rework a while > loop, or use the range() function? > > Here's an example: > > for (int i = 0; i < 50; i += 5) > > How would that go in Python, in the simplest and most efficient way? > > Thanks. Take a look at the range() builtin. That should give you what you need. From http Wed Feb 8 15:13:45 2006 From: http (Paul Rubin) Date: 08 Feb 2006 12:13:45 -0800 Subject: Too Many if Statements? References: <1139330447.716190.247940@z14g2000cwz.googlegroups.com> <1139429094.744499.258170@o13g2000cwo.googlegroups.com> Message-ID: <7xvevpr4li.fsf@ruckus.brouhaha.com> "rainbow.cougar at gmail.com" writes: > SystemError: com_backpatch: offset too large Yeah, that sounds like there's some 16-bit fields in the bytecode format. From deets at nospam.web.de Thu Feb 23 12:17:18 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 23 Feb 2006 18:17:18 +0100 Subject: need help regarding compilation References: <1140714583.014871.194640@p10g2000cwp.googlegroups.com> Message-ID: <46694pF9ms9bU1@uni-berlin.de> fidlee at gmail.com wrote: > i am new to learning jython... > > > i just tried compiling a small piece of code that is given below: > > def fac(x) > if x<=1:return 1 > return x*fac(x-1) You really have a book about python that doesn't mention that functions definitions are closed by a colon? I doubt that... Try this: def fac(x): if x<=1:return 1 return x*fac(x-1) regards, Diez From bearophileHUGS at lycos.com Fri Feb 10 09:41:43 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 10 Feb 2006 06:41:43 -0800 Subject: Create dict from two lists In-Reply-To: <1139581243.360298.164070@g43g2000cwa.googlegroups.com> References: <1139579518.129742.265680@o13g2000cwo.googlegroups.com> <453k9eF444frU1@uni-berlin.de> <1139581243.360298.164070@g43g2000cwa.googlegroups.com> Message-ID: <1139582503.478330.3670@z14g2000cwz.googlegroups.com> py: > Thanks, itertools.izip and just zip work great. However, I should have > mentioned this, is that I need to keep the new dictionary sorted. A Python dictionary is an unsorted data structure, so you cannot have it sorted as you please. (I have seen that lot of people ask for a sorted dictionary and for permutation/combination functions, maybe they are batteries to be included too in the standard library.) If you need an ordered dict you can manage it yourself, keeping the lists of keys, etc, or you can use an ordered dict implementation: http://www.voidspace.org.uk/python/odict.html http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438823 Etc. Bye, bearophile From andre.roberge at gmail.com Wed Feb 1 09:35:33 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 1 Feb 2006 06:35:33 -0800 Subject: Rur-ple lessons 0.36 In-Reply-To: <43e0c0ce$0$20180$8fcfb975@news.wanadoo.fr> References: <1138578056.564555.283470@o13g2000cwo.googlegroups.com> <43e0c0ce$0$20180$8fcfb975@news.wanadoo.fr> Message-ID: <1138804533.269105.6740@f14g2000cwb.googlegroups.com> Bonjour ! Je n'ai pas d'objections ? ce que tu le fasse. La seule chose qui m'emb?te, c'est que les le?ons ne sont qu'en anglais. C'est un peu pour moi une question de fiert? ; au moins l'interface de rur-ple est traduite en fran?ais. Andr? Roberge M?ta-MCI wrote: > Bonjour ! > > Il me semblerait sympathique que cette annonce soit dupliqu?e sur > fr.comp.lang.python, et sur quelques autres newsgroups. > Par exemple, puis-je r?percuter l'annonce sur le newsgroup > "programmation.python" de zoo-logique ? > > @-salutations > -- > Michel Claveau From chrisperkins99 at gmail.com Mon Feb 27 15:54:56 2006 From: chrisperkins99 at gmail.com (chrisperkins99 at gmail.com) Date: 27 Feb 2006 12:54:56 -0800 Subject: str.count is slow Message-ID: <1141073696.107136.318600@j33g2000cwa.googlegroups.com> It seems to me that str.count is awfully slow. Is there some reason for this? Evidence: ######## str.count time test ######## import string import time import array s = string.printable * int(1e5) # 10**7 character string a = array.array('c', s) u = unicode(s) RIGHT_ANSWER = s.count('a') def main(): print 'str: ', time_call(s.count, 'a') print 'array: ', time_call(a.count, 'a') print 'unicode:', time_call(u.count, 'a') def time_call(f, *a): start = time.clock() assert RIGHT_ANSWER == f(*a) return time.clock()-start if __name__ == '__main__': main() ###### end ######## On my machine, the output is: str: 0.29365715475 array: 0.448095498171 unicode: 0.0243757237303 If a unicode object can count characters so fast, why should an str object be ten times slower? Just curious, really - it's still fast enough for me (so far). This is with Python 2.4.1 on WinXP. Chris Perkins From mensanator at aol.com Thu Feb 9 20:36:06 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 9 Feb 2006 17:36:06 -0800 Subject: Pulling all n-sized combinations from a list In-Reply-To: References: <1139431819.946571.56710@g44g2000cwa.googlegroups.com> <1139509392.890581.94470@g43g2000cwa.googlegroups.com> <1139527518.210792.3420@g14g2000cwa.googlegroups.com> Message-ID: <1139535366.809771.241020@z14g2000cwz.googlegroups.com> Jack Diederich wrote: > liberally snipped out parts > On Thu, Feb 09, 2006 at 03:25:18PM -0800, mensanator at aol.com wrote: > > Jack Diederich wrote: > > > > > On Wed, Feb 08, 2006 at 12:50:19PM -0800, Swroteb wrote: > > > > > > > > > > > > I've got a reasonably sized list of objects that I'd like to pull out > > > > > > all combinations of five elements from. Right now I have a way to do > > > > > > this that's quite slow, but manageable. I know there must be a better > > > > > > way to do this, but I'm not sure what it is. Here's what I've got so > > > > > > far: > > > > > > > > > > import probstat # http://probstat.sourceforge.net > > > > > for (a, b, c) in probstat.Combination(range(9), 3): # 0..9, pick 3 > > > > > print a, b, c > > > > > > > > > so I put together a little test program to see how probstat > > compares. Correspondence to my emulations is (as far as I can tell) > > > > > > def p_perm(a,n): > > A = list(a) > > t0 = time.time() > > if len(A) > c = probstat.Permutation(A,n) > > else: > > c = probstat.Permutation(A) > > print time.time()-t0 > > p = [] > > for i in c: > > p.append(''.join(i)) > > return p > > This never calls the A choose n branch because len(A) is always > bigger than n. Duh . It was supposed to be if n > > print 'permutation w/o replacemment "abcdefghijklmnopqrstuvwxyz":4' > > t0 = time.time() > > p = p_perm("abcdefghijklmnopqrstuvwxyz", 4) > > t1 = time.time() > > print len(p),'4-letter words',t1-t0,'seconds' > > > > Unfortunately, the long test died (out of virtual memory) executing > > the probstat.Permution test. > > > > >>> import probstat > >>> p = probstat.Permutation(range(25)) > >>> len(p) > 2076180480 > >>> p = probstat.Permutation(range(26)) > >>> len(p) > -1853882368 > >>> > > Overflow error. I'll have to add a test that raises a ValueError > for lists that are too big. > > The following simple loop takes three minutes to run on my laptop > import probstat > count_to = len(probstat(range(12))) # just computes the size > cnt = 0 > while cnt < count_to: > cnt += 1 > > So a permutation of all arrangements of the alphabet would take > rougly forever. Right, I never intended to do that, was trying to make 4-letter words, not 26 letter permutations. Anyway, now that _my_ bug is fixed, it works properly: permutation w/ replacemment "abcdefghijklmnopqrstuvwxyz":4 456976 4-letter words 1.26600003242 seconds combination w/ replacemment "abcdefghijklmnopqrstuvwxyz":4 23751 4-letter words 0.671999931335 seconds permutation w/o replacemment "abcdefghijklmnopqrstuvwxyz":4 358800 4-letter words 1.6400001049 seconds combination w/o replacemment "abcdefghijklmnopqrstuvwxyz":4 14950 4-letter words 0.56200003624 seconds probstat.Cartesian "abcdefghijklmnopqrstuvwxyz":4 456976 4-letter words 1.42199993134 seconds probstat.Permutation "abcdefghijklmnopqrstuvwxyz":4 358800 4-letter words 1.06200003624 seconds probstat.Combination "abcdefghijklmnopqrstuvwxyz":4 14950 4-letter words 0.077999830246 seconds Thanks again for supplying that pyd. > > -Jack From fakeaddress at nowhere.org Wed Feb 15 18:48:53 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 15 Feb 2006 23:48:53 GMT Subject: is socket thread safe? In-Reply-To: <1139912679.559724.131020@f14g2000cwb.googlegroups.com> References: <1139912679.559724.131020@f14g2000cwb.googlegroups.com> Message-ID: e2wugui at gmail.com wrote: > thread1: > while 1: > buf = s.read() > process(buf) > > thread2: > while 1: > buf = getdata() > s.write(buf) Sockets don't have read() and write() methods. Connected sockets have recv() and send()/sendall(). Python's socket module has a makefile() function, but the resulting file object wouldn't make sense in the read loop above (and throws away control that network code typically needs). Is it safe for one thread to receive from a socket while another sends over the socket? Yes, that much is safe and perfectly reasonable. -- --Bryan From johnjsal at NOSPAMgmail.com Wed Feb 22 10:03:19 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 22 Feb 2006 15:03:19 GMT Subject: a little more help with python server-side scripting In-Reply-To: References: <59edncmGm6g2LmbeRVn-pw@rcn.net> <8t-dndPM0buNZmbeRVn-rA@rcn.net> Message-ID: Steve Holden wrote: > Note that purists might suggest this isn't the best way to use Python on > the web. If it gets you where you want to be, feel free to ignore them :-) Thanks for the info. Basically I don't plan to do big stuff with Python on the internet (at least not right now while I'm still learning the language). I already know how to use a PHP include, so I could just keep doing that, but I figure since I'm learning Python, I might as well start using it wherever I can, assuming that it is okay to use it this way. From girodt at gmail.com Wed Feb 15 08:35:47 2006 From: girodt at gmail.com (Thomas Girod) Date: 15 Feb 2006 05:35:47 -0800 Subject: Code organization Message-ID: <1140010547.891395.65510@g44g2000cwa.googlegroups.com> Hi. I found a lot of documentation about how to code in Python, but not much about how you organize your code in various modules / packages ... As I am not yet used to python, this puzzle me a bit. So, can anyone explain how one should organize and store its code ? the uses of __init__.py files ? Maybe my question is not very clear, but I hope someone will understand anyway ... Thomas From fredrik at pythonware.com Thu Feb 2 18:15:36 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 3 Feb 2006 00:15:36 +0100 Subject: Control if a input text is IP References: Message-ID: Sbaush wrote: > My app has in input an ip address in IPv4 notation. > is there a function that control if input is a string in IPv4 notation? here's one way to do it: def ipcheck(s): try: a, b, c, d = [chr(int(c)) for c in s.split(".")] except ValueError: return False else: return True another way is to use regular expressions; see http://www.regular-expressions.info/examples.html From ivoras at __yahoo__.com_ Fri Feb 3 06:12:06 2006 From: ivoras at __yahoo__.com_ (Ivan Voras) Date: Fri, 03 Feb 2006 12:12:06 +0100 Subject: would it be feasable to write python DJing software In-Reply-To: <1138962918.427815.70300@g14g2000cwa.googlegroups.com> References: <1138925819.465108.181760@o13g2000cwo.googlegroups.com> <1138962918.427815.70300@g14g2000cwa.googlegroups.com> Message-ID: simonwittber at gmail.com wrote: > Actually, manipulating and mixing audio samples can be both fast and > elegant, in Python, if you use Numeric or a similar library. ... at which point you're actually doing it in C, not pure python... :) From pydecker at gmail.com Sun Feb 19 22:27:41 2006 From: pydecker at gmail.com (Peter Decker) Date: Sun, 19 Feb 2006 22:27:41 -0500 Subject: Komodo - Will it Lock Me In? In-Reply-To: References: Message-ID: On 2/19/06, Matt at bag.python.org wrote: > My goal was to test out Python by writing a simple GUI app and then deploying > it to Mac OS X and Windows XP. Using a product such as RealBasic, a totally > green newbie could accomplish this in a few minutes.. So, I guess my main > question is, is there such a RAD tool for Python? You should take a look at Dabo, especially the Visual Designer. You can create GUI applications visually in a matter of minutes without having to write any code at all. If you want the app to do interesting things, you can add as much code as you need to accomplish this. No need to become a Python expert. http://dabodev.com -- # p.d. From duncanm255 at hotmail.com Sun Feb 19 23:07:24 2006 From: duncanm255 at hotmail.com (D) Date: 19 Feb 2006 20:07:24 -0800 Subject: Open Relay Test In-Reply-To: <871wy2cldi.fsf@rose.polar.local> References: <1140150719.298606.9710@g44g2000cwa.googlegroups.com> <871wy2cldi.fsf@rose.polar.local> Message-ID: <1140408444.059247.203260@g14g2000cwa.googlegroups.com> Thanks guys for the info..the DSBL client app is exactly what I need..unfortunately the app I'm writing will be for Windows (the only client I saw was for Linux). Do you know if there's a Windows command line port? From deets at nospam.web.de Sat Feb 4 09:52:43 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 04 Feb 2006 15:52:43 +0100 Subject: numeric expression from string? In-Reply-To: References: Message-ID: <44jtdsF2hp1mU1@uni-berlin.de> Brian Blais schrieb: > Hello, > > I have a string input from the user, and want to parse it to a number, > and would like to know how to do it. I would like to be able to accept > arithmetic operations, like: > > '5+5' > '(4+3)*2' > '5e3/10**3' > > I thought of using eval, which will work, but could lead to bad security > problems (not that it's a big deal in my app, but still...) > > string.atof won't do the job. Is there a preferred way of doing this? No. If you already know about the pro and cons of eval, either go for it - or if it bothers you, write a parser using pyparsing and evaluate the expressions yourself. Regards, Diez From roccomoretti at hotpop.com Wed Feb 1 14:04:56 2006 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 01 Feb 2006 13:04:56 -0600 Subject: locals() and dictionaries In-Reply-To: <1138818258.895406.34130@g47g2000cwa.googlegroups.com> References: <1138818258.895406.34130@g47g2000cwa.googlegroups.com> Message-ID: JerryB wrote: > Hi, > I have a dictionary, a string, and I'm creating another string, like > this: > > dict = {} > dict[beatles] = "need" > str = "love" > > mystr = """All you %(dict[beatles])s is %(str)s""" % locals() > > Why do I get > keyerror: 'dict[one]'? > > Is there a way to reference the elements in a dictionary with locals() > or do I need to create a temp variable, like > > need = dict[one] > mystr = """All you %(need)s is %(str)s""" 1) Avoid variable names like 'dict' and 'str'- they cover up the builtin names. 2) When showing error, don't retype - cut and paste: >>> dict[beatles] = "need" Traceback (most recent call last): File "", line 1, in -toplevel- dict[beatles] = "need" NameError: name 'beatles' is not defined >>> dict['beatles'] = "need" >>> 3) In string formating, the item in parenthesis, used as a string, is the key for the dictionary. That is: """All you %(dict[beatles])s is %(str)s""" % ld is the same as """All you %s is %s""" % (ld['dict[beatles]'],ld['str']) 4) Your best bet is not to use locals(), but to create a new dictionary with the appropriate keys. E.g.: >>> d = {} >>> d['beatles'] = "need" >>> s = "love" >>> d2 = d.copy() >>> d2['str'] = s >>> d['str'] Traceback (most recent call last): File "", line 1, in -toplevel- d['str'] KeyError: 'str' >>> d2['str'] 'love' >>> mystr = """All you %(beatles)s is %(str)s""" % d2 >>> print mystr All you need is love From lycka at carmen.se Wed Feb 1 03:20:26 2006 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 01 Feb 2006 09:20:26 +0100 Subject: Request for suggesstions and comments In-Reply-To: References: Message-ID: Vivek Kumar wrote: > Hi all, > > I have to write a network server (sort of) and I am > looking for your valuable comments. You might want to look at twisted for this. http://twistedmatrix.com/ From lycka at carmen.se Thu Feb 9 11:34:44 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 09 Feb 2006 17:34:44 +0100 Subject: Rethinking the Python tutorial Message-ID: While the official Python Tutorial has served its purpose well, keeping it up to date is hardly anyones top priority, and there are others who passionately create really good Python tutorials on the web. I think 'A Byte of Python' by Swaroop C H is a good beginners tutorial, and 'Dive Into Python' by Mark Pilgrim is a good tutorial for more experienced programmers. My radical idea is that we mirror these at diveinto.python.org and byteof.python.org, and simply remove the old tutorial from the Python 2.5 (or 2.6?) docs. Give these two good texts an official status as the Python tutorials. Just as we want to adopt best of breed packages for the standard library, I think we should use best of breed documentation, and I think there are less backward compatibility issues with tutorials than with libraries. :) I think this change would give us better docs as well as a smaller maintenance burden. If a day comes when Mark Pilgrim or Swaroop C H don't want to maintain these texts, I strongly suspect that there are other tutorials we can replace them with if noone else steps in to keep them up to date. From lycka at carmen.se Mon Feb 20 14:36:01 2006 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 20 Feb 2006 20:36:01 +0100 Subject: Python 3000 deat !? Is true division ever coming ? In-Reply-To: References: <1139810036.943598.229030@g47g2000cwa.googlegroups.com> <1140213665.105188.103450@o13g2000cwo.googlegroups.com> Message-ID: Steve Holden wrote: > seb.haase at gmail.com wrote: >> My main point was/is: why is there not more discussion about "true >> division" !!? > > You are about three years too late for the discussion. It was debated to > death when Guido proposed that Python should behave more like > non-programmers expected it to. Despite some fierce opposition this view > eventually held sway, and now long-time Pythonistas accept it as the way > forward. I think you should understand "discussion" as "mentioning" or "documentation" here. However much it was discussed three years ago, enabling it as default in 3.0 will be a bit like the Vogons suddenly appearing to demolish Earth, if it hasn't been documented clearly. The tutorial shouldn't teach a coding style that will cause problems when we reach the next major version of Python. At least not if it's easily avoided. Python has supported true division for more than four years, and it's been decided from the onset that this will be default behaviour in 3.0. The Tutorial basically ignores it. Ok, it's mentioned in passing in the glossary, but not where it explains how division works! > So basically most people saw your question and probably thought "enough, > already!". Having followed comp.lang.python for several years should not be a requirement for programming Python properly. Neither should it be a requirement to read all the PEPs or "what's new in Python version 2.2" when someone starts learning Python with 2.4! I had more or less forgotten about this (do you use "from __future__ import division" in all your scipts Steve?) so I think it's a good thing that this was brought up. Particularly if Guido's Google jobs brings 3.0 closer to its release... I started http://wiki.python.org/moin/FutureProofPython as a place to document this, but I doubt that yet-another-wiki-page is the perfect solution for this. It might be useful as a placeholder for the time being though, and I hope that some of you who are better at this than I am improves that page a bit, and more importantly, that it gets into the Tutorial. I've now inspected more than 1700 python files from a number of sources, Twisted being one of them, with 235kLoC, written by scores of different developers. I found no "from __future__ import division" statement, but almost 7000 lines with '/' that needs to be inspected one way or another. (Not all divisions, I'm sure, but still a substancial amount of work to check, and plenty of new test cases.) From lycka at carmen.se Mon Feb 20 11:24:54 2006 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 20 Feb 2006 17:24:54 +0100 Subject: Python 3000 deat !? Is true division ever coming ? In-Reply-To: References: <1139810036.943598.229030@g47g2000cwa.googlegroups.com> <1140213665.105188.103450@o13g2000cwo.googlegroups.com> Message-ID: Steven D'Aprano wrote: > The tutorial shouldn't talk about Python3000 at all. What would be the > point of that? The tutorial is there to teach about the way Python works > now, not to make guesses and prediction about how it will work some time > in the indefinite future. There is no guessing involved. The new division behaviour was implemented years ago, but to avoid breaking old code, it's not enabled by default. For new code, you ought to use 'from __future__ import division' and use // whenever you want floor division, regardless of that numeric types you divide. The ordinary / shouldn't truncate fractions. The problem is that the tutorial doesn't tell python programmers to do this. I can understand that there is a pedagogical problem here. Division is introduced way earlier than the import statement in the tutorial, and the "from __future__" thingie might not be the first thing you want to expose for a beginner. From neuzhoundxx at yahoo.com Tue Feb 21 18:15:11 2006 From: neuzhoundxx at yahoo.com (john peter) Date: Tue, 21 Feb 2006 15:15:11 -0800 (PST) Subject: interpreting the fractional portion of time.clock() vs time.time() measurements Message-ID: <20060221231511.79988.qmail@web36707.mail.mud.yahoo.com> let's say i'm taking timing measurements in Windows XP t1 = time.clock() ... t2 = time.clock() t3 = t2 - t1 = say, 0.018 what is the unit of measurement for t3? is it correct to say that t3 = 18 milliseconds? microseconds? what if the timing function used for t1 and t2 was time.time()? is it still correct to say that t3 = 18 milliseconds? i kinda know that in Windows, time.clock() has higher resolution than time.time(). all i need is millisecond resolution. which of these functions would be easier to translate into millisecond units of measurement? __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From smitty_one_each at bigfoot.com Sat Feb 18 09:23:24 2006 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Sat, 18 Feb 2006 09:23:24 -0500 Subject: Activestate python installation References: <1140243666.990365.131220@f14g2000cwb.googlegroups.com> Message-ID: <87r760n3tv.fsf@bigfoot.com> >>>>> "mik3" == mik3 writes: mik3> hi this is a question regarding installing Activestate mik3> python whenever i try to install the latest Activestate mik3> Python on WinXP SP2, it gives me error saying "The wizard mik3> was interrupted before Activestate 2.4.2 could be completely mik3> installed. Your system has not been modified ....." any mik3> ideas why this is going on? thanks Administrator? Writeable drive? Is there an install log file you could locate? R, C From tjreedy at udel.edu Tue Feb 21 01:46:15 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 21 Feb 2006 01:46:15 -0500 Subject: Augmented assignment References: Message-ID: "Suresh Jeevanandam" wrote in message news:dte88n$568$2 at home.itg.ti.com... > Hi, > Is there any gain in performance because of augmented assignments. > > x += 1 vs x = x+1 > > Or are both of them the same. The main gain is in programmer performance for writing a long name such as number_of_items once instead of twice. Also in reading to see that the same name gets rebound to the new name. Program performance might be noticeable if 'x' is something like a.b.c.d that takes some lookup time. But again, I would use the += form for readability without testing run time. Terry Jan Reedy From grante at visi.com Tue Feb 7 09:45:07 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 07 Feb 2006 14:45:07 -0000 Subject: Best way of finding terminal width/height? References: <96nFf.43896$d5.199922@newsb.telia.net> <11uc3dohfitotc5@corp.supernews.com> <11udc0r2bq11042@corp.supernews.com> <43E719EE.3040401@gmail.com> <11ueq4nhn91qm91@corp.supernews.com> <43E8659D.6010101@gmail.com> Message-ID: <11uhcjj2p10mm0d@corp.supernews.com> On 2006-02-07, Joel Hedlund wrote: > As before, the only IO case above that doesn't throw > exceptions is the uncommented one. > >> Yup, that's the exception. Standard practice is to catch it and >> retry the I/O operation. > > Hmm... I guess it's not that easy to "retry" IO operations on > pipes and streams (stdin/stdout in this case)... You just call the failed read() or write() again. Unless there's some way that the read/write partially succeeded and you don't have any way to know how many bytes were read/written, If that's the case then Python's "file" object read and write would appear to be broken by design. > And I tend to lean pretty heavily on those since I usually > write UNIX style text "filters". > > So in case I haven't missed something fundamental I guess my > best option is to accept defeat (of sorts :-) and be happy > with picking a terminal width at program startup. > > But anyway, it's been really interesting trying this out. > > Thank you Grant (och Jorgen) for all help and tips! -- Grant Edwards grante Yow! BRILL CREAM is at CREAM O' WHEAT in another visi.com DIMENSION... From johnjsal at NOSPAMgmail.com Tue Feb 14 11:19:30 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 14 Feb 2006 16:19:30 GMT Subject: how do you pronounce 'tuple'? In-Reply-To: References: <11v032ii4gvik72@corp.supernews.com> <1139816300.706181.79250@f14g2000cwb.googlegroups.com> Message-ID: Tim Peters wrote: > "tuhple" is a girly-man affectation. That's why Guido and I both say > the manly "toople". Heh heh. Actually, 'toople' sounds like a noun to me, and 'tuple' sounds like a verb, so I prefer 'toople' anyway. From jasondrew72 at gmail.com Mon Feb 20 17:59:14 2006 From: jasondrew72 at gmail.com (Jason Drew) Date: 20 Feb 2006 14:59:14 -0800 Subject: converting sqlite return values In-Reply-To: <1140465583.398495.63470@g44g2000cwa.googlegroups.com> References: <1140465583.398495.63470@g44g2000cwa.googlegroups.com> Message-ID: <1140476354.932279.184780@g43g2000cwa.googlegroups.com> Hi, You can use the built-in function "eval" to return how Python evaluates your string. For example: >>> eval( '(1,2,3,4)' ) (1, 2, 3, 4) In other words, eval will take your string that looks like a tuple, and return an actual tuple object. Note that the 'u' prefix in your string will cause an error if you pass it to eval, so you should drop that, e.g.: >>> utuple = 'u(1,2,3,4)' >>> eval( utuple[1:] ) (1, 2, 3, 4) In general, though, converting your strings/tuples back and forth like this might not be the best idea, depending on the situation. If the numbers represent consistent items, like (price, tax, code, quantity), then you would do better to use a field for each item in your database and insert/fetch the numbers appropriately. Storing whole Python objects in single database fields isn't unheard of, but in general you should only do it when you really need to do it. When you do, there are various Python modules to help, though I haven't used this approach much myself. Jason From steve at holdenweb.com Fri Feb 10 07:21:52 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 10 Feb 2006 07:21:52 -0500 Subject: a second TKinter In-Reply-To: <1d987df30602100320t4c61673ewfa6cd0f685a24bab@mail.gmail.com> References: <1d987df30602100253x33aece59u425dd7d61c0ffa3f@mail.gmail.com> <6f4025010602100256m5f390357o@mail.gmail.com> <1d987df30602100320t4c61673ewfa6cd0f685a24bab@mail.gmail.com> Message-ID: linda.s wrote: > On 2/10/06, Michael Foord wrote: > >> >> >>On 10/02/06, linda.s wrote: >> >>>I found if I opened a second TKinter, Python will go out of work. But >>>I need two graph outputs at the same time. What to do? >>>Linda. >>> >> >> >>Hello linda (?), >> >>How are you opening a 'second Tkinter' ? There is no problem with having two >>top level windows at the same time, you can't hjave two 'mainloops' though. >>:-) >> >>All the best, >> >>Fuzzyman > > What does "having two top level windows" mean? > Can you give an example? > For opening a second tkinter, i mean that I run python using > PythonWin: if I run the code again when the first Tk is still open, > then the program will crash. You are actually doing well to run even *one* Tkinter-based application under PythonWin, since PythonWin is an MFC-based Windows application. There may well be conflict between the multiple windowing modules in use. Not a good idea to run GUI-based applications under an IDE that isn't designed to handle them. Sorry. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From claird at lairds.us Sat Feb 25 21:08:01 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 26 Feb 2006 02:08:01 GMT Subject: Pythonic exceptionalism (was: A C-like if statement) References: Message-ID: In article , Steven D'Aprano wrote: >On Thu, 23 Feb 2006 12:04:38 -0700, Bob Greschke wrote: > >>> try: >>> i = a.find("3") >>> print "It's here: ", i >>> except NotFound: >>> print "No 3's here" >> >> Nuts. I guess you're right. It wouldn't be proper. Things are added or >> proposed every day for Python that I can't even pronounce, but a simple 'if >> (I = a.find("3")) != -1' isn't allowed. Huh. It might be time to go back >> to BASIC. :) > >There are *reasons* why Python discourages functions with side-effects. >Side-effects make your code hard to test and harder to debug. > >> I think your way would work if .find() were replaced with .index(). I'm >> just trying to clean up an if/elif tree a bit, so using try would make >> things bigger. > >Then write a function! Instead of calling the try..except block in every >branch directly, pull it out into a function: > >def test(s,what): > try: > i = s.index(what) > print "It's here: ", i > except ValueError: > print "No 3's here" . . . A recent piece by Collin Park illustrates how a user-defined exception arises so naturally in a tiny toy example that it occurs to a teenager first program- ming. From sw at wordtech-software.com Sat Feb 11 09:34:37 2006 From: sw at wordtech-software.com (Kevin Walzer) Date: Sat, 11 Feb 2006 09:34:37 -0500 Subject: Yet another GUI toolkit question... In-Reply-To: <1139651109.458106.239760@o13g2000cwo.googlegroups.com> References: <9eae7$43ed2ce5$4275d90a$5719@FUSE.NET> <43ED6990.1020707@wordtech-software.com> <1139651109.458106.239760@o13g2000cwo.googlegroups.com> Message-ID: <7be9b$43edf5fd$4275d90a$3241@FUSE.NET> dberlin at gmail.com wrote: > What's wrong with wxPython? (http://www.wxpython.org) > Didn't see it mentioned here. > > ---- > David Berlin > http://farpy.holev.com - Python GUI Editor > I did mention it...see "scaling the wxPython mountain." -- Kevin Walzer iReveal: File Search Tool http://www.wordtech-software.com From paul at boddie.org.uk Thu Feb 9 16:50:55 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 9 Feb 2006 13:50:55 -0800 Subject: creat a DOM from an html document References: Message-ID: <1139521855.447729.286850@g14g2000cwa.googlegroups.com> John J. Lee wrote: > Mark Harrison writes: > > > Ahh, it's BeautifulSoup... > > Strictly that's not THE DOM, just A document object model. The DOM > proper is a standardised interface, which BeautifulSoup does not > implement. You could build a DOM using BeautifulSoup, though. For a certain value of standardised, libxml2dom provides "the DOM" for HTML: import urllib, libxml2dom f = urllib.urlopen("http://www.python.org") s = f.read(); f.close() d = libxml2dom.parseString(s, html=1) print "There are", len(d.xpath("//table")), "tables in the document." See http://www.python.org/pypi/libxml2dom for more information. Paul From jjl at pobox.com Sat Feb 4 18:39:53 2006 From: jjl at pobox.com (John J. Lee) Date: Sat, 04 Feb 2006 23:39:53 GMT Subject: Python vs C for a mail server References: <1138728303.669646.36940@g49g2000cwa.googlegroups.com> <1138805854.533303.279610@g49g2000cwa.googlegroups.com> <1138819666.521465.108000@o13g2000cwo.googlegroups.com> Message-ID: <87wtgar8vp.fsf@pobox.com> "Randall Parker" writes: [...] > Also, a lot of C++'s flaws flow from the fact that it is old and grew > in lots of increments. That was a deliberate decision on the part of C++'s designers!-) I guess the same is true of Python in some respects: it's still incrementally changing (more than C++, I guess), and isn't all that much younger than C++ (around 15 and 23 years old respectively). > In my experience the overhead of explicitly deleting objects in C/C++ > is not the big burden that some argue here is the biggest reason to use > Python instead of C++. Should we be entirely surprised that from somebody from a engineering / numerical analysis background has that experience? Fortran 77 didn't even *have* a standard way to do dynamic memory allocation, did it? I certainly do think garbage collection is useful in that context, though... John From john_zenger at yahoo.com Sat Feb 18 08:36:59 2006 From: john_zenger at yahoo.com (John Zenger) Date: Sat, 18 Feb 2006 08:36:59 -0500 Subject: Should we still be learning this? In-Reply-To: References: Message-ID: Don't overly concern yourself with your course being 100% up to date. When learning programming, the concepts are what is important, not the syntax or libraries you happen to be using. Even if they were to teach you the latest and greatest features of 2.4.2, that would be out of date in a few months/years when the next version comes along and the Python gods decide to deprecate the entire os module or something. Syntax and libraries change; just roll with it. When you are a student, the important thing is learning the mental skills of how to put it all together. When I was a wee lad, they taught me Pascal, a language that is now as dead as Latin, but I now realize that the language did not matter; all that mattered was that I learned the basics of how to design and put together a program in a (procedural) language. Once I knew that, it was a cinch to teach myself C in an afternoon, and only slightly tougher to learn C++ and then Java. Python is a good teaching language because by learning one language you learn three major programming paradigms: procedural, OO, and functional. It doesn't matter if, three years from now, a Dark Age descends upon the land and Python becomes as extinct as Pascal. If your course was decent, you spent your time learning programming, not just learning today's syntax and libraries, and you'll be able to learn Microsoft Visual C#++.Net.Com.Org or whatever other language happens to be fashionable in the future. And BTW, map and filter are such useful concepts that it makes sense to teach them to students even if they will one day be deprecated in Python. If you want to teach yourself Haskell or a Lisp dialect (and you should!), knowing those concepts will come in very handy. Max wrote: > On monday I start a semester course in Python (the alternative was > Java). I was looking through the course outline and noticed the following: > > 1) UserDict is used. This is deprecated, right? > 2) There is no mention of list comprehensions, but map and filter are > taught early and then revisited later. I don't think this is good: list > comprehensions are, IMO, one of Python's great features, Psyco prefers > them, they're more pythonic, and map and filter seem to be going out the > window for Python 3000. > > What do you think? > > --Max From oshecho at gmail.com Mon Feb 20 18:07:57 2006 From: oshecho at gmail.com (Echo) Date: Mon, 20 Feb 2006 18:07:57 -0500 Subject: editor for Python on Linux In-Reply-To: References: <1140423903.462774.193920@g14g2000cwa.googlegroups.com> Message-ID: <910885da0602201507y486c681fv2727235186043f64@mail.gmail.com> On 2/20/06, billie wrote: > I really think that IDLE is one of the best around in Python source editing. For me, I find that IDLE is about the worse for editing Python sources. I used to use Notepad++ before I started using Boa. Sometimes I still use Notepad++ because I can easly right click on a file to open it up in Notepad++. I use the editor that comes with Dabo. It has most features that any good python editor has. It does CURRENTLY lack many options, however that will change in the future. All of Dabo is being worked on and updated a lot, sometimes as much as 10-15 things changed, added and/or fixed in a day. Although, you will want the svn version for the most resent changes. -- -Echo From sam at nuevageorgia.com Tue Feb 14 10:58:02 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 14 Feb 2006 07:58:02 -0800 Subject: Embedding an Application in a Web browser In-Reply-To: <1139932108.356041.155100@g14g2000cwa.googlegroups.com> References: <1139930045.408507.151440@g43g2000cwa.googlegroups.com> <1139932108.356041.155100@g14g2000cwa.googlegroups.com> Message-ID: <1139932682.203839.212200@g44g2000cwa.googlegroups.com> Perhaps IronPython could be hacked in somehow also? Seems like it might could. From patrik at olga.removethispart.mine.removethispart.nu Tue Feb 14 14:55:46 2006 From: patrik at olga.removethispart.mine.removethispart.nu (Patrik Blommaskog) Date: Tue, 14 Feb 2006 20:55:46 +0100 Subject: Pythonic gui format? In-Reply-To: <1139858810.606052.39130@z14g2000cwz.googlegroups.com> References: <1139858810.606052.39130@z14g2000cwz.googlegroups.com> Message-ID: How about this: def mogrify(): print "Mogrifying" gui = window(title = "Hello World!") [ image(text = "nice pics here", pos = (5, 5), src = "img.png"), text(opts = "italic") ["(some text here)"], lst() [ "first element", "second element" ], button(action = mogrify, text = "Click Me!") ] There may be some slight errors above, but the principle works for me. The gui is described with valid Python code, and object order, types, parameter checking etc works in the way you would expect in Python. If you try not to think about how it abuses Pythons items, I find it quite nifty. I have a toy project where I build a gui like this, with two major differences from your wishlist: (1) My code does not contain the actual widget objects, but instead builds a tree that gets traversed to build the gui objects. (2) The only parser I have right now builds html documents with callback dispatching (using Turbogears). I envision generation of gui code for locally executed GUI:s (e g wxPython) as well. However, I see no immediate reason that you should not be able to put the actual widget objects in the tree like illustrated above. I did not in any way invent this method of description. If you are interested, a more mature use can be found in Nevow (http://divmod.org/trac/wiki/DivmodNevow) where they have a document object model called Stan, using a similar method to generate xhtml documents. I'd be happy to hear about other uses. I'll leave it to others to have opinions about whether it is to be considered pythonic. - Patrik From johnjsal at NOSPAMgmail.com Mon Feb 13 10:54:37 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 13 Feb 2006 15:54:37 GMT Subject: how do you pronounce 'tuple'? In-Reply-To: <11v18rggmsa317d@corp.supernews.com> References: <11v18rggmsa317d@corp.supernews.com> Message-ID: <1Z1If.1601$No6.38091@news.tufts.edu> Grant Edwards wrote: > On 2006-02-13, John Salerno wrote: >> Markus Wankus wrote: >> >>> I'm not sure, but I think it is pronounced "m?nage ? trois". >> LOL. You guys are hilarious. I think I made the right decision >> to start learning Python! :) > > Of course! What did you expect from devotees of a language > named after one of the greatest comedy shows in TV history? > Well, I hope this doesn't make me lose credibility, but I've actually never seen the show! I saw Holy Grail several years ago, though. But I'm very curious about this whole cheese shop skit, so when I get home tonight I'm going to download it. :) From ivoras at fer.hr Sun Feb 5 20:35:39 2006 From: ivoras at fer.hr (Ivan Voras) Date: Mon, 06 Feb 2006 02:35:39 +0100 Subject: Thread imbalance In-Reply-To: References: <1138912272.382474.13170@g44g2000cwa.googlegroups.com> Message-ID: Aahz wrote: > > When did Perl gain threads? At least in 2001: http://mail.python.org/pipermail/python-dev/2001-August/017079.html http://www.xav.com/perl/lib/Pod/perlthrtut.html > If you read Bruce Eckel, you also know that > the Java threading system has been buggy for something like a decade. I'm sure precisely this is the reason why all Java Enterprise systems (J2EE) are threaded network servers :) From fredrik at pythonware.com Mon Feb 20 11:46:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Feb 2006 17:46:02 +0100 Subject: Processing text using python References: <1140451760.998278.90430@g43g2000cwa.googlegroups.com> Message-ID: "nuttydevil" wrote: > Hey everyone! I'm hoping someone will be able to help me, cause I > haven't had success searching on the web so far... I have large chunks > of text ( all in a long string) that are currently all in separate > notebook files. I want to use python to read these strings of text, > THREE CHARACTERS AT A TIME. (I'm studying the genetic code you see, so > I need to read and analyse each sequence one codon at a time > effectively.) Does anyone have any idea of how to do this using python? did you read the string chapter in the tutorial ? http://docs.python.org/tut/node5.html#SECTION005120000000000000000 around the middle of that chapter, there's a section on slicing: "substrings can be specified with the slice notation: two indices separated by a colon" From http Mon Feb 27 06:47:33 2006 From: http (Paul Rubin) Date: 27 Feb 2006 03:47:33 -0800 Subject: PEP 354: Enumerations in Python References: <87accdplbj.fsf@rose.polar.local> <7xmzgdtjl0.fsf@ruckus.brouhaha.com> <4402AB7F.7070804@REMOVEMEcyber.com.au> <7xzmkdxkce.fsf@ruckus.brouhaha.com> <7xoe0tozf8.fsf@ruckus.brouhaha.com> Message-ID: <7xaccdvx9m.fsf@ruckus.brouhaha.com> Felipe Almeida Lessa writes: > > If enums aren't supposed to work in that construction then the PEP > > shouldn't specify that they work that way. > > Sorry, but where do they say that? The PEP gives an example of iterating through the members of an enum. I'm not sure if that's what you're asking, but if you meant something else, it went past me. From steve at holdenweb.com Sat Feb 25 01:53:04 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 25 Feb 2006 01:53:04 -0500 Subject: Trolling for New Web Host . . . In-Reply-To: <1140811452.070955.105180@e56g2000cwe.googlegroups.com> References: <1140811452.070955.105180@e56g2000cwe.googlegroups.com> Message-ID: Ben Wilson wrote: > I've had the same web host (imhosted.com) for the past three years, and > have had decent service. However, I'm also trying to learn Python the > hard way--by doing. So, I figured I'd write a few Python CGIs > (non-Zope). Unfortunately, my web host does not have mod_python. They > only way I can run a python script is by using the .cgi extension. I'm > not sure if I want to stick with my host and just call my apps > index.cgi, or if I should move to a new server. If I were to move to a > new server, which would you recomend, and why? > I'd recommend that you don't change anything until you have good reason - a business relationship that works is to be valued above a notional speed gain in a currently non-existent web application. If you're just learning, CGI is fine. Migrate to mod_python when you start to feel limited by CGI, or when you discover a specific need for mod_python's neat functionality. The only other advice I'd give you is to download Python on to your desktop or laptop machine and do some of your learning locally. It's quite difficult to debug through a web interface if you don't know what you're doing (and remember the cgitb module is your friend). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From fredrik at pythonware.com Thu Feb 16 03:08:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Feb 2006 09:08:22 +0100 Subject: How to run shell commands within python References: <1140074469.258382.24620@f14g2000cwb.googlegroups.com> <1140074866.157972.214920@o13g2000cwo.googlegroups.com> Message-ID: "fileexit" wrote: > thanks... i was to hasty to post this question, i found a good answer > here: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/ffdab847125f81b6 that's an old thread, and Python has grown a few more ways to deal with shell commands since then. if os.system isn't good en- ough for you, subprocess is the preferred alternative: http://www.python.org/doc/lib/module-subprocess.html (also note that most trivial shell commands are better done in python. most uses of cat, for example, can be trivially emulated with one or two lines of python...) From peter at engcorp.com Thu Feb 16 09:38:59 2006 From: peter at engcorp.com (Peter Hansen) Date: Thu, 16 Feb 2006 09:38:59 -0500 Subject: Is empty string cached? In-Reply-To: References: Message-ID: Farshid Lashkari wrote: > However, the following commands add to my confusion: > > >> a = 'wtf?' > >> b = 'wtf?' > >> a is b > False > > So how are string literals cached? Is there an explanation somewhere? Is > it some freaky voodoo, and I should just assume that a string literal > will always generate a new object? A few comments (which I hope are correct, but which I hope you will read then mostly ignore since you probably shouldn't be designing based on this stuff anyway): 1. What you see at the interactive prompt is not necessarily what will happen in a compiled source file. Try the above test with and without the question mark both at the interactive prompt and in source and see. 2. The reason for the difference with ? is probably due to an optimization relating to looking up attribute names and such in dictionaries. wtf? is not a valid attribute, so it probably isn't optimized the same way. 2.5. I think I had a third comment like the above but after too little sleep last night it seems it's evaporated since I began writing... 3. As Steve or someone said, these things are implementation details unless spelled out explicitly in the language reference, so don't rely on them. 4. If you haven't already written your code and profiled and found it lacking in performance and proving that the cause is related to whether or not you hoisted the string literal out of the loop, you're wasting your time and this is a good opportunity to begin reprogramming your brain not to optimize prematurely. IMHO. FWIW. :-) -Peter From irvine.david at gmail.com Sun Feb 12 19:09:53 2006 From: irvine.david at gmail.com (dirvine) Date: 12 Feb 2006 16:09:53 -0800 Subject: by reference In-Reply-To: <43ef1edd$0$4165$636a55ce@news.free.fr> References: <1139598954.259297.74290@o13g2000cwo.googlegroups.com> <43ef1edd$0$4165$636a55ce@news.free.fr> Message-ID: <1139789393.053912.15310@g14g2000cwa.googlegroups.com> Yes I did I was trying to do something like (pseudo code) write: get files in path for each filename get size, type create dic called filename assign size:xx,type:y pickle to file read: open pickled file read dict name and contents (hoping unpickling file gives me the dict name as it was saved, which may not be true) do stuff with file and thats it. My prog is a bit more complex than this but this is the general idea basically read files -> create dicts of files one at a time, very similar to bittorrent in that take a file smash to bits and store links to bits in a big file. Many thanls David From bonono at gmail.com Thu Feb 23 19:49:09 2006 From: bonono at gmail.com (bonono at gmail.com) Date: 23 Feb 2006 16:49:09 -0800 Subject: A C-like if statement In-Reply-To: References: Message-ID: <1140742149.011750.321530@z34g2000cwc.googlegroups.com> Steven D'Aprano wrote: > On Thu, 23 Feb 2006 12:04:38 -0700, Bob Greschke wrote: > > >> try: > >> i = a.find("3") > >> print "It's here: ", i > >> except NotFound: > >> print "No 3's here" > > > > Nuts. I guess you're right. It wouldn't be proper. Things are added or > > proposed every day for Python that I can't even pronounce, but a simple 'if > > (I = a.find("3")) != -1' isn't allowed. Huh. It might be time to go back > > to BASIC. :) > > There are *reasons* why Python discourages functions with side-effects. > Side-effects make your code hard to test and harder to debug. > >>> "test".index("a") Traceback (most recent call last): File "", line 1, in -toplevel- "test".index("a") ValueError: substring not found >>> "test".find("a") -1 From mahmood.tariq at gmail.com Wed Feb 15 18:59:47 2006 From: mahmood.tariq at gmail.com (Tariq) Date: 15 Feb 2006 15:59:47 -0800 Subject: Scientific Computing with NumPy In-Reply-To: References: <1d987df30602100415o16ad3d02n71aca12686667ff@mail.gmail.com> Message-ID: <1140047987.435267.194220@g43g2000cwa.googlegroups.com> Has anyone been able to successfully install numpy 0.9.4 on python 2.4 under cygwin? I'm getting a few errors, especially while it installs the C source. -- Tariq From pprobert at wisc.edu Thu Feb 23 17:12:17 2006 From: pprobert at wisc.edu (Paul Probert) Date: Thu, 23 Feb 2006 16:12:17 -0600 Subject: time.sleep(1) sometimes runs for 200 seconds under windows In-Reply-To: References: Message-ID: Peter Hansen wrote: >Are you saying that you believe the time.sleep(1) call is actually >blocking for 200 seconds? Or just that your loop (and we can only guess >what it looks like) is the one taking that long? > >If the former, try something like putting "print 'before'" and "print >'after'" before and after the sleep, and observe what happens when you >run the program. I'm fairly confident in saying there's no chance >you'll see the "before" sit for 200s before you see the "after" and that >your problem lies elsewhere, not with time.sleep(1). > >If the latter, um, obviously we can't help without more info. > >-Peter > > > Yes, I'm doing this: ..... oldtime=time.time() time.sleep(1) newtime=time.time() dt=newtime-oldtime if dt > 2: print 'dt=',dt,' time=',time.strftime('%Y_%m_%d_%Hh_%Mm_%Ss') Its happening roughly 4 times a day total on our 20 machines, ie about once every 5 days on a given machine. Paul Probert University of Wisconsin From pink at odahoda.de Fri Feb 17 14:34:10 2006 From: pink at odahoda.de (Benjamin Niemann) Date: Fri, 17 Feb 2006 20:34:10 +0100 Subject: Apparent eval() leak for python 2.3.5 References: Message-ID: John Marshall wrote: > Hi, > > I am reposting this message from python-dev. > > Could someone please test the code below > to verify that there is indeed a problem > with eval() under python 2.3.5. I have > rebuilt python 2.3.5 under the latest debian > and under RH 7.3 (in case the problem is > in system libraries). > > The following code causes the virtual memory > allocation to constantly increase until there > is no more memory left (the VIRT column of the > 'top' utility display). I have this leak, too in python2.3 under debian/sid: Python 2.3.5 (#2, Nov 20 2005, 16:40:39) [GCC 4.0.3 20051111 (prerelease) (Debian 4.0.2-4)] on linux2 python2.4 seems to be unaffected. Python 2.4.2 (#2, Nov 20 2005, 17:04:48) [GCC 4.0.3 20051111 (prerelease) (Debian 4.0.2-4)] on linux2 -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From fredrik at pythonware.com Tue Feb 28 02:33:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 28 Feb 2006 08:33:15 +0100 Subject: type = "instance" instead of "dict" References: <1141069989.763239.191140@u72g2000cwu.googlegroups.com> Message-ID: James Stroud wrote: > Perhaps you did not know that you can inheret directly from dict, which > is the same as {}. For instance: > > class Dict({}): > pass > > Is the same as > > class Dict(dict): > pass it is ? >>> class Dict({}): ... pass ... Traceback (most recent call last): File "", line 1, in TypeError: Error when calling the metaclass bases dict expected at most 1 arguments, got 3 From gjzusenet at gmail.com Mon Feb 27 06:58:47 2006 From: gjzusenet at gmail.com (gjzusenet at gmail.com) Date: 27 Feb 2006 03:58:47 -0800 Subject: Help getting started with Pycurl / libcurl ? Message-ID: <1141041527.250110.83770@e56g2000cwe.googlegroups.com> Hi I just couldn't google up any docs or tutorial on how to set up everything necessary to use pycurl on windows. When I try running the pycurl setup I get a 'CURL_DIR' not found error, but no where can I find a detailed explanation of what is this dir, what dlls I need to install and where etc. It's also somewhat confusing in the pycurl docs - do I need cURL or libcurl?? Any help would be much appreciated. From python.list at tim.thechases.com Sun Feb 26 11:35:13 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 26 Feb 2006 10:35:13 -0600 Subject: wxPython: help(wx) causes segfaulting? Message-ID: <4401D8C1.7030102@tim.thechases.com> Trying to get my feet wet with wxPython (moving from just command-line apps), I tried the obvious (or, at least to me was obvious): Start python, "import wx" and then do a "help(wx)" to see what it can tell me. Unfortunately, it spewed back a handful of errors, gasped, wheezed and died semi-hideously. It's a stock install of Python 2.3.5 on Debian (testing). The session has been pasted below if it's of any help. I can successfully "dir(wx)" and get back all the goods. However, the call to help() bombs out. I'm having trouble figuring out what went wrong in the matter: it looks like "g_object_new" is failing some assertion test, but not knowing the internal workings of CPython, I'm afraid this doesn't mean much to me. Any help or suggestions would be appreciated. If it makes a difference, other wxPython apps seem to run just fine (particularly pyalacarte has no trouble). Thanks, -tkc Python 2.3.5 (#2, Aug 30 2005, 15:50:26) [GCC 4.0.2 20050821 (prerelease) (Debian 4.0.1-6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import wx >>> help(wx) (process:11000): GLib-GObject-CRITICAL **: gtype.c:2254: initialization assertion failed, use IA__g_type_init() prior to this function (process:11000): GLib-GObject-CRITICAL **: gtype.c:2254: initialization assertion failed, use IA__g_type_init() prior to this function (process:11000): GLib-GObject-CRITICAL **: gtype.c:2254: initialization assertion failed, use IA__g_type_init() prior to this function (process:11000): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion `G_TYPE_IS_INSTANTIATABLE (instance_type)' failed (process:11000): GLib-GObject-CRITICAL **: gtype.c:2254: initialization assertion failed, use IA__g_type_init() prior to this function (process:11000): GLib-GObject-CRITICAL **: gtype.c:2254: initialization assertion failed, use IA__g_type_init() prior to this function (process:11000): GLib-GObject-CRITICAL **: gtype.c:2254: initialization assertion failed, use IA__g_type_init() prior to this function (process:11000): GLib-GObject-CRITICAL **: g_object_new: assertion `G_TYPE_IS_OBJECT (object_type)' failed Segmentation fault From tprimke at interia.pl Sat Feb 4 12:51:22 2006 From: tprimke at interia.pl (TPJ) Date: 4 Feb 2006 09:51:22 -0800 Subject: A problem with some OO code. In-Reply-To: References: <1139055710.688193.81000@z14g2000cwz.googlegroups.com> Message-ID: <1139075482.510942.71640@z14g2000cwz.googlegroups.com> At first I'd like to thank you for such a long answer. > (...) > You need to simplify the code as much as possible, cutting away everything > you can, to the SMALLEST amount of code that still experiences the problem. I understand your POV and I really appereciate your reply, but I doubt that I could simplify my code to make it small *enough* to fit in one post and not look too long. BTW: is there some safety way to show long piece of code on a group like comp.lang.python? Uploading my code to my website was the first (and the only one...) idea I had. > (...) > There is very little point in showing us test code > that works -- your problem isn't with code that works, it is with code > that doesn't work. You see - that's one of my problems. I'm working on my PyObject module (it is intended to be a base for more complex systems). For now there are no other modules, that use PyObject. So the test.py module, that consists of some test for my module, is the *only* piece of code that I could show you. That's all the story. > > All you need to know is that there are four classes. > > No, I'm sure we need to know much more than that. Yes, you're right. But I tried to explain my problem as easily as possible. And (as I thought) only four classes were involved. > > (Of course, you > > may generate all the documentation by typing just "./make_docs". All > > you need is Python with Epydoc installed.) > > Oh right, well just let me rush off and install Epydoc just for you, okay? It was not my intention to ask you to install anything for me. I just thought, that someone might be interested to read some documentation about the module, that causes the problem. I think it's easier to read documentation of more complex system, than just code. Perhaps it's about my English (I'm still studying) - a language easy to learn, but difficult to master. By "you may" I meant "you might, if you'd like to (for some reasons)", not "you are expected to do it". > > In the PyObject.py there are two classes: Object and OManager. When > > Object wants to know if some link is safe (in another words: it wants > > to know if some another object exists), > > What is a link in your application? What do you mean "another object"? > Like an int or a string? 1) In OO vocabulary, class is something like template for an object. But I think the word "object" has something different meaning in Python. In general I don't use the word "object" in the same meaning, that it is used by Python. I try to use words in the same way, that they are used in OO. Sometimes I use the word "class" to talk about template (for an object), and the word "instance" to talk about an object of some class, but the only reason I do it is to distinguish between OO-object and Python-object. 2) Link is something like address (like a post address). My module - in general - is just a template of a system of objects, that are able to communicate with each other. All that an object needs to communicate with an another object, is the name of that another object - it's adress (my assumption is that the names of the objects will be unique). "Link" to an another object is just the name of that object. > > it calls the proper method of > > its objects' manager (the OManager instance). Details are not important > > here, > > I bet the details are absolutely vital. Yes, they are - were. But I didn't want to describe my code in details in my post. I suspected, that there's some stupid mistake somewhere in my code. The truth is, all I wanted was someone else to take a look at this code. (BTW - I was right. My problem was caused by a spelling mistake, and someone found it. And it made me feel very stupid, but I think I deserved it.) > > so I'll just say, that if the link is safe, the objects' manager > > calls the proper method of the object, that sent him request. This > > method of the object just stores the information about that link (that > > it's safe), in the so-called private field (the fields used to store > > the information about the links are called __ls_existing_links and > > __ls_demanded_links). > > This is a terribly involved way of doing it, and I'm not even sure what > "it" is that you are trying to do. Are you trying to do some sort of > dispatch mechanism? My idea is as follows: 1) There's one objects' manager, that manages all the objects in some system. 2) Every object has its unique name, and is registered with the objects' manager. 3) When an object-sender wants to send a message to some object-receiver, all that the object-sender has to do is to tell the objects' manager, what's the name of the object-receiver. The only problem is that the object-sender has no idea if the object-receiver exists. A situation, when object-receiver doesn't exist, shouldn't happen, but as long as code is written by people, such a mistake can be done. Therefore I developed a mechanism, that may prevent such a situation. Every object-sender must create a link to the object-receiver. A link is just the name (id) of the object-receiver. There's only one OO-object in the system, that knows, if the object-receiver exists. It's the objects' manager. So the object-sender "asks" its objects' manager, if the link from that object-sender to the object-receiver is "safe" (in another words: if the object-receiver exists). If the object-receiver exists, the objects' manager just informs the object-sender (that might be also called the object-requester), that the link is safe (and can be used). But if the object-receiver doesn't exist, the objects' manager doesn't inform the object-requester about anything. Now, there are two different scenarios, that might happen: a) The object-receiver will be created - this is the desired situation. When the object-receiver will be registered with the objects' manager, the objects' manager will inform the object-requester, that the object-receiver exists and the link is safe. b) The object-receiver won't be created. Because the object-requester tracks all the demanded links, it knows, that not all of these links are safe - and therefore it knows, that it's not ready to work. In the final version of the module, the objects' manager will be able to check, if there are any objects, that aren't ready to work. In such a case the whole system just won't work (and it'll explain the developer why). It's not so complicated, and I suppose it will help me to create less error-prone code in the future. > I see you have a line "i = self.__ls_demanded_links.index( s_object )". It > looks like you are storing your data in a chunk of text, and then running > index on that text to find the bit you want to work with. If you wanted to > do that much work, just write your script in bash and be done with it! > Python has lists and dicts and other advanced data structures. Use them. > You will be glad. The reason, why a list was used in this case, is now obsolete and it will probably change in the future. But, in general, you're right. The dictionary would be much better in this case even in the previous version of my module. And... I know how great are lists, dicts and tuples. That's the reason I threw out Java, C++ and (in most cases) C, and fell in love with Python. In my personal opinion the adventure with Python begins in the moment, when you realize, how easy are lists, dicts and tuples to use. (Yes, I know, there are also sets, but I don't use them at all. So far...) > So Obj is an alias for Object? What's an Object? Is it the same as the > Python built-in type "object"? > > But later on you say: > > "All these methods are the methods of the Object class (defined in > PyObject.py), not of the Obj class (defined in test.py)." > > So Object and Obj are not the same. No. I think that the declaration of the Obj class will explain everything: class Obj( Object ): ... So the Obj class is an *extension* of the Object class. Therefore I wrote that "Obj is just an Object". I (mis?)used the vocabulary from OO: something may *be* a kind of something else (inheritance), or it may *has* something else (composition). But I'm not sure about those words; I have read many books in Polish, not in English. > > -------------------------------------------------- > > Traceback (most recent call last): > > File "test.py", line 142, in test04CreateSystems > > system1 = System1() > > File "test.py", line 81, in __init__ > > self.objA.demandNewLink( 'B' ) > > File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", > > line 503, in demandNewLink > > s_object ) > > File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", > > line 800, in _makeNewLink > > o_srcobj._makeLinkSafe( s_target ) > > File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", > > line 608, in _makeLinkSafe > > self.__makeLinkSafe( s_object ) > > File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", > > line 582, in __makeLinkSafe > > i = self.__ls_demanded_links.index( s_object ) > > AttributeError: 'Obj' object has no attribute > > '_Object__ls_demanded_links' > > [snip] > > > Perhaps I'll explain what's going on there. First, the objects' manager > > is created, and then also some objects are created. After doing that, > > the object called "objA" demands a new link to the other object, called > > "objB" (this is the line 81 in the error message above). > > Your description does not match what line 81 actually says. It says: > > self.objA.demandNewLink('B') > > self (an instance of System1, not Obj or Object) grabs the attribute > called "objA", and calls its method demandNewLink with an argument of > the string 'B', not objB an instance of Obj or Object. It's a typo, it should be 'B' instead of "objB". In fact, the reference to the object "B" is self.objB - I think that's the reason for this mistake. > If you want to work with Object instances, why not just use them instead > of passing around strings that represent them? Well, I *don't* want to work with any instances, therefore I intend to give all the objects unique names. > (...) > Huh? Do you mean that there is a way for links (whatever they are) to be > requested without calling demandNewLink? How would this happen? Well - it's Python, so *anything* can be done with any so-called private attributes. Therefore such a possibility exists. But it's not intended to be used in such a way. In "normal" use it's impossible to request a link without calling demandNewLink method. Perhaps my explanation wasn't too clear. > > All these methods are the methods of the Object class (defined in > > PyObject.py), not of the Obj class (defined in test.py). According to > > my knowledge about the OO programming Python should be able to realize, > > that the so-called private fields, that are being referred from these > > Object class methods, are the private fields of the *Obj class > > instance*, not of the *Object class one*. > > Some serious confusion here. > > What are fields? Do you mean attributes? I'm going to assume that you do. > > Would it help if I told you that Python doesn't have private attributes? > It *simulates* private attributes using name mangling. 1) "Fields" - yes, I think I should have written attributes. Sorry for that, my problem is that the only books about OO that I have read were in Polish, so my vocabulary might be incorrect. In general, every object has methods (functions, procedures, etc.) and - I think - attributes (variables). 2) I know that Python has no private *anything*, and therefore I called it "so-called private". > (...) > PLEASE don't bother to tell us how Python sucks because it doesn't have > "real private attributes", we've heard the arguments (and the abuse) fifty > times before. Python's not sucks, I find it the best programming language in the world. It suits all my needs. Believe me or not, but I have argued for Python to be (one of) the best language(s) to write OO applications. Since I have started coding in Python, I found that the idea of private, protected and public attributes/methods may be as well the matter of *convention*, as real *mechanism*. Anyway, I don't find Python inferior to any other OO language just because Python have no *real* private methods/attributes. So, I think, we're both on the same side. > (...) > > Good. Now how about getting a simple program that demonstrates your > problem? > > (...) > > Do you enjoy all this make-work, writing tedious methods to get or set or > print attributes? I suggest you ditch all the private attributes and just > make them public. You've already spent three days hitting your head > against a brick wall because of excessive data-hiding. Was it worth it? > Python is a language that encourages the attitude "We're all adults here" > -- getters/setters are discouraged. Maybe I'll make it clear: I wrote this simple example to show *myself*, that I'm not out of my mind. It was supposed to be *very* simple. I just wanted to check, if I'll be able to change the so-called private attribute declared in the A class by calling a method declared in another class. That's all. I think that if I hadn't done it, I would have started to doubt, that 2 + 2 = 4. Why I did such a obvious test? Because I thought that it was my problem in the PyObject module: the need to change a so-called private attribute declared in the class Object by calling a method of another class (an instance of another class, to be precise). > (...) > > The call to A.__init__ creates an attribute __a to self. Remember, self is > an instance of B (not A). Apply the name-mangling rules, which are applied > at compile time: the code in A's method mangles __a to _A__a. So > A.__init__ creates an attribute _A__a in B's namespace. So B has two > attributes, _A__a and _B__b. > > (...) > > (However, that is not your problem.) So it works just as it's supposed to work. All right, now I'm OK. My madness has gone. > (...) > > Here is your exception again: > > (...) Well, I decided to cut out all the rest - because (I think) it has nothing to do with my code - and therefore with my problem. Once again - thank you for such a long and thorough answer. Once again - sorry for some mistakes that I made in my first message, especially for those "fields" (I feel really silly now). I wrote the first message in the state of madness, after spending *three* days on analysis of my code, without any progress. I was very frustrated, and my explanations could be incomprehensible. From donn at drizzle.com Mon Feb 20 01:01:22 2006 From: donn at drizzle.com (Donn Cave) Date: Mon, 20 Feb 2006 06:01:22 -0000 Subject: Python vs. Lisp -- please explain References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> <43f8ba1e$0$2895$626a54ce@news.free.fr> Message-ID: <1140415281.679774@jetspin.drizzle.com> Quoth Alexander Schmolck : | "Fredrik Lundh" writes: ... |> the only even remotely formal definition I've ever seen is "language with |> designed to script an existing application, with limited support for handling |> its own state". | |> Early Tcl and JavaScript are scripting languages, Python is not. | | Right. Which shows that by this definition scripting language is not a | meaningful and useful concept. No one will understand you correctly when you | refer to "scripting language" and mean only something like the above -- and | unless you spend a lot of your time talking about early tcl and early | javascript I doubt you'd need a word for it, either. Oddly enough, that's what I understand it to mean, too, so you can't strictly say "no one". On the other hand, I think it's obvious that a language like Python could be used for scripting, without having been specifically designed for it as described above. There's an ambiguity in the phrase, out of context - I can say "Python can serve as a scripting language for some applications", but not "Python is a scripting language!", since its place in the taxonomy of languages would be somewhere else. Donn Cave, donn at drizzle.com From python at rcn.com Fri Feb 17 06:06:43 2006 From: python at rcn.com (Raymond Hettinger) Date: 17 Feb 2006 03:06:43 -0800 Subject: Add a month References: <1140173540.686250.205760@g44g2000cwa.googlegroups.com> Message-ID: <1140174403.681691.256450@g14g2000cwa.googlegroups.com> [novin01 at gmail.com] > Hi, this is probably a really simple question but... > How do you add a month to a datetime date in python? It would be nice > if you could do something like: > > d = datetime.date(2006,2,17) > dm = datetime.timedelta(months=1) > d_new = d + dm > > but timedelta doesn't have a 'months' setting. Am I missing some easy > method or do I have to code a work around myself?? You need to code you own version. It was not included with datetime.timedelta() because the definition is ambiguous (i.e. what date is one month after Jan 30th?). Raymond From pmartin at snakecard.com Thu Feb 23 21:29:00 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Thu, 23 Feb 2006 20:29:00 -0600 Subject: Python stdout and Win 2003 Message-ID: Hi, I have a program at a customer's site that seems to have random problem which eventually come down to not being able to read/write from serial ports. I trapped all the exceptions I could think of and all of them look like this: *********************************** (ACCESS CONTROL)Fri, 24 Feb 2006 02:07:18 +0000 : Traceback (most recent call last): File "C \Python24\lib\site-packages\SC\readers\SC_IDTech_MiniSmart_RS232.py", line 308, in Is_Card_Inserted print 'CARD NOT INSERTED' IOError: [Errno 9] Bad file descriptor *********************************** To me that means the print failed ... that stdout was not available anymore. Am I correct? .... what could cause this. Many thanks. Philippe From lycka at carmen.se Fri Feb 24 05:45:04 2006 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 24 Feb 2006 11:45:04 +0100 Subject: ls files --> list packer In-Reply-To: <1140768527.006363.29050@i39g2000cwa.googlegroups.com> References: <1140765792.864556.289820@i40g2000cwc.googlegroups.com> <1140767111.490691.42460@e56g2000cwe.googlegroups.com> <1140768527.006363.29050@i39g2000cwa.googlegroups.com> Message-ID: kpp9c wrote: > that other sillyness i mentioned is not strickly required ... just > dreaming but i know involves some kind of os walk type thing prolly ... os.walk isn't exactly rocket science... Something similar to this? >>> import os >>> for dir, dirs, files in os.walk('.'): ... txt_files = [x for x in files if x.endswith('.txt')] ... if txt_files: ... print dir, txt_files From fredrik at pythonware.com Sun Feb 19 21:55:09 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Feb 2006 03:55:09 +0100 Subject: Python vs. Lisp -- please explain References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> Message-ID: Alexander Schmolck wrote: > My point was that Guido probably (and fortunately!) was unaware of the extent > to which you can have both dynamism and speed any my point was that chosing to ignore something doesn't mean that you're ignorant. (but since you keep repeating this nonsense, it's clear that you're pretty ignorant wrt. software design. too much CS exposure?). From grante at visi.com Mon Feb 6 15:56:42 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 06 Feb 2006 20:56:42 -0000 Subject: Accessing Windows Serial Port References: <1139253898.601680.265220@g44g2000cwa.googlegroups.com> Message-ID: <11ufe0agltktg7d@corp.supernews.com> On 2006-02-06, George T. wrote: > I need to access the serial port via python on a windows machine. > Reading on the web, there are three solutions: pyserial, siomodule and > USPP. You can also just use win32 stuff directly (CreateFile et al). > pyserial seems to be the best option since the other two are > tested with Windows 95 and older versions of python. Would you agree > with this or have I missed an option? I've used PySerial and win32 system calls. I've never used the other two. Try pyserial first. If you need lower level control than that gives you, use win32 calls. > Can anyone provide me an example of how to access the serial port with > pyserial? http://pyserial.sourceforge.net/ -- Grant Edwards grante Yow! Is this "BOOZE"? at visi.com From joao.macaiba at gmail.com Wed Feb 8 10:01:38 2006 From: joao.macaiba at gmail.com (Joao Macaiba) Date: Wed, 08 Feb 2006 13:01:38 -0200 Subject: Undergraduate project :: python ToDo list Message-ID: <43EA07D2.4090108@gmail.com> Hi. I would like to know if there's any todo list on python project. My interest in doing a undergraduate project. It could be anything in the python core interpreter. I program C/C++. Thanks in advance. Regards. Joao Macaiba (wavefunction) From pprobert at wisc.edu Thu Feb 23 17:00:40 2006 From: pprobert at wisc.edu (Paul Probert) Date: Thu, 23 Feb 2006 16:00:40 -0600 Subject: time.sleep(1) sometimes runs for 200 seconds under windows In-Reply-To: <43FE2A14.5070609@benjiyork.com> References: <43FE2A14.5070609@benjiyork.com> Message-ID: Benji York wrote: >Paul Probert wrote: > > Hi, My app runs in a loop looking for changes in a database, and like > > a good boy I call time.sleep(1) inside the loop. Unfortunately this > > sometimes runs for 200 seconds or so, presumably while my OS is > > calling Bill Gates to tell him what I've been doing. This happens > > under NT4, W2k, and XP. What do people do to fix this? Thanks! > > From the docs for time.sleep: > > The actual suspension time may be less than that requested because > any caught signal will terminate the sleep() following execution of > that signal's catching routine. Also, the suspension time may be > longer than requested by an arbitrary amount because of the > scheduling of other activity in the system. >-- >Benji York > > Benji, Thanks, but yes, I had read that before posting. One would think, though, that the extra 200 seconds is a bit extreme to be blamable on system scheduling granularity. I'm starting to think we've got a worm of some kind. If so, its invisible to our Norton AV corporate. Paul Probert University of Wisconsin From jgardner at jonathangardner.net Fri Feb 24 19:22:07 2006 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: 24 Feb 2006 16:22:07 -0800 Subject: Playing with modules In-Reply-To: <1140808435.311458.86770@z34g2000cwc.googlegroups.com> References: <1140808435.311458.86770@z34g2000cwc.googlegroups.com> Message-ID: <1140826926.993654.188640@j33g2000cwa.googlegroups.com> You're going to have to create the home.base module somewhere. If you want to put in that some code that basically imports another module's namespace into the home.base module's namespace, then that may do what you want. From jdhmistey at gmail.com Thu Feb 16 20:49:50 2006 From: jdhmistey at gmail.com (jdhmistey at gmail.com) Date: 16 Feb 2006 17:49:50 -0800 Subject: Pyserial never read In-Reply-To: <1140105936.408387.88130@z14g2000cwz.googlegroups.com> References: <1140105936.408387.88130@z14g2000cwz.googlegroups.com> Message-ID: <1140140990.492289.185060@g47g2000cwa.googlegroups.com> I don't know alot about python but I could help you with english? eventhough it was really good best regards- Just From steve at holdenweb.com Mon Feb 13 16:54:50 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Feb 2006 16:54:50 -0500 Subject: Pulling all n-sized combinations from a list In-Reply-To: <1139861618.098084.250350@g14g2000cwa.googlegroups.com> References: <1139431819.946571.56710@g44g2000cwa.googlegroups.com> <1139509392.890581.94470@g43g2000cwa.googlegroups.com> <1139513265.440321.184530@o13g2000cwo.googlegroups.com> <1139527129.367077.316590@g44g2000cwa.googlegroups.com> <1139601545.595021.201610@g44g2000cwa.googlegroups.com> <1139861618.098084.250350@g14g2000cwa.googlegroups.com> Message-ID: mensanator at aol.com wrote: > Magnus Lycka wrote: > >>mensanator at aol.com wrote: >> >>>But it turns out he actually had one, which he graciously provided >>>in response to my observation. If I had kept my trap shut, I wouldn't >>>have it, would I? [...] > And, strange as it may seem, asking questions the > smart way is sometimes less effective than being a > smartass. Given a chance to say > > idiot, you're wrong and here's why... > > people will jump all over you. Take this thread, > for example. Of course, if they just call you an idiot > then you haven't gained anything. > > But there's nobody like that on comp.lang.python, right? > Of course not, you idiot :-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From keith.b.perry at gmail.com Tue Feb 21 10:32:19 2006 From: keith.b.perry at gmail.com (kbperry) Date: 21 Feb 2006 07:32:19 -0800 Subject: Zope/Plone - Is it the right solution? In-Reply-To: References: <1140532818.195281.316580@g44g2000cwa.googlegroups.com> Message-ID: <1140535939.444599.30350@g43g2000cwa.googlegroups.com> Well, I guess our main goal in this class is to improve usability and user experiences at the site. While we want to improve our site visually and make it more usable to the prospective students, the site needs to be easily updated. I don't think that I am looking for a wiki. I will definitely check out Django and turbogears. Thanks a ton for the info! From aleaxit at yahoo.com Mon Feb 20 16:39:24 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Feb 2006 13:39:24 -0800 Subject: Quesion about the proper use of __slots__ References: <1140424508.393412.79140@o13g2000cwo.googlegroups.com> <43f9825e$0$4777$636a55ce@news.free.fr> <1140426860.033363.237150@o13g2000cwo.googlegroups.com> <1hb1vq2.1ij7f8e1bx24u8N%aleaxit@yahoo.com> Message-ID: <1hb28j3.1wgv4b2a54odpN%aleaxit@yahoo.com> Peter Hansen wrote: > Alex Martelli wrote: > > Zefria wrote: > > ... > >>this special case I'm expecting each "carrier" to have up to 150 > >>fighters, and 3 to 5 carriers for each of the two teams, which comes > >>out to be quite large. > > > > The problem with the spread of email is that it reduces the number of > > envelopes laying around, and thus makes it harder to do "back of the > > envelopes" calculations (the key skill in engineering...). > > Actually, a properly performed "engineering approximation" is done > entirely in one's head, preferably without resorting to calculation at > all. Of course, but you still need an envelope on whose back to scribble. Tradition and historical continuity demand it. > The "back of the envelope" ploy is reserved for cases where one is > trying to impress a waitress (which effort is inevitably doomed to fail > of course), or to make it easier to submit the dinner receipt as a > business expense... That's "back of the restaurant bill", a different though related technique. Since most restaurants don't print bills on envelopes, the two are not really comparable. Alex From arutz at mimoza.pantel.net Thu Feb 2 16:19:05 2006 From: arutz at mimoza.pantel.net (Antal Rutz) Date: Thu, 02 Feb 2006 22:19:05 +0100 Subject: Collecting snmp data - threads, processes, twisted? Message-ID: <43E27749.6010701@mimoza.pantel.net> Hi all, I'd like to collect snmp data from varoius network devices parallel. First I tried with my own threadpool class then I gave a try to Christopher Arndt's threadpool.py (http://chrisarndt.de/en/software/python/threadpool.html). I got the same result: with one thread it finished about 2 mins with more threads it needed more and more time. Maybe I ran into the situation where threads aren't the best. I use yapsnmp (fair easy to 'snmpwalk') for collecting. it uses net-snmp. Could you give me some advice how can I make my script really parallel? My options maybe: 1. pySNMP (as it's full in python) 2. subprocess (I'd like to make (find) a solution as threadpool.py) (running yapsnmp, pySNMP or even net-snmp?...) 3. TwistedSNMP (seems too weird for me.. cannot imagine a simple solution for my problem) 4. ... thanks for your help -- --arutz From cyril.bazin at info.unicaen.fr Tue Feb 28 07:42:31 2006 From: cyril.bazin at info.unicaen.fr (Cyril Bazin) Date: Tue, 28 Feb 2006 13:42:31 +0100 Subject: PEP 354: Enumerations in Python In-Reply-To: <1141125265.118619.36500@i40g2000cwc.googlegroups.com> References: <87accdplbj.fsf@rose.polar.local> <1141109451.570616.86140@p10g2000cwp.googlegroups.com> <1141125265.118619.36500@i40g2000cwc.googlegroups.com> Message-ID: What about that? SomeNumbers = enum('0', '1', '2', '3', '4', '5', '6', '7') or Rooms = enum('1bed', '2beds', 'moreThan2beds') or even Comments = enum('#', ';', '//') Cyril On 28 Feb 2006 03:14:25 -0800, Carl Banks wrote: > > Stefan Rank wrote: > > on 28.02.2006 07:50 Carl Banks said the following: > > > Ben Finney wrote: > > >> This PEP specifies an enumeration data type for Python. > > > > > [snip] > > > > > > Here's why I think it's not too useful to begin with: the benefits of > > > the enum you describe here are pretty weak. > > > > I need to disagree heavily here :) > > "the benefits of the enum you describe here [beyond my example which I > claimed enum was only a minor improvement over] are pretty weak." > > > > > It's a pretty weak case to have a dedicated builtin to prevent > > > duplicates in something that changes maybe once a month, as enums tend > > > to change rather slowly. (At least, that's the way enums in other > > > languages are used, and the design you present here seems to suggest > > > you intend to use them that way as well.) And frankly, a unit test or > > > assertion could check this. > > [snip] > > > > I don't understand what you mean by 'change rather slowly'? > > Construct data structure on-the-fly from an XML file edited by multiple > people every day = changes rather quickly > > Construct data structure from a Python file that was last edited a year > and a half ago = changes rather slowly > > Typically, enums fall into the latter category. You set the enum > values, and then pretty much leave them alone, adding new values only > occasionally. (Come on, how often do the days of the week change?) > All I was saying is, changes to the enum values are infrequent enough > that having a special type just to make sure there are no duplicates is > a waste. The only justification for a built-in enum is the other stuff > you mentioned. > > > > One thing that is probably missing to allow this, is a enum-set-creation > > with the | operator:: > > > > Weekdays = enum('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun') > > daysihate = Weekdays.mon | Weekdays.thu > > > > (and this discussion needs to move to python-dev ?) > > What's wrong with set((Weekdays.mon,Weekdays.thu))? Explicit is better > than implicit. > > > > As for the metaclass versions: For myself, the above version feels more > > natural and straightforward (in the same way as the PEP author describes > > it), though I understand the subclassing ideas. > > > > But are there use cases for subclassing, that aren't better served with > > a new enum or something homegrown? > > Can C++/Pascal/Java enums be subclassed? > > In C++, enum is a type but not a class. Same thing with Ada. Java > didn't have enums last time I checked. Don't know about Pascal. I > didn't care too much about subclassing; I just thought different enum > constant that couldn't (or, rather, oughtn't) be compared probably > should be instances of a separate class. It doesn't matter much, > though. > > Should something like this work: > > day = Weekdays.mon > isinstance(day,Weekdays) > > ? > > > Carl Banks > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.petrazzo at TOGLIunipex.it Wed Feb 22 13:27:55 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Wed, 22 Feb 2006 19:27:55 +0100 Subject: PyUNO with different Python In-Reply-To: References: Message-ID: <43fcad29$0$29099$5fc30a8@news.tiscali.it> ? wrote: > Hi! maybe somebody can give me an hint to my problem setting up PyUNO > on my Mac to work with my Python not the Python delivered with > OpenOffice. As said in installation instructions I've set > OPENOFFICE_PATH="/usr/lib/openoffice/program" export > PYTHONPATH="$OPENOFFICE_PATH" export > LD_LIBRARY_PATH="$OPENOFFICE_PATH" according to my environment. > > importing uno gives me this error: > >>>> import uno > Traceback (most recent call last): File "", line 1, in ? File > "/Applications/OpenOffice.org > 2.0.app/Contents/openoffice.org2.0/program/uno.py", line 37, in ? > import pyuno ImportError: No module named pyuno > > which means python finds uno but not pyuno (pyuno.dylib). > Do you want to use system python inside OOo (inside a macro, or...), or system python outside OOo? For the first, follow this: http://udk.openoffice.org/python/python-bridge.html#replacing for the second: http://udk.openoffice.org/python/python-bridge.html#modes > Any hints? Regards, Katja Michele From scott.daniels at acm.org Wed Feb 22 20:05:47 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 22 Feb 2006 17:05:47 -0800 Subject: What's up with this code? In-Reply-To: <1140649331.924736.128420@g43g2000cwa.googlegroups.com> References: <1140649331.924736.128420@g43g2000cwa.googlegroups.com> Message-ID: <43fd08cf$1@nntp0.pdx.net> Gregory Petrosyan wrote: > Hello, it's me again. > I am trying to optimise small module for working with polynomials, and > I have encountered problem: new, optimised, code, doesn't work in some > specific case. Here's the old version of the code: > > (3x^2 + 2x + 1 <=> poly([3, 2, 1]), btw) > > def __add__(self, other): > "Return sum of two polynomials" > rcoefs1 = list(reversed(self.coefs)) > rcoefs2 = list(reversed(other.coefs)) > coefs = [c1+c2 for c1,c2 in zip(rcoefs1, rcoefs2)] > minlen = min(len(rcoefs1), len(rcoefs2)) > coefs.extend(rcoefs1[minlen:] + rcoefs2[minlen:]) > return Polynomial(reversed(coefs)) > > Here's the new version: > > def __add__(self, other): > rcoefs1 = reversed(self.coefs) > rcoefs2 = reversed(other.coefs) > coefs = [c1+c2 for c1,c2 in it.izip(rcoefs1, rcoefs2)] > coefs.extend(it.chain(rcoefs1, rcoefs2)) #? -- here is magic > if coefs[-1] != 0: > return Polynomial(reversed(coefs), False, False) > else: > return Polynomial(reversed(coefs), False) > > Last four lines are ok (tested), "magic" seems to occure in #? line. > What's the magic? Here it is: > > poly([1,2,1]) + poly([1,-2,1]) is ok, > poly([1,-2,1]) + poly([5,4,3,2,1]) is ok, > poly([1]) + poly([2]) is ok, > poly([1,2,1]) + poly([5,4,3,2,1]) is ok, but > > poly([1,0]) + poly([-1]) gives poly([-1]), > poly([1,-3]) + poly([-2]) gives poly([-5]) etc. > > "magic" happens when processing something like poly([a,b]) + > poly([c]) and it gives poly([b+c]) as result. Can anybody help me with > it? OK, the trick is to think about how zip/izip _must_ work. When the first list runs out first it stops. When the second list runs out, it has already read ahead one element of the first list. def __add__(self, other): shorter = reversed(self.coefs) longer = reversed(other.coefs) if len(self.coefs) > len(other.coefs): shorter, longer = longer, shorter # insure shorter first coefs = [c1+c2 for c1,c2 in it.izip(shorter, longer)] if len(self.coefs) == len(other.coefs): while coefs and coefs[-1] == 0: coefs.pop() else: coefs.extend(longer) ... --Scott David Daniels scott.daniels at acm.org From fraca7 at free.fr Tue Feb 21 09:33:17 2006 From: fraca7 at free.fr (fraca7) Date: Tue, 21 Feb 2006 15:33:17 +0100 Subject: Mutable numbers In-Reply-To: References: Message-ID: <43fb2462$0$3211$636a55ce@news.free.fr> Suresh Jeevanandam a ?crit : > # I am new to python. > > In python all numbers are immutable. This means there is one object ( a > region in the memory ) created every time we do an numeric operation. I > hope there should have been some good reasons why it was designed this way. The memory allocation for integers is optimized. 'Small' integers (between -5 and 100 IIRC) are allocated once and reused. The memory for larger integers is allocated once and reused whenever possible, so the malloc() overhead is negligible. From felipe.lessa at gmail.com Tue Feb 14 20:38:27 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 14 Feb 2006 23:38:27 -0200 Subject: Soduku In-Reply-To: <1139967167.960780.171360@o13g2000cwo.googlegroups.com> References: <1139967167.960780.171360@o13g2000cwo.googlegroups.com> Message-ID: <1139967507.22163.18.camel@kenshin> Em Ter, 2006-02-14 ?s 17:32 -0800, Jonathan Gardner escreveu: > So, one more story on why Python is really good. I think, at least with > 2.4, we should start bragging about Python's speed. I mean, it beats > Java AND perl! Maybe the other implementations also have errors? Well, I'm not saying Python is worse than them, I'm just trying to be fair. Besides, puzzles can't say if one is better than the other, they're completely out of the reality of most programs. Just my two cents, Felipe. -- "Quem excele em empregar a for?a militar subjulga os ex?rcitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destr?i os estados dos outros povos sem lutas prolongadas. Deve lutar sob o C?u com o prop?sito primordial da 'preserva??o'. Desse modo suas armas n?o se embotar?o, e os ganhos poder?o ser preservados. Essa ? a estrat?gia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" From lycka at carmen.se Wed Feb 8 11:06:16 2006 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 08 Feb 2006 17:06:16 +0100 Subject: 450 Pound Library Program In-Reply-To: <1139411880.032250.181300@g43g2000cwa.googlegroups.com> References: <1139351498.090768.82270@o13g2000cwo.googlegroups.com> <43e9f1e1$0$612$636a15ce@news.free.fr> <1139411880.032250.181300@g43g2000cwa.googlegroups.com> Message-ID: plahey at alumni.caltech.edu wrote: > Ok, > > I give up. DRY = Don't Repeat Yourself (google Pragmatic Programmers) > but SPOT? Google is little help here, SPOT is too common a word. The only SPOT I worked with (as I know of) was SPOT4 (Le Systeme Pour 'l Observation de la Terre) but that's probably not it... Single Point Of Truth? It seems some claim that DRY and SPOT are the same things. http://www.artima.com/cppsource/reducepnp3.html From timr at probo.com Sat Feb 11 01:23:52 2006 From: timr at probo.com (Tim Roberts) Date: Sat, 11 Feb 2006 06:23:52 GMT Subject: by reference References: <1139598954.259297.74290@o13g2000cwo.googlegroups.com> Message-ID: "dirvine" wrote: > >Thanks but I am a bit unsure as to what error I have made by posting >this question. I am not trying to be funny but can you give me a >pointer to the issue. The problem is that your question is quite unclear. I suggest that you post your exact Python code, with the results you get, and the results you expect. That's usually enough! -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mayyash at gmail.com Thu Feb 16 02:21:09 2006 From: mayyash at gmail.com (fileexit) Date: 15 Feb 2006 23:21:09 -0800 Subject: How to run shell commands within python Message-ID: <1140074469.258382.24620@f14g2000cwb.googlegroups.com> How can I execute shell commands from within python. Specifically, I am looking for something like the shell "cat". But this also made me wonder how to execute shell commands anyway, just if i needed to do that in the future. From malvert at telenet.be Tue Feb 7 11:21:08 2006 From: malvert at telenet.be (malv) Date: 7 Feb 2006 08:21:08 -0800 Subject: Dual Core outlook Message-ID: <1139329268.695421.191340@g47g2000cwa.googlegroups.com> Multiprocessing has been pushed into the field as the chip manufacturers can no longer deliver as they were used to for many years. The general public has been conditioned to believe that 1 + 1 = 2 but this is in fact not that simple. Although software manufacturers can with some effort adapt packages to exploit these dual core architectures, the same is not true for other development work were no large distribution of the application is to take place. What is the outlook for programming languages in general? Of course, multiprocessing has been used for many years but this always involved a much higher level of sophistication on the part of the designers. This point seems to be largely hidden from the public, ignorant and semi-ignorant, by the chip manufacturers. Will new languages see the light rendering the spreading of applications over many processors quasi transparent? What is the outlook for Python? Would Ironpython with .net do better? What about talk by the Java lobby that Java would be very much suited for taking advantage of dual-core? Is there any thruth to this? These are questions that many Python users like myself would like to find some answers for. One thing is clear. The old days will never come back and the processor multiplication is likely to increase. malv From gaz082 at gmail.com Thu Feb 23 08:40:45 2006 From: gaz082 at gmail.com (Gaz) Date: 23 Feb 2006 05:40:45 -0800 Subject: No (and a meaningless subject here too!) In-Reply-To: <4tjqv1dnpv80m1k412ecjmsncqgsv8quik@4ax.com> References: <1140534490.873612.64280@g47g2000cwa.googlegroups.com> <1140619645.303344.317890@g14g2000cwa.googlegroups.com> <1140629467.849254.285410@g43g2000cwa.googlegroups.com> <4tjqv1dnpv80m1k412ecjmsncqgsv8quik@4ax.com> Message-ID: <1140702045.812136.104980@g43g2000cwa.googlegroups.com> Aye, but i dont need to run an FTP daemon every time i want to upload an image to Imageshack or any other website. About the topic name, yes, it's meaningless and its a shame. I fucked it up when typing the title =P From deets at nospam.web.de Wed Feb 15 12:07:37 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 15 Feb 2006 18:07:37 +0100 Subject: Embedding a binary file in a python script References: <1140021879.698353.324230@o13g2000cwo.googlegroups.com> <1140022952.353744.323780@g47g2000cwa.googlegroups.com> Message-ID: <45h5gfF6nohpU1@uni-berlin.de> mrstephengross wrote: > Ok, this is a neat idea... The uu module deals with files though, not > strings. Is there a way in python to make a string act like a file > handle? (c)?StringIO Diez From grante at visi.com Thu Feb 9 10:27:02 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 09 Feb 2006 15:27:02 -0000 Subject: Best way of finding terminal width/height? References: <96nFf.43896$d5.199922@newsb.telia.net> <11uc3dohfitotc5@corp.supernews.com> <11udc0r2bq11042@corp.supernews.com> <43E719EE.3040401@gmail.com> <11ueq4nhn91qm91@corp.supernews.com> <43E8659D.6010101@gmail.com> <11uhcjj2p10mm0d@corp.supernews.com> <43E8D4DD.7040904@gmail.com> <11uhodjciifej02@corp.supernews.com> <11uk67a4ao5efe6@corp.supernews.com> Message-ID: <11umnq61kf9m5f3@corp.supernews.com> On 2006-02-09, Joel Hedlund wrote: >> It didn't insert an EOF, it just caused read() to return >> "prematurely". You should call read() again until it receives >> a _real_ EOF and returns ''. > > Copy that. Point taken. > >> There appear to be a couple problems with this description: >> >> 1) It says that read() in blocking mode without a size >> parameter it will read until EOF. This is not what happens >> when reading a terminal that receives SIGWINCH, so you're >> right: read() it isn't working as described. >> >> 2) It also says that it makes sense to continue to read a tty >> after you get an EOF. That's not true. Once you get an >> EOF on a tty, there's no point in reading it any more: >> you'll continue to get an EOF forever. I should qualify comment 2) with the disclaimer that that's how tty devices on Unix/Linux work -- I don't know about windows. > Should I post a bug about this? Sure. I was going to do that yesterday, but I realized that I didn't know how/where to do it. I assume there's a link somewhere at www.python.org, but I haven't had a chance to look yet. -- Grant Edwards grante Yow! I wish I was on a at Cincinnati street corner visi.com holding a clean dog! From markscala at gmail.com Sun Feb 19 15:27:39 2006 From: markscala at gmail.com (markscala at gmail.com) Date: 19 Feb 2006 12:27:39 -0800 Subject: Countdown Timer In-Reply-To: <1140378968.362832.250720@g47g2000cwa.googlegroups.com> References: <1140378968.362832.250720@g47g2000cwa.googlegroups.com> Message-ID: <1140380858.958124.68200@g47g2000cwa.googlegroups.com> take a look at the time module. From larry.bates at websafe.com Mon Feb 20 10:20:57 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 20 Feb 2006 09:20:57 -0600 Subject: Tab Character? In-Reply-To: <1140298494.225985.103510@g47g2000cwa.googlegroups.com> References: <1140298494.225985.103510@g47g2000cwa.googlegroups.com> Message-ID: tbonejo at gmail.com wrote: > How do I make a tab character in code to split a line read with tabs in > it? > > > Thanks. > > Tom > You should also take a look at csv module. If you are reading lines that contain tab delimeted data the csv module can make splitting very easy. -Larry Bates From duncan.booth at invalid.invalid Mon Feb 13 16:25:34 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Feb 2006 21:25:34 GMT Subject: trapping errors in function call syntax References: Message-ID: Fredrik Lundh wrote: > Avi Kak wrote: >> Suppose I write a function that I want to be called >> with ONLY keyword argumnts, how do I raise an >> exception should the function get called with >> what look like position-specfic arguments? > > here's one way to do it: > >>>> def func(*args, **kw): > ... def myrealfunc(a=1, b=2, c=3): > ... print a, b, c > ... if args: > ... raise TypeError("invalid call") > ... return myrealfunc(**kw) > ... > If you aren't particular about the message then you can do without the args argument and just define it with **kw: >>> def func(**kw): def myrealfunc(a=1, b=2, c=3): print a, b, c return myrealfunc(**kw) >>> func(1) Traceback (most recent call last): File "", line 1, in -toplevel- func(1) TypeError: func() takes exactly 0 arguments (1 given) >>> func(a=3) 3 2 3 >>> and if you are particular about the message perhaps submitting a patch to generate a more appropriate message would be a good idea. From onurb at xiludom.gro Wed Feb 8 04:31:17 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 08 Feb 2006 10:31:17 +0100 Subject: Too Many if Statements? In-Reply-To: <1139384021.290153.120470@g14g2000cwa.googlegroups.com> References: <1139330447.716190.247940@z14g2000cwz.googlegroups.com> <1139384021.290153.120470@g14g2000cwa.googlegroups.com> Message-ID: <43e9ba7e$0$31853$626a54ce@news.free.fr> Pierre Quentel wrote: > This is because Python has a hidden mechanism to detect programs > generated by Perl scripts, and make them crash with no explanation > KEYBOARD ! -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From richmoore44 at gmail.com Fri Feb 24 08:51:55 2006 From: richmoore44 at gmail.com (richmoore44 at gmail.com) Date: 24 Feb 2006 05:51:55 -0800 Subject: KPanelApplet using Python In-Reply-To: <1140785533.642904.263660@j33g2000cwa.googlegroups.com> References: <1140785533.642904.263660@j33g2000cwa.googlegroups.com> Message-ID: <1140789115.123838.210280@t39g2000cwt.googlegroups.com> Another way to do it is to use ksystraycmd which is included with your KDE. Some usage info is covered in my tutorial: http://xmelegance.org/customising-window-behaviour/html/customising-window-behaviour.html Rich. From george.sakkis at gmail.com Mon Feb 13 15:46:32 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 13 Feb 2006 12:46:32 -0800 Subject: Writing a Web Robot in Python References: <1139818483.962291.131570@g47g2000cwa.googlegroups.com> Message-ID: <1139863592.516855.75850@g44g2000cwa.googlegroups.com> You'd probably get more results by searching for "web crawlers" or "web spiders". You may start from here: http://harvestman.freezope.org/faq.html HTH, George From mfranklin1 at gatwick.westerngeco.slb.com Wed Feb 15 05:54:21 2006 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 15 Feb 2006 10:54:21 +0000 Subject: Downloading files using urllib in a for loop? In-Reply-To: <1139998630.164445.207110@f14g2000cwb.googlegroups.com> References: <1139996216.765104.119260@g14g2000cwa.googlegroups.com> <1139998630.164445.207110@f14g2000cwb.googlegroups.com> Message-ID: <43F3085D.9000604@gatwick.westerngeco.slb.com> justsee at gmail.com wrote: > Thanks - but have printed and verified they are valid paths and > filenames. One correction to the code I listed: > theurl = imagepath[:-8] > > For some reason the values aren't being passed through > urllib.urlretrieve properly but this makes no sense to me? > A working (for me!) example:- import urllib paths = ["http://www.python.org/index.html", ] for remotepath in paths: # keep only last 10 chars (index.html) # for local file name localpath = remotepath[-10:] print remotepath, localpath urllib.urlretrieve(remotepath, localpath) From aleaxit at yahoo.com Sat Feb 11 13:24:04 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 11 Feb 2006 10:24:04 -0800 Subject: ordered sets operations on lists.. References: <1139592166.993686.212000@f14g2000cwb.googlegroups.com> <1139599834.975607.77180@f14g2000cwb.googlegroups.com> Message-ID: <1halbdx.dd0p1l1obawfkN%aleaxit@yahoo.com> Raymond Hettinger wrote: ... > The intersection step is unnecessary, so the answer can be simplified a > bit: > > >>> filter(set(l2).__contains__, l1) > [5, 3] > >>> filter(set(l1).__contains__, l2) > [3, 5] ...and if one has time to waste, "setification" being only an optimization, it can also be removed: filter(l2.__contains__, l1) etc (very slow for long lists, of course). Personally, I'd always use (depending on guesses regarding lengths of lists) [x for x in l1 if x in l2] or the setified equivalent, of course. Alex From larry.bates at websafe.com Thu Feb 23 19:04:06 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 23 Feb 2006 18:04:06 -0600 Subject: How would you open this file? In-Reply-To: <1140735212.419265.219980@e56g2000cwe.googlegroups.com> References: <1140735212.419265.219980@e56g2000cwe.googlegroups.com> Message-ID: <43FE4D76.6090605@websafe.com> Bob wrote: > I want to open a file in a function and pass the file back to main so > another function can manipulate the file, something like this: > > # begin > def open_file() > filename=open(options.filename_input,'r') > return filename > > open_file() > print filename.read() > filename.close() > # end > > But this doesn't work... It appears that "open_file()" needs a > variable, but in order to pass a variable to "open_file()" I first need > a variable... but I would rather have the function send me "filename" > without creating it main. Is that possible? > > Is there a better way to have a function open a file and pass the file > back to main than what I am trying to do? Thanks! > Your function returned filename but in the main program you didn't have anywhere for it to be saved. fp=open_file() print fp.read() fp.close() Others have pointed out the filename is a bad choice for a variable name as it is a pointer to a file object. Most tutorials and a lot of standard library code use fp. -Larry Bates From deets at nospam.web.de Thu Feb 23 08:12:15 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 23 Feb 2006 14:12:15 +0100 Subject: Get Root access in Linux? References: <1140698762.654497.272490@o13g2000cwo.googlegroups.com> Message-ID: <465qp8F9hujdU1@uni-berlin.de> tbonejo at gmail.com wrote: > Does anyone know how to call for the root prompt before launching your > app? > Kinda like synaptic or the superuser file manager does? That is Windowmanager/Desktop dependand. For KDE, you can e.g. create links to applications that instruct the KDE to first acquire root privileges. As gnome and KDE try to become more cooperative especially in config-issues, you might be lucky and can use one mechanism for both. However, this is neither a python nor a general unix thing. For better answers, try and search the KDE/gnome resources. Diez From grahn+nntp at snipabacken.dyndns.org Sun Feb 5 12:33:54 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 5 Feb 2006 17:33:54 GMT Subject: Importing a class, please help... References: Message-ID: On Sun, 05 Feb 2006 17:16:38 +0100, Xavier Morel wrote: > anon wrote: >> Would somebody please drop me a hint, please? >> > Yeah, the definition of "JAR" is Java ARchive, why the hell would a > Python script be able to read a JAR in the first place You are rude to an obvious newbie here ... please keep in mind that today's stupid newbies are tomorrow's Python professionals. ... > If you want to use Java classes and modules in a Pythonic context, you > want Jython (http://www.jython.org/) not Python (http://www.python.org/) Maybe he /is/ running Jython and failed to explain that properly? If I understand things correctly, jar files are not tied to Java but to the java bytecode format -- which Java and Jython share. In either case, we'd need more information from the original poster. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From fredrik at pythonware.com Mon Feb 27 19:04:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 28 Feb 2006 01:04:05 +0100 Subject: str.count is slow References: <1141073696.107136.318600@j33g2000cwa.googlegroups.com> <1141083127.970403.147100@v46g2000cwv.googlegroups.com> Message-ID: Ben Cartwright wrote: > > On my machine, the output is: > > > > str: 0.29365715475 > > array: 0.448095498171 > > unicode: 0.0243757237303 > This tactic typically avoids most (sometimes all) of the calls to > memcmp. Other string search functions, including unicode.count, > unicode.index, and str.index, use this tactic, which is why you see > unicode.count performing better than str.count. it's about time that someone sat down and merged the string and unicode implementations into a single "stringlib" code base (see the SRE sources for an efficient way to do this in plain C). moving to (basic) C++ might also be a good idea (in 3.0, perhaps). is any- one still stuck with pure C89 these days ? From agriff at tin.it Sun Feb 26 17:29:08 2006 From: agriff at tin.it (Andrea Griffini) Date: 26 Feb 2006 14:29:08 -0800 Subject: How can I find the remainder when dividing 2 integers In-Reply-To: References: <1140984473.723258.70050@e56g2000cwe.googlegroups.com> Message-ID: <1140992948.579675.228000@t39g2000cwt.googlegroups.com> Writing a while loop with ++x to increment the index was the first mistake i made with python. "++x" unfortunately is valid, it's not a single operator but a double "unary plus" Andrea From cjw at sympatico.ca Mon Feb 20 15:11:23 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 20 Feb 2006 15:11:23 -0500 Subject: number ranges (was Re: Matlab page on scipy wiki) In-Reply-To: <43F97AA8.50005@REMOVEMEcyber.com.au> References: <1139945386.3346.38.camel@pc1.cole.uklinux.net> <43F8D881.5030804@sympatico.ca> <43F97AA8.50005@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > John Zenger wrote: > >> I strongly agree that Python should promote range or xrange to syntax. >> I favor [0..10] rather than [0:10] because 0..10 is inherently easier >> to understand. > > > "Inherently"? > > You mean people are born with an instinctive, unlearnt understanding of > ..? Or that our brains are constructed in such a way that .. is easier > to understand? > > For what it is worth, even after years of Python programming, I still > sometimes write this: > > for i in len(myList): > # Oops. > > I too prefer range() or xrange() over magic syntax, but I'm not > especially a lover of the range() idiom. How about this? With the > introduction of a single keyword, we could do this: > > for i in 2 to 5: > print i, > > which would print 2 3 4 5 This could be extended to: for i in 2 to 5 by 2: print i This would require another reserved word. Colin W. > > (I'm open to arguments that it should be more Pythonic and less > mathematical, and halt at 4.) > > A second keyword "downto" would allow easy backwards loops, and a third > "step" will absolutely kill any chance of Guido agreeing to this > whatsoever. > > > >> Haskell also has a good step notation. In Haskell: >> >> [1..10] means [1,2,3,4,5,6,7,8,9,10] >> [1,3..10] means [1,3,5,7,9] > > > I'm wary of that notation. It is too easy to make typos, what with , and > . next to each other, and the typos often will not raise an exception > but will simply give incorrect but puzzling behaviour. This isn't unique > to the proposed syntax (e.g. under Python today it isn't obvious whether > [0,3] is a typo for [0.3]) but it gives me pause. > > From claird at lairds.us Tue Feb 28 07:08:02 2006 From: claird at lairds.us (Cameron Laird) Date: Tue, 28 Feb 2006 12:08:02 GMT Subject: Python advocacy in scientific computation References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <45h1lqF6hks7U2@individual.net> Message-ID: In article <45h1lqF6hks7U2 at individual.net>, Georg Brandl wrote: >Michael Tobis wrote: >> Someone asked me to write a brief essay regarding the value-add >> proposition for Python in the Fortran community. Slightly modified to >> remove a few climatology-related specifics, here it is. > >Great text. Do you want to put it onto a Wiki page at wiki.python.org? . . . From sschwarzer at sschwarzer.net Wed Feb 8 17:07:00 2006 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 08 Feb 2006 23:07:00 +0100 Subject: Avoiding FTP server timeout for files based on sockets (long posting) Message-ID: <43EA6B84.3030508@sschwarzer.net> Hi all! For my FTP library module ftputil [1], some users have asked for a way to avoid server timeouts (FTP status code 421). But I haven't found out yet how I can do this in all cases. I try to explain the problem in more detail. The following is rather special and probably not so easy to understand, but I'll do my best. Please ask if you need more information. ftputil has an FTPHost class (defined in [2]), which can be instantiated like # very similar to ftplib.FTP host = ftputil.FTPHost(ftphost, user, password) You can use an FTPHost instance to get file(-like) objects from it: read_from_this_file = host.file("remote_file", "r") write_to_this_file = host.file("another_remote_file", "wb") In the background, each call of the FTPHost.file method opens another connection to the FTP server by using the login data from the FTPHost instantiation. The return value of each call is a _FTPFile object (defined in [3]) which wraps a file object returned by socket.makefile. My current FTPHost.keep_alive is roughly defined as # in FTPHost def keep_alive(self): # just prevent loss of the connection, so discard the result self.getcwd() # refresh also connections of associated file-like objects for host in self._children: # host._file is an _FTPFile object (see [3]) host._file.keep_alive() whereas in _FTPFile it's # in _FTPFile def keep_alive(self): if self._readmode: # read delegates to the file made from the data transfer # socket, made with socket.makefile (see [4]) self.read(0) else: # write delegates to the file made from the data transfer # socket, made with socket.makefile (see [4]) self.write("") self.flush() In fact, the read method call above on the data transfer channel keeps the connection open but the call to the write method can't avoid a timeout from the FTP server (however, I notice this only when I call _FTPFile.close(), so it seems that no data is sent until the _FTPFile.close call). An approach which seems feasible at first is to call pwd() on the FTP session (an ftplib.FTP class) on which the _FTPFile builds (similar to the FTPHost.getcwd() call above). Unfortunately, this doesn't work because as soon as the file is opened, a STOR command has been sent to the FTP server and it seems I can't send another FTP command until the data transfer is finished (by calling _FTPFile.close; see _FTPFile._open in [3] for details of making the connection). So to re-phrase my question: How can I keep the connection - for writing of remote files - from being closed by the FTP server without requiring the user of the ftputil library to explicitly send data with _FTPFile.write? Stefan [1] http://ftputil.sschwarzer.net/ [2] http://ftputil.sschwarzer.net/trac/browser/trunk/ftputil.py [3] http://ftputil.sschwarzer.net/trac/browser/trunk/ftp_file.py [4] http://docs.python.org/lib/socket-objects.html#l2h-2660 From xavier.morel at masklinn.net Sat Feb 11 19:10:08 2006 From: xavier.morel at masklinn.net (Xavier Morel) Date: Sun, 12 Feb 2006 01:10:08 +0100 Subject: appending to a list via properties In-Reply-To: <1hal7v6.1pa7ijfg3np46N%aleaxit@yahoo.com> References: <1139605443.823899.141260@g47g2000cwa.googlegroups.com> <1139670699.632590.148760@g14g2000cwa.googlegroups.com> <1hal7v6.1pa7ijfg3np46N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Carl Banks wrote: > ... >>> class better_list (list): >>> tail = property(None, list.append) >> This is an impressive, spiffy little class. > > Yes, nice use of property. > > Alex I don't know, I usually see people considering that properties are "cool" as long as they don't have side effects, as long as they're virtual members. The tail property doesn't behave like member data at all, the semantics are strange, counter-intuitive (tail would usually be the end of the list, either [-1] or [1:], in this case it's some magic position at the end of the list). And it has one hell of a side effect. From hancock at anansispaceworks.com Tue Feb 28 16:06:22 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 28 Feb 2006 15:06:22 -0600 Subject: PEP 354: Enumerations in Python In-Reply-To: References: <87accdplbj.fsf@rose.polar.local> <1141109451.570616.86140@p10g2000cwp.googlegroups.com> <440415A1.7070503@ofai.at> Message-ID: <20060228150622.69d01398@samwise.anansi> On Tue, 28 Feb 2006 14:26:49 -0500 "Terry Reedy" wrote: > "Stefan Rank" wrote in message > news:440415A1.7070503 at ofai.at... > > recent examples from this list: > > > > 2006-01-03: > > http://www.nabble.com/Re%3A-Regex-anomaly-p2179421.html > > 2006-02-20: > > http://www.nabble.com/Re%3A-Regular-expression-gone-mad-p3029028.html > > If the re flags were implemented as instances of object > instead of int, then misuse of them as int args would be > excepted. I don't know if such a change would otherwise > cause a problem. > > I wonder whether a subclass of object (EnumSet?) that > allowed for initialization with a better string > representation and that disabled order comparisons would > fill the bill for unordered enum. > > As Steven Bethard also noted, there seem to be a need for > two Enum subclasses: > EnumSet and EnumSeq. And one other distinction -- mutable versus immutable. A immutable enum is the usual use case, a mutable one is a "vocabulary" (i.e. an open set of symbols, which nevertheless requires controlled access). The key thing about symbols like enums etc is that they don't really represent anything (or that which they represent is inconvenient to bind to the symbols -- perhaps its even an abstract concept that has no programmatic representation beyond the enumerated value). One thing about an enumerated value is that it should know what enum it belongs to. For example, I'm currently working on a project that has the following rather unfortunate near-collision of symbols: sym.ABSTRACTS "scope of abstract nouns" in SCOPE vocabulary sym.ABSTR "definiteness of abstract noun" in ARTICLE enum sym.ABST "number of noun which has no count because abstract (not mass)" NUMBER enum It's quite useful that I can ask "sym.ABST" which one of the above domains it's in: >>> sym.ABST.domain NUMBER or even better: >>> sym.ABST Which makes the enumeration values somewhat self-documenting. I'm currently trying to figure out how best to make this instead show (e.g.): >>> sym.ABST I can of course, also use this to catch errors by checking that the pluralization function in my locale module has been passed a NUMBER or an explicit int, instead of say, a SCOPE, by accident. Another feature here is that all of these symbols, though also defined within their domain collections is also made into an attribute of the sym object (which is a "trivial class" or "convenience namespace"). I also raise an error if any domain tries to overwrite a symbol in sym, so I can avoid accidental collisions. I'm still tinkering with this, and the above is from memory, but I do have it working on another machine. I'm currently subclassing from dict, not set, though I'm unsure if this is really wise (but I'm more familiar with dict, and I'm currently making use of the mapping internally, though I'm not sure I really need to). I'm not sure this would be a smart way to do this in another application, but it looks promising for this one (which is a kind of artificial locale-neutral language representation). I'm not sure that the enum described in the PEP would be as useful to me as this. So I'm -0 on it becoming a built-in, though I'm +0 on it becoming a module (it's not that hard to type "from enum import Enum"). But I'm not sure it's the "best" enum, or even that "one size fits all" with enums (though having fewer implementations might improve clarity if they are really equivalent). Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From deusfaber at gmail.com Sun Feb 12 15:58:00 2006 From: deusfaber at gmail.com (dfaber) Date: 12 Feb 2006 12:58:00 -0800 Subject: python and webcam In-Reply-To: References: <1139773485.698970.195320@z14g2000cwz.googlegroups.com> Message-ID: <1139777880.787466.210640@f14g2000cwb.googlegroups.com> It is a Win32 Python Extension. I am looking for something that work on Linux. From michaeltaft at gmail.com Sun Feb 12 04:06:37 2006 From: michaeltaft at gmail.com (mwt) Date: 12 Feb 2006 01:06:37 -0800 Subject: Clearing the screen In-Reply-To: <1139731250.332185.278280@o13g2000cwo.googlegroups.com> References: <1139688262.046667.296940@g14g2000cwa.googlegroups.com> <1139725568.890659.253770@f14g2000cwb.googlegroups.com> <1139731250.332185.278280@o13g2000cwo.googlegroups.com> Message-ID: <1139735197.228877.71770@z14g2000cwz.googlegroups.com> Arrgghh... Is there any way to edit posts on this thing? The os.system("clear") doesn't work at all in a module. From deets at nospam.web.de Fri Feb 24 04:49:42 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 24 Feb 2006 10:49:42 +0100 Subject: PYTHONPATH? References: Message-ID: <46839nF9pi1rU1@uni-berlin.de> Dr. Pastor wrote: > Several Documents about Python > refer to PYTHONPATH. > I could not find such variable. > (Python 2.4.2, IDLE 1.1.2, Windows XP) > How should/could I nominate a Directory to be > the local Directory? > Thanks for any guidance. It's a so called environment-variable. You can set these in some obscure windows dialog in the system-preferences on a per-system or per-user base. Or you start using cygwin (lots of good other reasons for that), and do export PYTHONPATH=/whatever Diez From julius.lucks at gmail.com Sun Feb 19 21:08:18 2006 From: julius.lucks at gmail.com (Julius Lucks) Date: 19 Feb 2006 18:08:18 -0800 Subject: Eric3 Help/Tutorial Message-ID: <1140401298.746089.47010@g43g2000cwa.googlegroups.com> Does anyone know of Help docs/tutorials that explain Eric3's plethora of features? http://www.die-offenbachs.de/detlev/eric3.html Thanks, Julius From fuzzyman at gmail.com Fri Feb 3 06:28:04 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 3 Feb 2006 03:28:04 -0800 Subject: would it be feasable to write python DJing software In-Reply-To: References: <1138925819.465108.181760@o13g2000cwo.googlegroups.com> <1138962918.427815.70300@g14g2000cwa.googlegroups.com> Message-ID: <1138966084.385205.254410@g14g2000cwa.googlegroups.com> Ivan Voras wrote: > simonwittber at gmail.com wrote: > > > Actually, manipulating and mixing audio samples can be both fast and > > elegant, in Python, if you use Numeric or a similar library. > > ... at which point you're actually doing it in C, not pure python... :) Only in as much as doing anything in Python is *really* doing it in C, surely ? Come to that, you're **really** doing it in machine code... All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From mrstephengross at hotmail.com Fri Feb 17 11:30:45 2006 From: mrstephengross at hotmail.com (mrstephengross) Date: 17 Feb 2006 08:30:45 -0800 Subject: Simple question about freeze Message-ID: <1140193845.660117.302750@g43g2000cwa.googlegroups.com> I'm working with the freeze utility, and I'm trying to learn the basics. For the most part, I think I understand how it works. I have a question about modules, though. I want to make sure that my native executable is entirely standalone. That is, it should have no dynamic linking. I've read through a number of posts on the subject, and think I get it. In order to make this work, I need to do two things: (1) Recompile libpythonXXX.a so that the required modules are indeed compiled into the archive. (2) Modify the freeze-generated Makefile to force gcc to use static linking and to use my custom-built libpythonXXX.a in linking together the native executable. My question is: is it sufficient to carry out the above steps? Freeze is designed to use the version of python installed on the host system, *not* a custom build in a different directory. If freeze looks to the system's default installation, but I've modified the makefile to use my custom-built libpython.a, will that cause problems? My sense is that it will not, but I want to make sure I think things through. Any thoughts? Thanks, --Steve (mrstephengross at hotmail.com) From Nainto at gmail.com Wed Feb 22 19:34:47 2006 From: Nainto at gmail.com (Nainto) Date: 22 Feb 2006 16:34:47 -0800 Subject: Cross-Platform Bonjour Module In-Reply-To: <1140652897.395005.244170@z14g2000cwz.googlegroups.com> References: <1140652897.395005.244170@z14g2000cwz.googlegroups.com> Message-ID: <1140654887.769340.85180@f14g2000cwb.googlegroups.com> Take a look at: http://lists.apple.com/archives/bonjour-dev/2005/Jun/msg00018.html From vania.smirk at gmail.com Mon Feb 13 16:27:39 2006 From: vania.smirk at gmail.com (VSmirk) Date: 13 Feb 2006 13:27:39 -0800 Subject: hard disk activity In-Reply-To: <7xbqxb0xo0.fsf@ruckus.brouhaha.com> References: <1139850420.902979.71620@o13g2000cwo.googlegroups.com> <1139857505.376840.37440@g43g2000cwa.googlegroups.com> <1139859890.407497.124870@o13g2000cwo.googlegroups.com> <1139863885.755813.324450@g47g2000cwa.googlegroups.com> <7xfymn0yda.fsf@ruckus.brouhaha.com> <1139864840.300396.170070@o13g2000cwo.googlegroups.com> <7xbqxb0xo0.fsf@ruckus.brouhaha.com> Message-ID: <1139866059.604198.245040@g44g2000cwa.googlegroups.com> Thanks for the head's up. I was so giddy with the simplicity of the solution, I stopped trying to poke holes in it. I agree with your philosophy of not "reinventing the wheel", but I did notice two things: First, the link you provided claims in the features section that rsync if for *nix systems, so I am assuming I'll need a port of it for windows systems; however looking at a Python rsync module I found, it looks like it's just doing file-copy (which I have already solved). So I'm wondering if you know off-hand which windows port does this checksum validation you outlined. From lycka at carmen.se Tue Feb 14 09:50:49 2006 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 14 Feb 2006 15:50:49 +0100 Subject: Rethinking the Python tutorial In-Reply-To: References: Message-ID: A.M. Kuchling wrote: > On Mon, 13 Feb 2006 11:03:55 -0500, > Steve Holden wrote: >>What we are talking about here is a Python Language Users' Guide. > > I actually started on such a document over the holidays, but have only > described about 3 or 4 statements at this point. Great! I hope you'll find the time to make this into something useful. I don't know how easy it is to make such a thing into a collaborative effort. Either way, I think some kind of champion is needed... I hope we'll see some kind of tools for on-line collaboration for python.org soon, whether it's something wiki-like or some other way to add comments to the web pages. From nogradi at gmail.com Thu Feb 9 16:42:16 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 9 Feb 2006 22:42:16 +0100 Subject: pythonic exec* spawn* Message-ID: <5f56302b0602091342m32dfc9aey65399003b229178c@mail.gmail.com> Is it possible to pass a python object to a python program as argument? In my program I would like to start executing an other python program and don't wait until that finishes, only launch it and keep running the original program. The obvious way I can think of it is using the exec* or spawn* function families. However, these are generic functions to start any external program and I was wondering if there was a special way to start a python program (as opposed to an arbitrary program), especially because I would like to pass data to this other program in the form of python objects. While the original program is running it creates all sorts of data in a nice pythonic way, for example as a class instance with lot of member data, and then I wouldn't want to convert all of this into command line arguments because that would create a huge list. I would like to pass the whole object at once to the second python program which should start doing its thing with it while the original program should keep running. I was looking around for threading and forking but couldn't come up with a clear solution. From siona at chiark.greenend.org.uk Wed Feb 8 09:49:48 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 08 Feb 2006 14:49:48 +0000 (GMT) Subject: 450 Pound Library Program References: <1139351498.090768.82270@o13g2000cwo.googlegroups.com> Message-ID: mwt wrote: > while len(self.stacks) == 0: To (kind of) repeat myself, the idiomatic Python would be: while not self.stacks: An empty list is considered to be false, hence testing the list itself is the same as testing len(l) > 0 . As someone else has noticed, you're using len() an awful lot when you don't need to. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From xavier.morel at masklinn.net Thu Feb 16 20:32:53 2006 From: xavier.morel at masklinn.net (Xavier Morel) Date: Fri, 17 Feb 2006 02:32:53 +0100 Subject: define loop statement? In-Reply-To: References: Message-ID: Rene Pijlman wrote: > David Isaac: >> I would like to be able to define a loop statement >> (nevermind why) so that I can write something like >> >> loop 10: >> do_something >> >> instead of >> >> for i in range(10): >> do_something >> >> Possible? If so, how? > > Yes. By implementing a compiler or an interpreter for your programming > language. Or a preprocessor that converts your language to Python, or some > other suitable intermediate language. Or a programmer, that converts your > pseudocode and some coffee to the desired algorithm :-) > Or by hacking through the Python source and creating his own "somehow pythonish but absolutely not python" language From larry.bates at websafe.com Tue Feb 21 12:42:24 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 21 Feb 2006 11:42:24 -0600 Subject: fast text processing In-Reply-To: References: Message-ID: <43FB5100.9000906@websafe.com> Alexis Gallagher wrote: > Steve, > > First, many thanks! > > Steve Holden wrote: >> Alexis Gallagher wrote: >>> >>> filehandle = open("data",'r',buffering=1000) >> >> This buffer size seems, shall we say, unadventurous? It's likely to >> slow things down considerably, since the filesystem is probably going >> to naturally wnt to use a rather larger value. I'd suggest a 64k minumum. > > Good to know. I should have dug into the docs deeper. Somehow I thought > it listed lines not bytes. > >>> for currentLine in filehandle.readlines(): >>> >> Note that this is going to read the whole file in to (virtual) memory >> before entering the loop. I somehow suspect you'd rather avoid this if >> you could. I further suspect your testing has been with smaller files >> than 80GB ;-). You might want to consider >> > > Oops! Thanks again. I thought that readlines() was the generator form, > based on the docstring comments about the deprecation of xreadlines(). > >>> So on every iteration I'm processing mutable strings -- this seems >>> wrong. What's the best way to speed this up? Can I switch to some >>> fast byte-oriented immutable string library? Are there optimizing >>> compilers? Are there better ways to prep the file handle? >>> >> I'm sorry but I am not sure where the mutable strings come in. Python >> strings are immutable anyway. Well-known for it. > > I misspoke. I think was mixing this up with the issue of object-creation > overhead for all of the string handling in general. Is this a bottleneck > to string processing in python, or is this a hangover from my Java days? > I would have thought that dumping the standard string processing > libraries in favor of byte manipulation would have been one of the > biggest wins. > >> Of course you leave us in the dark about the nature of >> table.markEquivalent as well. > > markEquivalent() implements union-join (aka, uptrees) to generate > equivalence classes. Optimising that was going to be my next task > > I feel a bit silly for missing the double-processing of everything. > Thanks for pointing that out. And I will check out the biopython package. > > I'm still curious if optimizing compilers are worth examining. For > instance, I saw Pyrex and Pysco mentioned on earlier threads. I'm > guessing that both this tokenizing and the uptree implementations sound > like good candidates for one of those tools, once I shake out these > algorithmic problems. > > > alexis When your problem is I/O bound there is almost nothing that can be done to speed it up without some sort of refactoring of the input data itself. Python reads bytes off a hard drive just as fast as any compiled language. A good test is to copy the file and measure the time. You can't make your program run any faster than a copy of the file itself without making hardware changes (e.g. RAID arrays, etc.). You might also want to take a look at csv module. Reading lines and splitting on delimeters is almost always handled well by csv. -Larry Bates From rarelychecked at gmail.com Wed Feb 1 11:07:38 2006 From: rarelychecked at gmail.com (Don't Code Faster Than You Can See) Date: Wed, 01 Feb 2006 16:07:38 +0000 Subject: urllib2 - My POST Request just isn't working right In-Reply-To: References: Message-ID: <8a-dnQmY1NJTQX3eRVny0A@mailbox.co.uk> (blogger.com gives the same error if you don't .strip() your password before using it to connect) i noticed one spelling mistake here: > headers = { 'Referer' : 'YourCompany', 'Referrer' could it be that simple? From harlinseritt at yahoo.com Tue Feb 7 08:01:19 2006 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 7 Feb 2006 05:01:19 -0800 Subject: python In-Reply-To: References: <20060206222757.3277.qmail@web25701.mail.ukl.yahoo.com> Message-ID: <1139317279.772951.19440@g47g2000cwa.googlegroups.com> Hi Simon, Honestly, any type of application can be programmed with Python. Python is extremely "wrappable" as it can be wrapped around virtually any type of platform that exists. You can create GUI, system, and web apps easily. The main niche that Python holds is the fact it exists for the benefit of the programmer as opposed to application performance. Maybe 6-8 years ago this may have not been beneficial for an application. Now, however, inexpensive, faster and higher-performance hardware has eliminated application speed and occasional memory leaks as a non-factor (except perhaps for extreme data crunching and video gaming -- which must squeeze out as much performance as it can from the hardware) when it comes to deciding what platform one should use. Python will help you be more productive as apps will generally be three times faster to write as opposed to even a language that was once thought to be easy, Java. A word of warning: once you've gotten used to writing Python code, you will never want to write using any other programming language. From lee at example.com Wed Feb 1 16:41:35 2006 From: lee at example.com (Lee Harr) Date: Wed, 01 Feb 2006 21:41:35 GMT Subject: import datetime References: <1138739342.436000.11290@g44g2000cwa.googlegroups.com> <1138807764.118105.218190@g44g2000cwa.googlegroups.com> Message-ID: >> I did look at the sys.path but the issue is that I dont see a module >> name datetime anywhere. Only datetime thing that is there is in include >> directory and it is datetime.h, which I think is for C interface. I >> have a python installed on my Windows desktop and it is working fine >> there. Where is the datetime module stored? Does any body know? > > on windows, it's linked to the interpreter. > >>>> import datetime >>>> datetime > > >>>> import sys >>>> "datetime" in sys.builtin_module_names > True > > on other platforms, it may be linked to the interpreter or placed in > a shared library: > >>>> import datetime >>>> datetime > > So maybe there is just a problem with the way Python was built. Is that from an "official" HP-UX package? You could ask on an HP-UX list. Alternatively, you could try compiling Python yourself. From johnjsal at NOSPAMgmail.com Sat Feb 11 01:02:46 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 11 Feb 2006 01:02:46 -0500 Subject: installing python on a server? In-Reply-To: <1139610715.439681.185510@g44g2000cwa.googlegroups.com> References: <1139610715.439681.185510@g44g2000cwa.googlegroups.com> Message-ID: Renato wrote: > You mentioned using python for web apps: with which framework? > (TurboGears, CherryPy, Subway, Django, whatever) Or only for cgi? > > With which web server? (Apache, Twisted, Zope, etc.) > > On which linux platform? (Slackware, Debian, Fedora/RedHat, Suse, etc) > > I think you'll have to think about other questions before. > > On systems with package management (pretty much all of them, except > Slack) install is a matter of a few commands. And you can automate it, > obviously. > Yikes, that's all the stuff I don't know. Maybe this is over my head right now. From dwahler at gmail.com Wed Feb 1 11:41:06 2006 From: dwahler at gmail.com (David Wahler) Date: 1 Feb 2006 08:41:06 -0800 Subject: urllib2 - My POST Request just isn't working right In-Reply-To: References: <312cfe2b0602010753uc363a85wb3f87cf2677993a2@mail.gmail.com> <1138810726.547315.82890@f14g2000cwb.googlegroups.com> Message-ID: <1138812066.711274.15360@g43g2000cwa.googlegroups.com> Gregory Pi?ero wrote: > Ok, I tried the changes you guys suggested but same error still: > 1. Corrected spelling of referrer. > 2. Don't specify host. > > Here is what they say my request should look like: > ------------------------------------------------------------------------- > POST /GatewayDC HTTP/1.0 > Referer: YourCompanyNameGoesHere > Host: SSLserver.fedex.com > Accept: image/gif, image/jpeg, image/pjpeg, text/plain, text/html, */* > Content-Type: image/gif Content-length: %d > > Your FedEx Transaction > ------------------------------------------------------------------------- > Note that Host here is ficticious. My host should be correct. And > they have referrer mispelled here so who knows which to use! > "Referer" is the correct header name. The HTTP specification spells it incorrectly, so "Referrer" is the proper English spelling but invalid in the context of HTTP. This is for historical reasons, and is not likely to change. > Here are some suspicions I have: > > 1 . One thing that is weird is that the data part just says "Your > FedEx Transaction". I know I put the XML here, but I also notice that > urllib2 is putting this as: > > request= > Can I have my xml placed here without that something= part? That > don't specify what parameter name I should use. Are you sure it's supposed to be URL-encoded? Try just sending the XML data directly as part of the request. -- David From pprobert at wisc.edu Thu Feb 23 16:26:36 2006 From: pprobert at wisc.edu (Paul Probert) Date: Thu, 23 Feb 2006 15:26:36 -0600 Subject: time.sleep(1) sometimes runs for 200 seconds under windows Message-ID: Hi, My app runs in a loop looking for changes in a database, and like a good boy I call time.sleep(1) inside the loop. Unfortunately this sometimes runs for 200 seconds or so, presumably while my OS is calling Bill Gates to tell him what I've been doing. This happens under NT4, W2k, and XP. What do people do to fix this? Thanks! Paul Probert University of Wisconsin From kent at kentsjohnson.com Wed Feb 8 22:18:48 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 08 Feb 2006 22:18:48 -0500 Subject: Jython inherit from Java class In-Reply-To: <1139344211.725580.263660@g47g2000cwa.googlegroups.com> References: <1139344211.725580.263660@g47g2000cwa.googlegroups.com> Message-ID: <43eab05b_2@newspeer2.tds.net> Mark Fink wrote: > I wrote a Jython class that inherits from a Java class and (thats the > plan) overrides one method. Everything should stay the same. > > If I run this nothing happens whereas if I run the Java class it says: > usage: java fit.FitServer [-v] host port socketTicket > -v verbose It sounds like the Java class has a main() function. When you run it as an application, the Java runtime looks for the main() function in the class you tell it to run. Even in Java, this behaviour is not preserved by inheritance, a subclass has to have its own main() to be executable. Jython (and Python) works a little differently, your module is executed from start to finish when you run it. Any statements that are not inside a class or function definition will be executed. (Actually the class and function definitions are executed to, but not in the same way...) You might get the behaviour you want if you put the line import sys fit.FitServer.main(sys.argv) at the end of your file. This will run the main() function of the Java class. Kent > > I think this is because I do not understand the jython mechanism for > inheritance (yet). > > JyFitServer.py: > =========== > import fit.FitServer > import fitnesse.components.FitProtocol > from fit.Parse import Parse > from fit.Fixture import Fixture > > # Inherit from original Java FitServer Implementation by Robert C. > Martin and Micah D. Martin > class FitServer(fit.FitServer): > # call constructor of superclass > def __init__(self, host, port, verbose): > FitServer.__init__(self, host, port, verbose) > > # override process method > def process(self): > self.fixture.listener = self.fixtureListener > print "hello, I am JyFitServer!" > try: > size = FitProtocol.readSize(self.socketReader) > if size > 0: > try: > document = > FitProtocol.readDocument(self.socketReader, size) > tables = Parse(document) > fixture = Fixture() > fixture.listener = self.fixtureListener; > fixture.doTables(tables) > self.counts.tally(self.fixture.counts) > except FitParseException, e: > self.exception(e) > except Exception, e: > self.exception(e) > > > > Please help, > Mark Fink > From lycka at carmen.se Sun Feb 5 07:28:39 2006 From: lycka at carmen.se (Magnus Lycka) Date: Sun, 05 Feb 2006 13:28:39 +0100 Subject: Python vs C for a mail server In-Reply-To: <87wtgar8vp.fsf@pobox.com> References: <1138728303.669646.36940@g49g2000cwa.googlegroups.com> <1138805854.533303.279610@g49g2000cwa.googlegroups.com> <1138819666.521465.108000@o13g2000cwo.googlegroups.com> <87wtgar8vp.fsf@pobox.com> Message-ID: John J. Lee wrote: > I guess the same is true of Python in some respects: it's still > incrementally changing (more than C++, I guess), and isn't all that > much younger than C++ (around 15 and 23 years old respectively). But C++ is almost entirely backwards compatible with C, which adds another dozen years or so... From michaeltaft at gmail.com Wed Feb 15 14:45:10 2006 From: michaeltaft at gmail.com (mwt) Date: 15 Feb 2006 11:45:10 -0800 Subject: Clearing the screen In-Reply-To: References: <1139688262.046667.296940@g14g2000cwa.googlegroups.com> <1139735197.228877.71770@z14g2000cwz.googlegroups.com> <1139953968.011216.210560@g43g2000cwa.googlegroups.com> Message-ID: <1140032710.313981.3940@g47g2000cwa.googlegroups.com> You know, for now, I just would like it to work in a standard Gnome terminal (my version is 2.12.0). From kent at kentsjohnson.com Mon Feb 6 08:23:13 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 06 Feb 2006 08:23:13 -0500 Subject: Learning Python In-Reply-To: <1139159843.488988.279770@g43g2000cwa.googlegroups.com> References: <1139154754.099716.71300@f14g2000cwb.googlegroups.com> <1139156577.897100.69140@g43g2000cwa.googlegroups.com> <1139158796.288778.244000@z14g2000cwz.googlegroups.com> <1139159843.488988.279770@g43g2000cwa.googlegroups.com> Message-ID: <43e7498f$1_2@newspeer2.tds.net> Byte wrote: > Yes, sorry, didnt realise diffrence between int and input. Since i'm > such an idiot at this, any links to sites for people who need an > unessicerily gentle learning curve? The Python tutor mailing list is for newbies: http://mail.python.org/mailman/listinfo/tutor Many beginners' tutorials listed here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Kent From stewart.midwinter at gmail.com Sat Feb 11 21:02:03 2006 From: stewart.midwinter at gmail.com (stewart.midwinter at gmail.com) Date: 11 Feb 2006 18:02:03 -0800 Subject: installing python on a server? In-Reply-To: References: <1139610715.439681.185510@g44g2000cwa.googlegroups.com> <21bsu1dpb4nabbq04fdpubkidj23dh379j@4ax.com> Message-ID: <1139706297.538841.5990@z14g2000cwz.googlegroups.com> I'm wondering whether you couldnn't use MovPy for this purpose - a situation where you don't have root access. You can install the whole MovPy package in your home directory; it provides a self-contained environment. At the moment I think it only runs on Windows boxen, but that may change. From http Sat Feb 25 18:00:37 2006 From: http (Paul Rubin) Date: 25 Feb 2006 15:00:37 -0800 Subject: Is Python a Zen language? References: <1140876556.080086.252390@e56g2000cwe.googlegroups.com> <1140878147.541074.233540@i40g2000cwc.googlegroups.com> <1140879469.853398.322850@i40g2000cwc.googlegroups.com> <1140903119.580735.108440@e56g2000cwe.googlegroups.com> Message-ID: <7xoe0vhwmi.fsf@ruckus.brouhaha.com> "Kay Schluehr" writes: > I have at times the impression that many people who talk about Zen > philosophy confuse it with some home brewn mixture of platonism with > its transgressive move towards the true reality, a stoic hedonism of > contemplation and the taoistic being-in-doing. Zen on the other side is > more radical: if you erase yourself there is no-one "who" is in the > flow but chances are that you and the computer over there are the same > thing. QOTW or something. From steve at holdenweb.com Wed Feb 22 00:32:00 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 22 Feb 2006 00:32:00 -0500 Subject: a little more help with python server-side scripting In-Reply-To: References: <59edncmGm6g2LmbeRVn-pw@rcn.net> Message-ID: John Salerno wrote: > Steve Holden wrote: > > >>Fortunately they've given you the information you need to run CGI >>scripts. Try installing this script in your cgi-bin directory as test.py >>(you may have to set it executable): > > > Thank you! I desperately needed to test it, and that seemed to work. I > didn't have to make it executable though. I wonder why? Probably because the cgi-bin directory is specially marked to contain executables. If you drop the script in another directory you will almost certainly just see the source of the script. Making it executable *might* cause it to run, but that would depend on exactly how your server is configured. Certainly my sites all have a line like ScriptAlias /cgi-bin/ "c:/apache/cgi-bin/" in the httpd.conf file. ScriptAlias tells Apache that the files in the directory are scripts. The first argument is the address in web-space, the second the address on disk. You'll find you can affect *some* configuration items by creating files called .htaccess in your web content directories, but that's a ways down the road yet. If the script ran, you will now know waht version of Apaceh you're running with! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From LittlePython at lost.com Thu Feb 16 21:24:52 2006 From: LittlePython at lost.com (LittlePython) Date: Fri, 17 Feb 2006 02:24:52 GMT Subject: Seaching Active Directory via ADO References: <1140138661.484502.86380@f14g2000cwb.googlegroups.com> <56aJf.78250$_D1.4370@trnddc03> <1140142239_1425@sp6iad.superfeed.net> Message-ID: I notice there is no adodb.command. This is not required? Thx for the example! "Roger Upole" wrote in message news:1140142239_1425 at sp6iad.superfeed.net... > Here's a short example that uses ADO to search for a > user by wildcard. > > import win32com.client > c = win32com.client.Dispatch("ADODB.Connection") > c.Open("Provider=ADSDSOObject") > > rs,rc=c.Execute(""" > SELECT adspath, title, name > From 'LDAP://DC=yourdomain, DC=COM' > where objectClass='user' and name='Roger*' > """) > > while not rs.EOF: > for f in rs.Fields: > print f.Name, f.Value > rs.MoveNext() > > hth > Roger > > "LittlePython" wrote in message > news:56aJf.78250$_D1.4370 at trnddc03... > > Thanks but I was looking more for ADO com object than ADSI or ldap. > > For some strange reason it is very hard to locate any working scripts that > > use ADO to connect and search AD. Is there an issue with ADO and python > > when connecting to AD? > > I have try to build one myself with no luck. I think my problem is with > > adodb.command calls. > > > > Thanks for your response. > > > > "alex23" wrote in message > > news:1140138661.484502.86380 at f14g2000cwb.googlegroups.com... > > > Heya, > > > > > > There are a couple of examples on the O'Reilly site. These two are > > > taken from 'Active Directory Cookbook', the first uses a COM object > > > while the second uses a native LDAP module: > > > > > > > > > http://www.rallenhome.com/books/adcookbook/src/18.6-rootdse_python_com.py.tx > > t > > > > > > http://www.rallenhome.com/books/adcookbook/src/18.6-rootdse_python_ldap.py.t > > xt > > > > > > This might give you a start. > > > > > > - alex23 > > > > > > > > > > > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- > http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups > ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From durumdara at gmail.com Mon Feb 27 08:13:39 2006 From: durumdara at gmail.com (Durumdara) Date: Mon, 27 Feb 2006 14:13:39 +0100 Subject: Py2Exe - how to set BDist (Build) directory ? Message-ID: <4402FB03.9090508@gmail.com> Hi ! I want to set the temp. build directory that it is does not placed in python source directory. I want to set this: \bin\ compiled version \src\ python source \tmp\ temp build dir How to I do it ? Thanx for help: dd From michael at elehack.net Tue Feb 28 08:33:47 2006 From: michael at elehack.net (Michael Ekstrand) Date: Tue, 28 Feb 2006 07:33:47 -0600 Subject: HTML/DOM parser In-Reply-To: <1141115591.120432.221900@t39g2000cwt.googlegroups.com> References: <1141115591.120432.221900@t39g2000cwt.googlegroups.com> Message-ID: <20060228073347.b90d14a4.michael@elehack.net> On 28 Feb 2006 00:33:11 -0800 "Xah Lee" wrote: > is there a module that lets me parse validated html files and store it > as a tree? BeautifulSoup will parse valid HTML (not just XHTML), and also crummy HTML while it's at it. And generates a tree structure. Warning: I haven't actually used this myself, I've just looked at it. http://www.crummy.com/software/BeautifulSoup/ - Michael -- mouse, n: a device for pointing at the xterm in which you want to type. -- Fortune From ian at excess.org Wed Feb 8 15:10:26 2006 From: ian at excess.org (Ian Ward) Date: Wed, 08 Feb 2006 15:10:26 -0500 Subject: Replacing curses (Was: Re: Problem with curses and UTF-8) In-Reply-To: <11ukf0ci8d6ac64@corp.supernews.com> References: <43E9234B.6030108@v.loewis.de> <11uk55h47lruk18@corp.supernews.com> <11ukf0ci8d6ac64@corp.supernews.com> Message-ID: <43EA5032.3080307@excess.org> Grant Edwards wrote: > Depending on what you're tring to do, slang might be an option, I've looked at newt and snack, but all I really need is: - a way to position the cursor at (0,0) - a way to hide and show the cursor - a way to detect when the terminal is resized - a way to query the terminal size Ian Ward From reply.in.the.newsgroup at my.address.is.invalid Tue Feb 21 12:41:14 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 21 Feb 2006 18:41:14 +0100 Subject: Zope/Plone - Is it the right solution? References: <1140532818.195281.316580@g44g2000cwa.googlegroups.com> Message-ID: <6sjmv117tmgs5sp35k3002882gkisc2lg0@4ax.com> kbperry: >1) Is Zope/Plone overkill for this type of project? No, Plone is an excellent CMS for your purpose. >2) Why use Plone vs. straight up Zope? Plone is an out-of-the-box CMS for non-technical editors, Zope is the underlying infrastructure for developers. >3) Is there a way to get over the steep learning curves (that I have >read about)? There is a steep learning curve when you need to develop custom content types, application code, integrate other databases and so on. But when all you want is a CMS for a community-type website, Plone is fine. I recommend this book, it probably contains all you need to know: http://plone.org/documentation/manual/definitive-guide (it's available as web pages and on dead tree as well) -- Ren? Pijlman From tuvas21 at gmail.com Tue Feb 21 15:48:06 2006 From: tuvas21 at gmail.com (Tuvas) Date: 21 Feb 2006 12:48:06 -0800 Subject: Tkinter Event Binding Double-click Message-ID: <1140554886.169328.265060@f14g2000cwb.googlegroups.com> I am trying to execute a function with a tkinter event binding double click. With 2 mouse clicks done quickly, the function should happen, otherwise, it should not. However, I am noticing that the time that the event binding of a double-click is quite long, on the order of a second or so. I am double-clicking twice in a second, and the function is being executed 3 times, and not just 2. I want to know, is this controlled by the OS, or by Tkinter? And if by tkinter, is there a way to change it, and how so? Thanks! From enleverlesX.XmcX at XmclaveauX.com Sat Feb 25 04:51:00 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Sat, 25 Feb 2006 10:51:00 +0100 Subject: PyUNO with different Python References: <43fcad29$0$29099$5fc30a8@news.tiscali.it> <43fcc038$0$19689$8fcfb975@news.wanadoo.fr> <43fd77cf$0$29110$5fc30a8@news.tiscali.it> Message-ID: <440061a4$0$29193$8fcfb975@news.wanadoo.fr> hmmmm... I can run OK "hello_world.py". But only with Python-core-2.3 Python 2.4 don't run (conflict-version, or windows error). And, it's not possible to install extensions (like PyWin) to Python-core-2.3 (this destroy the same extensions in my "normal" Python 2.4) I had let down these aspects of OOo. *sorry for my bad english* MCI From user at example.net Sat Feb 4 14:29:23 2006 From: user at example.net (pyluke) Date: Sat, 04 Feb 2006 19:29:23 GMT Subject: re.search slashes In-Reply-To: References: Message-ID: pyluke wrote: > I'm parsing LaTeX document and want to find lines with equations blocked > by "\[" and "\]", but not other instances of "\[" like "a & b & c \\[5pt]" > > so, in short, I was to match "\[" but not "\\]" > > to add to this, I also don't want lines that start with comments. > > > I've tried: > check_eq = re.compile('(?!\%\s*)\\\\\[') > check_eq.search(line) > > this works in finding the "\[" but also the "\\[" > > so I would think this would work > check_eq = re.compile('(?![\%\s*\\\\])\\\\\[') > check_eq.search(line) > > but it doesn't. Any tips? Alright, this seems to work: re.compile('(? Message-ID: "Tim Golden" wrote in message news:mailman.1895.1139917457.27775.python-list at python.org... [Sergey] >But note that r prefix to the string. Is it possible >that your string didn't include it? If not, then the >backslash character which Windows uses as a separator >can be stolen by Python which sees it as an escaping >character. It's ok with backslashes, I don't use r'', but double them so string is correct: >>> print c \\?\e:\files\........ From juho.schultz at helsinki.fi Thu Feb 16 02:25:15 2006 From: juho.schultz at helsinki.fi (Juho Schultz) Date: Thu, 16 Feb 2006 09:25:15 +0200 Subject: How to run shell commands within python In-Reply-To: <1140074469.258382.24620@f14g2000cwb.googlegroups.com> References: <1140074469.258382.24620@f14g2000cwb.googlegroups.com> Message-ID: fileexit wrote: > How can I execute shell commands from within python. Specifically, I > am looking for something like the shell "cat". But this also made me > wonder how to execute shell commands anyway, just if i needed to do > that in the future. > You can use os.system() for that. From derek at hotmail.com Tue Feb 28 10:23:38 2006 From: derek at hotmail.com (derek) Date: Tue, 28 Feb 2006 23:23:38 +0800 Subject: looking for help about python-sane Message-ID: I m looking for help about python-sane, The follow sample code try to grab the image from the webcam through a /dev/video0 on linux, it works fine for the first 185 times, but it freeze the computer when i ~ 185, I dont know why? The computer become very busy when i > 160, very strange? I m using Ubuntu 5.10 Linux Thanks -----------------------code start------------------ #! /usr/bin/python import sane, time, Image def grabImage(_webcam): _webcam.mode='color' _webcam.start() img=_webcam.snap() return img for i in range(200): print 'i=', i sane.init() webcam = sane.open('v4l:/dev/video0') grabImage(webcam) webcam.close() sane.exit() time.sleep(1) ----------------------code end------------------- ---------------------output-------------------- i=0 i=1 i=2 .... i= 182 i= 183 i= 184 i= 185 Traceback (most recent call last): File "testSane.py", line 17, in ? grabImage(webcam) File "testSane.py", line 7, in grabImage _webcam.start() File "/usr/lib/python2.4/site-packages/sane.py", line 201, in start return self.dev.start() _sane.error: Error during device I/O From dylan.moreland at gmail.com Sat Feb 18 18:35:05 2006 From: dylan.moreland at gmail.com (Dylan Moreland) Date: 18 Feb 2006 15:35:05 -0800 Subject: general coding issues - coding style... In-Reply-To: References: <45ool3F7ipqbU1@uni-berlin.de> Message-ID: <1140305704.970072.177040@g14g2000cwa.googlegroups.com> calmar wrote: > On 2006-02-18, Diez B. Roggisch wrote: > > - why are these {{{ thingies there? > > markers for folding for vim > http://www.calmar.ws/tmp/sc.png I would look into one of the many Vim scripts which automatically fold most large blocks without the ugly {{{. From gh at ghaering.de Tue Feb 21 04:52:16 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 21 Feb 2006 10:52:16 +0100 Subject: converting sqlite return values In-Reply-To: <1140465583.398495.63470@g44g2000cwa.googlegroups.com> References: <1140465583.398495.63470@g44g2000cwa.googlegroups.com> Message-ID: <43FAE2D0.5070906@ghaering.de> bolly wrote: > Hi, > I've been putting Python data into a sqlite3 database as tuples but > when I retrieve them they come back as unicode data e.g > 'u(1,2,3,4)'. Looks like you're using pysqlite 2.x. > How can I change it back to a tuple so I can use it as a > Python native datatype? You cannot store tuples using pysqlite directly: >>> from pysqlite2 import dbapi2 as sqlite >>> con = sqlite.connect(":memory:") >>> cur = con.cursor() >>> cur.execute("create table test(foo)") >>> t = (3, 4, 5) >>> cur.execute("insert into test(foo) values (?)", (t,)) Traceback (most recent call last): File "", line 1, in ? pysqlite2.dbapi2.InterfaceError: Error binding parameter 0 - probably unsupported type. >>> That's because only a limited set of types that have a sensible mapping to SQLite's supported data types is supported. So probably you did something like: >>> cur.execute("insert into test(foo) values (?)", (str(t),)) >>> cur.execute("select foo from test") >>> res = cur.fetchone()[0] >>> res u'(3, 4, 5)' >>> Aha. You stored a string and got back a Unicode string. That's all ok because SQLite strings are by definition all UTF-8 encoded that's why the pysqlite developer decided that what you get back in Python are Unicode strings. Now there are different possibilites to attack this problem. a) Use SQLite as a relational database and don't throw arbitrary objects at it b) Write a custom converter and adapter for your tuple type. See http://initd.org/pub/software/pysqlite/doc/usage-guide.html#sqlite-and-python-types This way it will all work transparently from you once you've done the preparations. c) Store and retrieve the whole thing as a BLOB and convert manually: >>> cur.execute("delete from test") >>> cur.execute("insert into test(foo) values (?)", (buffer(str(t)),)) >>> cur.execute("select foo from test") >>> res = cur.fetchone()[0] >>> res >>> eval(str(res)) (3, 4, 5) That's the simple apprach, but it sucks because eval() is sloppy programming IMO. So I'd rather marshal and demarshal the tuple: >>> import marshal >>> cur.execute("delete from test") >>> cur.execute("insert into test(foo) values (?)", (buffer(marshal.dumps(t)),)) >>> cur.execute("select foo from test") >>> res = cur.fetchone()[0] >>> marshal.loads(res) (3, 4, 5) > I have looked in the docs and seen there is a decode/encode method but > how do I do this? You don't. This was for only there in pysqlite 1.x and pysqlite 2.x. In pysqlite 2.x, you use the Python builtin buffer() callable to convert strings to buffers to mark them as BLOB values for pysqlite and you willg et back buffer objects from pysqlite for BLOB values, too. HTH, -- Gerhard From skromta at gmail.com Tue Feb 14 06:15:37 2006 From: skromta at gmail.com (Kalle Anke) Date: Tue, 14 Feb 2006 12:15:37 +0100 Subject: Python / Apache / MySQL References: <1139907519.427789.188760@g14g2000cwa.googlegroups.com> <0001HW.C01764D700060858F0407550@news.individual.de> <43f1aebb$0$1728$636a55ce@news.free.fr> <0001HW.C01772E1000952B1F0407550@news.individual.de> Message-ID: <0001HW.C0177A69000B1680F0407550@news.individual.de> On Tue, 14 Feb 2006 12:04:45 +0100, Peter Hansen wrote (in article ): > SQLite. (As but one option, but "just basic selects" is certainly > included in the set of suitable conditions for SQLite use.) I've considered to use SQLite for an application but for completely different reasons ... hmm, I should perhaps consider SQLite for some other ideas I have also ... > Don't optimize prematurely? If you use something like SQLObject, or any > other means of abstracting yourself away from the details of a specific > datbase, you won't be particularly tied to it if you decide you need > improved performance, or sophistication, or whatever. That's true ... I was thinking in general terms here (a couple of people I know handles huge data sets, genome data type of things, and in their case speed is very important) From tprimke at interia.pl Sat Feb 4 07:21:50 2006 From: tprimke at interia.pl (TPJ) Date: 4 Feb 2006 04:21:50 -0800 Subject: A problem with some OO code. Message-ID: <1139055710.688193.81000@z14g2000cwz.googlegroups.com> Help me please, because I really don't get it. I think it's some stupid mistake I make, but I just can't find it. I have been thinking about it for three days so far and I still haven't found any solution. My code can be downloaded from here: http://www.tprimke.net/konto/PyObject-problem.tar.bz2. There are some scripts for GNU/Linux system (bash to be precise). All you need to know is that there are four classes. (Of course, you may generate all the documentation by typing just "./make_docs". All you need is Python with Epydoc installed.) In the PyObject.py there are two classes: Object and OManager. When Object wants to know if some link is safe (in another words: it wants to know if some another object exists), it calls the proper method of its objects' manager (the OManager instance). Details are not important here, so I'll just say, that if the link is safe, the objects' manager calls the proper method of the object, that sent him request. This method of the object just stores the information about that link (that it's safe), in the so-called private field (the fields used to store the information about the links are called __ls_existing_links and __ls_demanded_links). And now the tests. In the test.py file this is a class called Obj. That class is just an Object. This is also a class called System1 - this class is used only to create a more complex system composed of many objects and one objects' manager. You can run all the tests by just typing "./test" in console (or a terminal emulator). I'm still getting the same error: -------------------------------------------------- Traceback (most recent call last): File "test.py", line 142, in test04CreateSystems system1 = System1() File "test.py", line 81, in __init__ self.objA.demandNewLink( 'B' ) File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", line 503, in demandNewLink s_object ) File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", line 800, in _makeNewLink o_srcobj._makeLinkSafe( s_target ) File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", line 608, in _makeLinkSafe self.__makeLinkSafe( s_object ) File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", line 582, in __makeLinkSafe i = self.__ls_demanded_links.index( s_object ) AttributeError: 'Obj' object has no attribute '_Object__ls_demanded_links' -------------------------------------------------- Perhaps I'll explain what's going on there. First, the objects' manager is created, and then also some objects are created. After doing that, the object called "objA" demands a new link to the other object, called "objB" (this is the line 81 in the error message above). As the result, the "demandNewLink" method of the object "objA" is called. This method calls the "_makeNewLink" method of the objects' manager, and this method calls the "_makeLinkSafe" method of the object, that demanded a new link. The last method, called "__makeNewLink" (so this is a so-called private method), is called then. This last method is supposed to check if the link was really demanded and then make it "safe" by placing the information about this link in the proper dictionary (__ls_existing_links). All these methods are the methods of the Object class (defined in PyObject.py), not of the Obj class (defined in test.py). According to my knowledge about the OO programming Python should be able to realize, that the so-called private fields, that are being referred from these Object class methods, are the private fields of the *Obj class instance*, not of the *Object class one*. I even wrote a simple program to test the usage of the so-called private fields in Python classes: -------------------------------------------------- class A( object ): def __init__( self ): self.__a = 1 def _add( self ): print "self.__a =", self.__a self.__a += 1 def print_a( self ): print self.__a class B( A ): def __init__( self ): A.__init__( self ) self.__b = 2 def print_b( self ): print self.__b def test(): o = B() o.print_a() o.print_b() o._add() o.print_a() o.print_b() -------------------------------------------------- The code works just as I thought it should work: all is fine here. The B class instance (the b object) is able to refer to the so-called private field of the A class (through a A-class method, that was inherited by the class B). Why I can't do the same thing in test.py and in PyObject.py? I just don't get it. (And sorry for the subject of this topic. I really had no better idea...) From mcbooczech at gmail.com Wed Feb 15 17:03:42 2006 From: mcbooczech at gmail.com (Petr Jakes) Date: 15 Feb 2006 14:03:42 -0800 Subject: how to get function names from the file Message-ID: <1140041022.500870.141430@g14g2000cwa.googlegroups.com> I have got names of functions stored in the file. For the simplicity expect one row only with two function names: printFoo, printFOO In my code I would like to define functions and then to read function names from the file, so the functions can be executed in the order the function names are stored in a file. While trying to read the names from the file I am getting always "strings" and I am not able to execute them. I would like to write my code so it will look something like: def printFoo(): print "foo" def printFOO(): print "FOO" # here I would like to read the file with the function names sequences # and to create tuple which will contain the function names. # After that I would like to call functions from the tuple: functions=(printFoo, printFOO) for function in functions: function() Thanks for your postings Petr Jakes From mrmakent at cox.net Tue Feb 14 13:19:50 2006 From: mrmakent at cox.net (mrmakent at cox.net) Date: 14 Feb 2006 10:19:50 -0800 Subject: Python advocacy in scientific computation In-Reply-To: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> Message-ID: <1139941190.633797.133020@g47g2000cwa.googlegroups.com> Nicely done. But now for a couple of small nits: > other language is that they are suddenly dramatically several times > more productive 'suddenly dramatically several times' seems a bit redundantly repeditively excessive, don't you think? > Among the Python components and Python bindings of special interest to > scientists are the elegant and powerful matplotlib plotting package, > which began by emulating and now surpasses the plotting features of > Matlab, SWIG, which allows for runtime interoperability with various > languages, f2py which specifically interoperates with Fortran, NetCDF > libraries (which cope with NetCDF files with dramatically less fuss > than the standard C or Fortran bindings), statistics packages including > bindings to the R language, linear algebra packages, various > platform-specific and portable GUI libraries, genetic algorithms, > optimization libraries, and bindings for high performance differential > equation solvers (notably, using the Argonne National Laboratory > package PetSC). As the length of the sentence built up, and the inumerable commas passed by, my brain exploded. I'd suggest turning this into a bullet list. From deets at nospam.web.de Mon Feb 20 19:15:06 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 21 Feb 2006 01:15:06 +0100 Subject: decorator and function local variable In-Reply-To: <21b0qx59zcqo$.5dmxxfkxl7h3$.dlg@40tude.net> References: <21b0qx59zcqo$.5dmxxfkxl7h3$.dlg@40tude.net> Message-ID: <45v4cbF8lb11U1@uni-berlin.de> Grzegorz Smith schrieb: > Hi all. I have got situation that I need make parameter injection into > function and I want that parametet be a local variable of that function. > eg. something like > def decorator(): > > @decorator > def myfun(): > a = 20 > > and in myfun i can use b wariable like that: > b = "ok it's working" > I try to use sample decorators from: > http://www.python.org/moin/PythonDecoratorLibrary > but unsuccesfully. Does anyone know hot to achieve this? Or is it possible? I don't fully understand what you're after here - but are you aware of the __call__-method on objects? You might very well do it like this: class Foo: def __init__(self, parameter): self.parameter = parameter def __call__(self, *args): return "%r %r" % (self.parameter, args) Then you can do f = Foo() f(1,2,3,4) And if you need to alter f's working by means of parameter, just assign it a new value. Diez From mark at mark-fink.de Sun Feb 5 07:36:38 2006 From: mark at mark-fink.de (Mark Fink) Date: 5 Feb 2006 04:36:38 -0800 Subject: rexec in jython?? References: <1139138133.072742.282710@z14g2000cwz.googlegroups.com> <1139140115.016898.72360@z14g2000cwz.googlegroups.com> Message-ID: <1139142998.236991.130470@g47g2000cwa.googlegroups.com> this is really funny... I tried to use eval(String) as an replacement. It works now but the calculation results from my tests are not as expected: 2 + 3 = 23 !!! 2 - 3 = 2-3... I have the feeling that there is a really easy solution for this. Unfortunately I have no enough experience From johnjsal at NOSPAMgmail.com Thu Feb 23 11:51:02 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 23 Feb 2006 16:51:02 GMT Subject: a little more help with python server-side scripting In-Reply-To: References: <59edncmGm6g2LmbeRVn-pw@rcn.net> Message-ID: Sybren Stuvel wrote: > Check out PSP. I found a PSP website that said this: --------- In general, PSP pages are like normal HTML files with two exceptions: 1. They always have a .PSP file extension 2. They can have JPython code embedded in them --------- That sounds like just what I want, except do I have to write my code in Jython? Can't I just use regular Python? From steve at REMOVETHIScyber.com.au Sat Feb 4 09:34:33 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 05 Feb 2006 01:34:33 +1100 Subject: A problem with some OO code. References: <1139055710.688193.81000@z14g2000cwz.googlegroups.com> Message-ID: On Sat, 04 Feb 2006 04:21:50 -0800, TPJ wrote: > Help me please, because I really don't get it. I think it's some stupid > mistake I make, but I just can't find it. I have been thinking about it > for three days so far and I still haven't found any solution. > > My code can be downloaded from here: > http://www.tprimke.net/konto/PyObject-problem.tar.bz2. There are some > scripts for GNU/Linux system (bash to be precise). Hint: when asking strangers to help you, at THEIR time and expense, with no offer to recompense them for their efforts, it is up to YOU to make their job as easy as possible. That means don't expect people to download some untrusted, potentially dangerous, piece of code from a stranger on Usenet, go to the trouble of extracting it from an archive, and then debug it for you. You need to simplify the code as much as possible, cutting away everything you can, to the SMALLEST amount of code that still experiences the problem. I've made some comments based on the information in your post. If they don't help, you will need to spend some time creating a short example that has the same problem. There is very little point in showing us test code that works -- your problem isn't with code that works, it is with code that doesn't work. > All you need to know is that there are four classes. No, I'm sure we need to know much more than that. > (Of course, you > may generate all the documentation by typing just "./make_docs". All > you need is Python with Epydoc installed.) Oh right, well just let me rush off and install Epydoc just for you, okay? > In the PyObject.py there are two classes: Object and OManager. When > Object wants to know if some link is safe (in another words: it wants > to know if some another object exists), What is a link in your application? What do you mean "another object"? Like an int or a string? This is the normal Python idiom for testing whether an object exists (strictly speaking, whether a name is bound to an object). try: some_object except NameError: print "some_object does not exist" Is that what you mean? > it calls the proper method of > its objects' manager (the OManager instance). Details are not important > here, I bet the details are absolutely vital. > so I'll just say, that if the link is safe, the objects' manager > calls the proper method of the object, that sent him request. This > method of the object just stores the information about that link (that > it's safe), in the so-called private field (the fields used to store > the information about the links are called __ls_existing_links and > __ls_demanded_links). This is a terribly involved way of doing it, and I'm not even sure what "it" is that you are trying to do. Are you trying to do some sort of dispatch mechanism? I see you have a line "i = self.__ls_demanded_links.index( s_object )". It looks like you are storing your data in a chunk of text, and then running index on that text to find the bit you want to work with. If you wanted to do that much work, just write your script in bash and be done with it! Python has lists and dicts and other advanced data structures. Use them. You will be glad. > And now the tests. In the test.py file this is a class called Obj. That > class is just an Object. So Obj is an alias for Object? What's an Object? Is it the same as the Python built-in type "object"? But later on you say: "All these methods are the methods of the Object class (defined in PyObject.py), not of the Obj class (defined in test.py)." So Object and Obj are not the same. > This is also a class called System1 - this > class is used only to create a more complex system composed of many > objects and one objects' manager. > > You can run all the tests by just typing "./test" in console (or a > terminal emulator). I'm still getting the same error: > > -------------------------------------------------- > Traceback (most recent call last): > File "test.py", line 142, in test04CreateSystems > system1 = System1() > File "test.py", line 81, in __init__ > self.objA.demandNewLink( 'B' ) > File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", > line 503, in demandNewLink > s_object ) > File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", > line 800, in _makeNewLink > o_srcobj._makeLinkSafe( s_target ) > File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", > line 608, in _makeLinkSafe > self.__makeLinkSafe( s_object ) > File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", > line 582, in __makeLinkSafe > i = self.__ls_demanded_links.index( s_object ) > AttributeError: 'Obj' object has no attribute > '_Object__ls_demanded_links' [snip] > Perhaps I'll explain what's going on there. First, the objects' manager > is created, and then also some objects are created. After doing that, > the object called "objA" demands a new link to the other object, called > "objB" (this is the line 81 in the error message above). Your description does not match what line 81 actually says. It says: self.objA.demandNewLink('B') self (an instance of System1, not Obj or Object) grabs the attribute called "objA", and calls its method demandNewLink with an argument of the string 'B', not objB an instance of Obj or Object. (Aside: generic names like "Obj" or "Object" are poor practice unless they genuinely are generic. A good name should be self-documenting if possible, but more importantly, names which are easy to confuse like Obj and Object should be avoided.) If you want to work with Object instances, why not just use them instead of passing around strings that represent them? > As the result, > the "demandNewLink" method of the object "objA" is called. This method > calls the "_makeNewLink" method of the objects' manager, and this > method calls the "_makeLinkSafe" method of the object, that demanded a > new link. The last method, called "__makeNewLink" (so this is a > so-called private method), is called then. This seems like a very brittle way to code. > This last method is supposed > to check if the link was really demanded and then make it "safe" by > placing the information about this link in the proper dictionary > (__ls_existing_links). Huh? Do you mean that there is a way for links (whatever they are) to be requested without calling demandNewLink? How would this happen? > All these methods are the methods of the Object class (defined in > PyObject.py), not of the Obj class (defined in test.py). According to > my knowledge about the OO programming Python should be able to realize, > that the so-called private fields, that are being referred from these > Object class methods, are the private fields of the *Obj class > instance*, not of the *Object class one*. Some serious confusion here. What are fields? Do you mean attributes? I'm going to assume that you do. Would it help if I told you that Python doesn't have private attributes? It *simulates* private attributes using name mangling. Thus: class Parrot: __plumage = "red" actually creates a class attribute "_Parrot__plumage". If you know the name of the class, you can bypass Python's "private attributes". PLEASE don't bother to tell us how Python sucks because it doesn't have "real private attributes", we've heard the arguments (and the abuse) fifty times before. Now, the consequences: When Python does a lookup, it looks in the appropriate namespace for a name. Except for special rules relating to inheritance, Python doesn't magically look up attributes in another object's namespace just because that attribute was defined as a private attribute elsewhere. See below for the consequences. > I even wrote a simple program to test the usage of the so-called > private fields in Python classes: Good. Now how about getting a simple program that demonstrates your problem? > class A( object ): > def __init__( self ): > self.__a = 1 > def _add( self ): > print "self.__a =", self.__a > self.__a += 1 > def print_a( self ): > print self.__a Do you enjoy all this make-work, writing tedious methods to get or set or print attributes? I suggest you ditch all the private attributes and just make them public. You've already spent three days hitting your head against a brick wall because of excessive data-hiding. Was it worth it? Python is a language that encourages the attitude "We're all adults here" -- getters/setters are discouraged. > class B( A ): > def __init__( self ): > A.__init__( self ) > self.__b = 2 > def print_b( self ): > print self.__b > > def test(): > o = B() > o.print_a() > o.print_b() > o._add() > o.print_a() > o.print_b() I don't think this is showing what you think it is showing. Private vs public attributes just get in the way: they work *exactly* the same in Python except for name mangling. This is the problem bit: class B( A ): def __init__( self ): A.__init__( self ) ### LOOK HERE You aren't creating an A instance here, you are calling A.__init__ with a first argument of "self", which is a B instance. __init__ does not create instances, it runs AFTER the instance is already created. Perhaps you already know that. But I don't think you understand the consequences of this, when using so-called private attributes: The call to A.__init__ creates an attribute __a to self. Remember, self is an instance of B (not A). Apply the name-mangling rules, which are applied at compile time: the code in A's method mangles __a to _A__a. So A.__init__ creates an attribute _A__a in B's namespace. So B has two attributes, _A__a and _B__b. That means that B methods that access self.__b will work, because the name mangling rules work *with you*, and self.__b is mangled to self._B__b. But B methods that access self.__a will NOT work, because it is mangled to self._B__a, and that attribute does not exist. (However, that is not your problem.) > The code works just as I thought it should work: all is fine here. Except it is brittle and hard to maintain. > The > B class instance (the b object) is able to refer to the so-called > private field of the A class (through a A-class method, that was > inherited by the class B). > > Why I can't do the same thing in test.py and in PyObject.py? Here is your exception again: > line 582, in __makeLinkSafe > i = self.__ls_demanded_links.index( s_object ) > AttributeError: 'Obj' object has no attribute > '_Object__ls_demanded_links' This is not making sense to me. If self is an instance of Obj, the name-mangling rules will convert self.__ls_demanded_links to self._Obj__ls_demanded_links. The only thing I can guess is that somehow, somewhere, you have tried to manually set the class of an object. Something like this perhaps? >>> class Obj: ... __bar = "nothing" ... >>> class Object(Obj): ... __foo = "something" ... def foo(self): ... print self.__foo ... def bar(self): ... print self.__bar ... >>> x = Object() >>> x.__class__.__name__ = "Obj" >>> x.foo() something >>> x.bar() Traceback (most recent call last): File "", line 1, in ? File "", line 6, in bar AttributeError: Obj instance has no attribute '_Object__bar' That's the only way I can think of to get such an unusual error. -- Steven. From greg at cosc.canterbury.ac.nz Sun Feb 12 01:50:56 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 12 Feb 2006 19:50:56 +1300 Subject: ANN: PyGUI 1.6 Message-ID: PyGUI 1.6 is now available: http://www.cosc.canterbury.ac.nz/~greg/python_gui/ The major change in this version is that the Mac version is based on Cocoa instead of Carbon. This should provide a much better base for future development, but it does mean that MacOSX will now be required. (This isn't as big a change as it seems, since the Carbon version actually required MacOSX too, despite being Carbon.) There have been numerous other changes and improvements as well. See the CHANGES file in the distribution or on the web site for full details. What is PyGUI? -------------- PyGUI is an experimental highly-Pythonic cross-platform GUI API. Implementations are currently available for MacOSX and Gtk. For a full description of the project goals, see the PyGUI web page at the above address. From weinhand at unileoben.ac.at Mon Feb 13 04:28:46 2006 From: weinhand at unileoben.ac.at (WEINHANDL Herbert) Date: Mon, 13 Feb 2006 10:28:46 +0100 Subject: Writing a Web Robot in Python In-Reply-To: <1139818483.962291.131570@g47g2000cwa.googlegroups.com> References: <1139818483.962291.131570@g47g2000cwa.googlegroups.com> Message-ID: <43f05119$0$11868$3b214f66@aconews.univie.ac.at> mudgen at gmail.com schrieb: > I'm working on writing a web robot (for searching web pages) in Python > so I've been browsing around the web looking for data about building > web robots. > > I'm surprised to find that I didn't find much data. Seems like robots > would be kind of a common thing to build. I know there is this: "The > Web Robots Pages" (http://www.robotstxt.org/wc/robots.html) but that > doesn't have a lot of data and seems pretty out of date. > > I checked amazon.com for books on building web robots and I didn't find > very much. Seems kind of weird that I don't find much data on this > subject. Anybody know some good places to go to get information on > building a web robots? maybe one of the following packages will fullfill your needs http://www.idyll.org/~t/www-tools/twill/ http://wwwsearch.sourceforge.net/mechanize/ http://python.org/pypi/mechanoid happy pythoning herbert From python.list at tim.thechases.com Mon Feb 27 03:03:38 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 27 Feb 2006 02:03:38 -0600 Subject: How to do an 'inner join' with dictionaries In-Reply-To: <1141047580.492771.97130@z34g2000cwc.googlegroups.com> References: <1141047580.492771.97130@z34g2000cwc.googlegroups.com> Message-ID: <4402B25A.8040600@tim.thechases.com> > Let's say I have two dictionaries: > dict1 is 1:23, 2:76, 4:56 > dict2 is 23:A, 76:B, 56:C > > How do I get a dictionary that is > 1:A, 2:B, 4:C >>> d1={1:23,2:76,4:56} >>> d2={23:"a", 76:"b", 56:"c"} >>> result = dict([(d1k,d2[d1v]) for (d1k, d1v) in d1.items()]) >>> result {1: 'a', 2: 'b', 4: 'c'} If you don't know that all the values in d1 will be in d2, >>> d1[5]=444 >>> d2[333]='qqq' you can put in a "if" check like >>> result = dict([(d1k,d2[d1v]) for (d1k, d1v) in d1.items() if d1v in d2]) {1: 'a', 2: 'b', 4: 'c'} (using "d1v" for "dictionary1's value" and "d1k" for "dictionary1's key") HTH, -tkc From steven.bethard at gmail.com Tue Feb 28 10:55:38 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 28 Feb 2006 08:55:38 -0700 Subject: PEP 354: Enumerations in Python In-Reply-To: <87accdplbj.fsf@rose.polar.local> References: <87accdplbj.fsf@rose.polar.local> Message-ID: Ben Finney wrote: > This PEP specifies an enumeration data type for Python. > > An enumeration is an exclusive set of symbolic names bound to > arbitrary unique values. Values within an enumeration can be iterated > and compared, but the values have no inherent relationship to values > outside the enumeration. -1 on the proposal as-is. I don't have many use cases for enumerations, and I don't think they merit appearing in the builtins. If you put them in the collections module instead, I'd probably be +0. > This allows the operation to succeed, evaluating to a boolean value:: > > >>> gym_night = Weekdays.wed > >>> gym_night < Weekdays.mon > False > >>> gym_night < Weekdays.wed > False > >>> gym_night < Weekdays.fri > True > >>> gym_night < 23 > False > >>> gym_night > 23 > True > >>> gym_night > "wed" > True > >>> gym_night > Grades.B > True For the few cases of enumerations that I've needed, I've never wanted them to be comparable with <, >, etc. If there were two classes, say ``collections.Enum`` and ``collections.OrderedEnum`` where only the latter made the enumerated items comparable, you might even get me as high as +0.5. (I only care about the non-comparable one, but I understand that others may have a need for the comparable one.) STeVe From claird at lairds.us Fri Feb 17 10:08:02 2006 From: claird at lairds.us (Cameron Laird) Date: Fri, 17 Feb 2006 15:08:02 GMT Subject: Print a PDF transparently References: <1140184955.674138.275010@o13g2000cwo.googlegroups.com> Message-ID: In article <1140184955.674138.275010 at o13g2000cwo.googlegroups.com>, Daniel Crespo wrote: >Hi to all, > >I want to print a PDF right from my python app transparently. With >"transparently" I mean that no matter what program handles the print >petition, the user shouldn't be noticed about it. > >For example, when I want to print a PDF, Adobe Acrobat fires and keep >opened. This is what I don't want to happen (and I thing there are a >lot of people who want this too). So I just want to send the PDF to the >right handler and print it. That's all. > >I've seen some things like Adobe's Postscript driver that can read a >PDF, or Ghostscript, but I still don't know how to use it. > >Any help for printing a PDF transparently? . . . Yes, but it's never going to be easy. People have worked on this for years ... First, what platforms and printers interest you? Are you only interested in Linux-connected-to-PostScript-capable-printers, or do you want to do Windows and Mac, and ...? Also, there are likely to be licensing considerations sooner or later. Start thinking about your situation in that regard. From uche.ogbuji at gmail.com Tue Feb 7 12:44:28 2006 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 7 Feb 2006 09:44:28 -0800 Subject: XML Writer in wxPython In-Reply-To: <16prs1hphnihj4klt3f8552p6fhsmoeg8v@4ax.com> References: <1137083537.351635.190010@g14g2000cwa.googlegroups.com> <1137405788.767291.175750@o13g2000cwo.googlegroups.com> <16prs1hphnihj4klt3f8552p6fhsmoeg8v@4ax.com> Message-ID: <1139334268.835849.197400@g44g2000cwa.googlegroups.com> Tim Roberts wrote re using print to generate XML: > def PrintAddress( last, first, address, city, state, zip ): > print "
" > print " %s" % last > print " %s" % first > print " %s" % address > print " %s" % city > print " %s" % state > print " %s" % zip > print "
" > > print "" > for row in addressDatabase: > PrintAddress( row.last, row.first, > row.address, row.city, row.state, row.zip ) > print "" Just be sure you're well aware of all the issues: http://www.xml.com/pub/a/2002/11/13/py-xml.html See also: http://www.ibm.com/developerworks/xml/library/x-think35.html -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ From donn at u.washington.edu Wed Feb 1 12:31:21 2006 From: donn at u.washington.edu (Donn Cave) Date: Wed, 01 Feb 2006 09:31:21 -0800 Subject: Python vs C for a mail server References: <1138728303.669646.36940@g49g2000cwa.googlegroups.com> <1138805854.533303.279610@g49g2000cwa.googlegroups.com> Message-ID: In article <1138805854.533303.279610 at g49g2000cwa.googlegroups.com>, ... > Granted, it is a pain to change type declarations. I see it is time for the bi-monthly reminder that C++ is not the ideal example of strong static typing, unless you just want to make it look bad. Cf. Hindley-Milner type inference. Donn Cave, donn at u.washington.edu From codecraig at gmail.com Sat Feb 18 22:27:42 2006 From: codecraig at gmail.com (abcd) Date: 18 Feb 2006 19:27:42 -0800 Subject: Get parameters from URL using CGI In-Reply-To: References: <1140285087.919635.74530@g43g2000cwa.googlegroups.com> Message-ID: <1140319662.582538.250400@g43g2000cwa.googlegroups.com> Ian Leitch wrote: > >>> from urlparse import urlparse > >>> dict([n for n in [i.split('=') for i in > urlparse('http://www.somesite.com/cgi-bin/foo.cgi?name=john&age=90')[4].split('&')]]) > {'age': '90', 'name': 'john'} Ian, thanks for the reply, but that is not what I need to do. Inside foo.cgi how can I parse out the values given in the URL? So if you visit: http://www.somesite.com/cgi-bin/foo.cgi?valA=1&valB=2 .....I want the script, foo.cgi to print out the parameters and their values. It's dynamic so the values are url wont be the same all the time. How do i get the URL from the script? does this make sense? So I'm thinking foo.cgi will look like [code] url = getTheFullURL() parse(url) def parse(url): # parse the parameter names and values [/code] From paul at boddie.org.uk Thu Feb 23 08:31:26 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 23 Feb 2006 05:31:26 -0800 Subject: Python vs. Lisp -- please explain References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> <1140425017.101462.117380@g47g2000cwa.googlegroups.com> <1140622216.436013.234400@g47g2000cwa.googlegroups.com> Message-ID: <1140701486.038987.66790@v46g2000cwv.googlegroups.com> Alexander Schmolck wrote: > Rocco Moretti writes: > > > I think it's worth pointing out that not all dynamicism is equal, when it > > comes to difficulty in compiling to machine code. > > No kidding (do you have any idea how this thread started out?). I had to remind myself. > > Lisp, like the good functional language that it is, has (primarily) immutable > > values, and minimal side effects. > [further nonsense snipped] > > Please don't spread misinformation about things about which you are clueless[1]. I don't see why you have to be quite so blunt, here. Anyway, some of the observations made about Python, especially when any comparisons with Lisp (once corrected) show that Python is more similar to Lisp than previously thought, are worth considering with respect to things like type inference and the subsequent generation of low-level code. > Footnotes: > [1] Just as a minor illustrative detail: in python 2 out of 4 builtin > collection types are immutable (tuples and strings; newer versions also > have immutable and mutable sets) in CL 5 out of 5 are mutable > (arrays/vectors/strings, hash-tables, cons cells). Well, apart from a brief encounter with Lisp back in the microcomputer era, I've only just got back into looking at the language, and I suppose I'll eventually find out how the optional type declarations mentioned occasionally in connection with Lisp actually manage to handle the harder problems around efficient code generation. I haven't really studied type systems or compilers in any depth, however, but having considered the issues for a while I'd like to think that my rating has progressed from "clueless" to "mostly clueless" by this point. Paul From kent at kentsjohnson.com Mon Feb 27 15:16:05 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 27 Feb 2006 15:16:05 -0500 Subject: type = "instance" instead of "dict" In-Reply-To: <1141069989.763239.191140@u72g2000cwu.googlegroups.com> References: <1141069989.763239.191140@u72g2000cwu.googlegroups.com> Message-ID: <44035966$1_2@newspeer2.tds.net> Cruella DeVille wrote: > I'm trying to implement a bookmark-url program, which accepts user > input and puts the strings in a dictionary. Somehow I'm not able to > iterate myDictionary of type Dict{} > > When I write print type(myDictionary) I get that the type is > "instance", which makes no sense to me. What does that mean? Maybe you have an instance of UserDict instead of a built-in dict? >>> type({}) >>> from UserDict import UserDict >>> type(UserDict()) UserDict.UserDict is not iterable, though you can still use for k in myDictionary.keys() There is also UserDict.IterableUserDict which does support iteration. I don't think there is much reason to use UserDict in modern Python as dict can be subclassed. Kent From finite.automaton at gmail.com Fri Feb 10 20:47:50 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 10 Feb 2006 17:47:50 -0800 Subject: equivalent functions? In-Reply-To: <1139621457.141754.228880@f14g2000cwb.googlegroups.com> References: <1139621457.141754.228880@f14g2000cwb.googlegroups.com> Message-ID: <1139622470.638044.158410@o13g2000cwo.googlegroups.com> Very close... it is equivalent to: apply_each = lambda fns, args=[]: [f(*args) for f in fns] The asterisk in f(*args) expands the sequence to fill the arguments to f, where as f(args) would pass the args as only the first argument to the function. apply is deprecated, replaced by the syntax: function( *args, **keywords ) From crutcher at gmail.com Sun Feb 26 00:18:18 2006 From: crutcher at gmail.com (Crutcher) Date: 25 Feb 2006 21:18:18 -0800 Subject: xslt queries in xml to SQL queries In-Reply-To: References: Message-ID: <1140931098.472396.50620@i39g2000cwa.googlegroups.com> Skipping ahead, let me try to rephrase this. First, this isn't really a python question, it is SQL, XSLT, and program design, but I'll try to answer. You have templates, they contain general layout stuff, and input fields. You are transforming them into HTML pages, and part of what you want to do is to expand the enumerated fields with the enumeration values at the time of template application. You read an article about XSLT, and decided that you could use it in your app. For some unknown reason, perhaps involving large amounts of alcohol, you want to use the syntax of XSLT, but have it actually parsed by python, which silently does an SQL querry to give you your results. This is a really, really bad idea. There are many ways to solve your problem using XSLT, and though all of them are easy, none of them are so simple that I could put them in a post to someone who doesn't know XSLT. If you know XSLT, follow the directions below, if you don't, DO NOT USE XSLT for this project. And for the love of anything you may believe in, don't try to implement a partial XSLT engine in python. Pattern 1, paramaterized templates: Pattern 1 assumes that all the data you will need for your templates is known in advance, and is common to your templates. If this is true, you need only generate an XML fragment with the data you need, and compose a document which contains both the data you need, and the page template you are rendering. Then, write an XSLT transform to build your pages, which can now resolve data needs in the template section using the data provided in the data section. Pattern 2, query extraction: When you don't know what data the page template might need, and the full dataset is unmanageably large, you can't use pattern 1 easily. So instead, write an XSLT transform which _only_ extracts information about the data you need. You can then run this transform, get the query list, perform the queries, and use the resultant data for the data tree from pattern 1. From mooquack at suad.org Tue Feb 7 22:24:48 2006 From: mooquack at suad.org (Kirk McDonald) Date: Tue, 07 Feb 2006 19:24:48 -0800 Subject: UnboundMethodType and MethodType In-Reply-To: References: Message-ID: <43e9635b$1@nntp0.pdx.net> Sch?le Daniel wrote: > Hello all, > > >>> class Q: > ... def bar(self): > ... pass > ... > >>> import types > >>> types.UnboundMethodType is types.MethodType > True > >>> > >>> type(Q.bar) > > >>> > >>> q = Q() > >>> type(q.bar) > > >>> > >>> type(q.bar) is types.UnboundMethodType > True > >>> q.bar > > > >>> > > I think is not very consistent > notice q.bar is bounded although type(q.bar) > says it's types.UnboundedMethodType > what do you think? > > Regard, Daniel > I think it's perfectly consistent: >>> class B(object): ... def bar(self): pass ... >>> B.bar >>> type(B.bar) >>> b = B() >>> b.bar > >>> type(b.bar) >>> id(B.bar) -1211888788 >>> id(b.bar) -1211888788 It's the same function, whether it's bound or not. Thus, it should always have the same type. It's simply called in different ways. You can just as easily say: >>> B.bar(b) As: >>> b.bar() -Kirk McDonald From sjw28 at sussex.ac.uk Mon Feb 20 11:09:21 2006 From: sjw28 at sussex.ac.uk (nuttydevil) Date: 20 Feb 2006 08:09:21 -0800 Subject: Processing text using python Message-ID: <1140451760.998278.90430@g43g2000cwa.googlegroups.com> Hey everyone! I'm hoping someone will be able to help me, cause I haven't had success searching on the web so far... I have large chunks of text ( all in a long string) that are currently all in separate notebook files. I want to use python to read these strings of text, THREE CHARACTERS AT A TIME. (I'm studying the genetic code you see, so I need to read and analyse each sequence one codon at a time effectively.) Does anyone have any idea of how to do this using python? I'm going to be optimistic and thank you for your help in advance! Samantha. From pikatxu at pikatxu.re Mon Feb 20 07:58:43 2006 From: pikatxu at pikatxu.re (pikatxu) Date: 20 Feb 2006 13:58:43 +0100 Subject: editor for Python on Linux References: Message-ID: On Sun, 19 Feb 2006 20:52:54 +0100, Mladen Adamovic wrote: > Hi! > > I wonder which editor or IDE you can recommend me for writing Python > programs. I tried with jEdit but it isn't perfect. eclipse+pydev ? I've never tried it though From abkhd at earth.co.jp Wed Feb 22 07:00:45 2006 From: abkhd at earth.co.jp (A.B., Khalid) Date: 22 Feb 2006 04:00:45 -0800 Subject: With pyMinGW References: <1140565378.921287.177380@g44g2000cwa.googlegroups.com> Message-ID: <1140609645.670997.49670@g44g2000cwa.googlegroups.com> bearophileHUGS at lycos.com wrote: > To use Pyrex, SWIG and the like on a Win2K I have followed this way: > > http://jove.prohosting.com/iwave/ipython/pyMinGW.html > > I already had MinGW 3.4.2, so I have decompressed the Python 2.4.2 > sources, I have merged in the pyMinGW patch, and I have run the global > compilation with: > > make -f python24.mak all > > It has compiled most things, but not zlibmodule.c > It has stopped the compilation with: > > c:\......\bin\dllwrap.exe: no export definition file provided. > Creating one, but that may not be what you want > make[1]: Leaving directory `/.../PyminGW/Python-2.4.2/MinGW' > make -f zlib.mak > make[1]: Entering directory `/.../PyminGW/Python-2.4.2/MinGW' > gcc.exe -c ../Modules/zlibmodule.c -o ../Modules/zlibmodule.o > -I"../Include" -I"../Pc" -I"../../../d > ist/zlib-1.2.3" -Wall -s -DNDEBUG -D_USRDLL -O2 > ../Modules/zlibmodule.c:8:18: zlib.h: No such file or directory > ../Modules/zlibmodule.c:66: error: syntax error before "z_stream" > > ... etc etc. > > Anyway, probably 98% was compiled and this Python works, I have tried > the standard tests and most of them pass. > Then I have downloaded the pyMinGW Extensions V. 0.0.6.6, so zip and > other things now work. > > The link to the Tcl-Tkinter extension doesn't work (the free site > hosting the file doesn't accept this file format anymore), so I cannot > use Tkinter. > > I have decompressed SWIG and put it in a temporary Path. > > I have then tried a basic SWIG example, (called example) coming from > this obsolete but probably still interesting page: > http://sebsauvage.net/python/mingw.html > > But I have had problems durign the module creation: > > C:\...\PyminGW\Python-2.4.2\MinGW>python setup.py build -cmingw32 > running build > running build_ext > building 'example' extension > swigging example.i to example_wrap.c > C:\...\PyminGW\swigwin-1.3.28\swig.exe -python -o example_wrap.c > example.i > creating build > creating build\temp.win32-2.4 > creating build\temp.win32-2.4\Release > C:\......\bin\gcc.exe -mno-cygwin -mdll -O -Wall -Ic:\python24\include > -Ic:\pytho > n24\PC -c example_wrap.c -o build\temp.win32-2.4\Release\example_wrap.o > example_wrap.c: In function `My_variable_set': > example_wrap.c:2550: error: `My_variable' undeclared (first use in this > function) > > ... ecc. > > > So I have had 3 problems, maybe some of you can suggest me how to solve > some of them. > > (Can the standard Python site accept to distribuite an installer with > MinGW-compiled Python + minGW + SWIG for people using Windows that want > such system prebuilt? Maybe me or another person can assemble it). > > Thank you, > bearophile It seems you may be using an old version of pyMinGW, because in the one I have the directory issue of zlib was fixed and the relevant part dealing with include directories in zlib.mak should read now as follows: LIBS = -L. -lpython24 -L"../../../dist/zlib-1.2.3" -lz --image-base,0x1e1B0000 INCS = -I"../Include" -I"../Pc" -I"../../../dist/zlib-1.2.3" CXXINCS = -I"../Include" -I"../Pc" -I"../../../dist/zlib-1.2.3" The idea is to make INCS point at the location of your zlib sources. As to the Tkinter-Tcl point, then please remember that this was a binary build extension distribution that had nothing to do with the core Python that pyMinGW is supposed to address. And if you download the extension sources then you can certainly build the libraries yourself, and then the python extensions, especially since you have make files ready to use for the later in the pyMinGW sources. The binary distribution was meant to make things a bit easier for people, but since the site stopped the hosting of zip files and since many people do not download that particular file anyway when it was hosted elsewhere, letting the file expire (inactive files are removed after one week from last download), then I hope you'd agree it would be much work for me to keep track of expired and unexpired files and so keep on uploading the files. As to your SWIG problem, then I suggest you look into the pyMinGW's extensions' directory. There you will find two examples of building C and CPP extensions using SWIG and MinGW. Regards, Khalid pyMinGW: http://jove.prohosting.com/iwave/ipython/pyMinGW.html From peter at engcorp.com Tue Feb 21 19:02:08 2006 From: peter at engcorp.com (Peter Hansen) Date: Tue, 21 Feb 2006 19:02:08 -0500 Subject: Video. In-Reply-To: References: Message-ID: Sybren Stuvel wrote: > Dr. Pastor enlightened us with: > >>What environment,library,product should I import or study to >>manipulate cameras, video, fire-wire, avi files? > > > That depends on what you want with it. Without more information I'd > say "transcode" Presumably this, found easily by typing that exact word into Google: http://www.transcoding.org/cgi-bin/transcode From duncan.booth at invalid.invalid Sat Feb 18 04:15:11 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Feb 2006 09:15:11 GMT Subject: Does Plone support distinct sets of users in subgroups? References: Message-ID: wheel wrote: > I'm not sure if this is the right venue for Plone questions, if not, > could someone ref me to a better one? The discussion groups on the plone > site are mailing lists and I'd rather not subscribe quite yet. Use gmane.org: you get NNTP access to all the plone mailing lists (and several thousand others) and it will subscribe you automatically under its own email address if you choose to post (you have to respond to a confirmation email from gmane before first time you post to each newsgroup). http://dir.gmane.org/index.php?prefix=gmane.comp.web.zope.plone From tim.golden at viacom-outdoor.co.uk Thu Feb 16 12:06:30 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 16 Feb 2006 17:06:30 -0000 Subject: Determing whether two ranges overlap Message-ID: <9A28C052FF32734DACB0A288A3533991044D257A@vogbs009.gb.vo.local> [Robin Haswell] | I was wondering if you could give me a hand with something. | If I have two | tuples that define a range, eg: (10, 20), (15, 30), I need to | determine | whether the ranges overlap each other. The algo needs to catch: | | (10, 20) (15, 25) | (15, 25) (10, 20) | (10, 25) (15, 20) | and | (15, 20) (10, 25) | | I can think of lots of ways to do this but it's in a tight | loop so I need | it to be as efficient as possible. Any help welcome :-) Don't know about efficient, but: x = 10, 20 y = 15, 25 (x[0] <= y[1]) and (x[1] >= y[0]) TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From kent at kentsjohnson.com Thu Feb 9 11:49:44 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 09 Feb 2006 11:49:44 -0500 Subject: line wrapping problem In-Reply-To: <1139484488.037165.106170@g43g2000cwa.googlegroups.com> References: <1139484488.037165.106170@g43g2000cwa.googlegroups.com> Message-ID: <43eb6e67$1_3@newspeer2.tds.net> S Borg wrote: > Hello, > > I am parsing text from one document to another. I have a scheme > similar to: > > for x in myfoobar: > print >> mytextfile, "%s " % mydictionary[x], #all on same line > print >> mytextfile, '\n' #new line > > > I am getting line breaks before my explicit line break. Am I > unwittingly copying '\n' characters from the original file? Where does mydictionary[x] come from? If it is from reading lines from a file it may contain trailing newlines. Also print >> mytextfile, '\n' will print two newlines, one explicit and one implicit in the print. Kent From rudy.schockaert at gmail.com Thu Feb 23 05:53:49 2006 From: rudy.schockaert at gmail.com (Rudy Schockaert) Date: Thu, 23 Feb 2006 11:53:49 +0100 Subject: CSV module and UNICODE Message-ID: <60987dac0602230253q3154866erff6b0a4f26b50378@mail.gmail.com> I'm having problems writing unicode to a csv file. I use the following code: ------------------------- import codecs import csv csvfile = csv.writer(codecs.open('filename.csv','w+','utf-8')) a = u'\xc9' csvfile.writerow([a,a]) ------------------------- It fails with the message: UnicodeEncodeError: 'ascii' codec can't encode ..... Is there any way I can solve this. 1. What about Unicode? Is it sufficient to pass a file object gotten from codecs.open()? For example: csvreader = csv.reader(codecs.open("some.csv", "r", "cp1252")) csvwriter = csv.writer(codecs.open("some.csv", "w", "utf-8")) In the first example, text would be assumed to be encoded as cp1252. Should the system be aggressive in converting to Unicode or should Unicode strings only be returned if necessary? In the second example, the file will take care of automatically encoding Unicode strings as utf-8 before writing to disk. Note: As of this writing, the csv module doesn't handle Unicode data. PEP 305 was last modified on Wed, 11 Aug 2004 Has something changed in between? Thanks in advance, Rudy -------------- next part -------------- An HTML attachment was scrubbed... URL: From petite.abeille at gmail.com Sun Feb 12 11:44:50 2006 From: petite.abeille at gmail.com (PA) Date: Sun, 12 Feb 2006 17:44:50 +0100 Subject: Is python very slow compared to C In-Reply-To: References: <1139690972.344818.136870@f14g2000cwb.googlegroups.com> <1139694723.857673.263750@z14g2000cwz.googlegroups.com> <1139742200.155197.245490@g14g2000cwa.googlegroups.com> <1139754010.067582.214830@z14g2000cwz.googlegroups.com> Message-ID: On Feb 12, 2006, at 16:11, Steven D'Aprano wrote: > availability of skilled programmers is absolutely critical for the use > of a language. By that measure, we should all be using Java, no? "TIOBE Programming Community Index" http://www.tiobe.com/tpci.htm > By comparison, even Forth gives 13 million plus hits, and who uses > Forth? Anyone writing in English: http://www.answers.com/forth&r=67 > Lua appears to be *too* lightweight, without even classes or > inheritance, Programming in Lua Object-Oriented Programming http://www.lua.org/pil/16.html > and a single data type where Python has dicts, sets, tuples and lists. "Lua gives you the power; you build the mechanisms." -- Roberto Ierusalimschy, "Programming in Lua", December 2003 http://www.lua.org/pil/12.1.2.html Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From peter.maas at somewhere.com Thu Feb 9 15:34:54 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Thu, 09 Feb 2006 21:34:54 +0100 Subject: What editor shall I use? In-Reply-To: <1139410110.389122.215400@z14g2000cwz.googlegroups.com> References: <1139410110.389122.215400@z14g2000cwz.googlegroups.com> Message-ID: Lad schrieb: > What editor shall I use if my Python script must contain utf-8 > characters? > I use XP An extremely capable, easy to use and small editor is Neil Hodgson's SciTE. It's my favorite editor on Windows and Linux. There is a Windows installer at http://users.hfx.eastlink.ca/~gisdev/scite-1.67-setup-3.exe Peter Maas, Aachen From erniedude at gmail.com Wed Feb 1 10:29:00 2006 From: erniedude at gmail.com (Ernesto) Date: 1 Feb 2006 07:29:00 -0800 Subject: Capture Windows command line output - put in text file In-Reply-To: <1138805834.790265.93130@g44g2000cwa.googlegroups.com> References: <1138805834.790265.93130@g44g2000cwa.googlegroups.com> Message-ID: <1138807740.494115.55260@g43g2000cwa.googlegroups.com> Ernesto wrote: > I'm looking for a way to capture command line output from a cmd > session. Is there a way to use python to launch the application from > the beggining.... then stream all of the output to a text file ? Nevermind. This is a telnet question. I'm trying to get telnet localhost output to a text file. From apardon at forel.vub.ac.be Wed Feb 8 09:23:19 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 8 Feb 2006 14:23:19 GMT Subject: module with __call__ defined is not callable? References: <1139394463.255902.168960@f14g2000cwb.googlegroups.com> <1139401113.301377.21520@g47g2000cwa.googlegroups.com> Message-ID: Op 2006-02-08, Steve Holden schreef : > Fuzzyman wrote: >> Steve Holden wrote: > [...] >>> >>>The pursuit of orthogonality, while admirable, can lead to insanity if >>>pushed too far. >>> >> >> >> Sure - feel free to venture as far down the road of insanity as you >> like :-) To pursue your analogy, why don't we answer all usenet posts >> by pushing suggestions to ridiculous levels ? ;-) >> > Right, and publish cartoons of Larry Wall where his hat is a bomb. Then > the perlmongers will burn the Googleplex down? > >> What would actually be the problem with allowing modules to define a >> __call__ though ? This would allow for nice clean namespaces at the >> module level. >> > What's clean about defining __call__() and calling the module name > rather than defining functions and calling them? The same question can be asked about classes? What's clean about defining a __call__() method and calling the instance name rather than defining methods and calling them? > Why should one specific > function in a module be promoted to this special status? How many > modules have precisely one function? For the same reason they are already promoted special status in classes. Python promotes duck typing so why shouldn't special functions of modules be treated the same as special methods? -- Antoon Pardon From finite.automaton at gmail.com Fri Feb 10 15:03:16 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 10 Feb 2006 12:03:16 -0800 Subject: is there a better way? In-Reply-To: <1139594221.696053.7360@g47g2000cwa.googlegroups.com> References: <1139594221.696053.7360@g47g2000cwa.googlegroups.com> Message-ID: <1139599489.308928.54190@g44g2000cwa.googlegroups.com> everybody is making this way more complicated than it needs to be. storage = list[:list.index(O)] incidentally, "list" is the name of a type, so you might want to avoid using it as a variable name. From reply.in.the.newsgroup at my.address.is.invalid Sun Feb 19 15:33:59 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sun, 19 Feb 2006 21:33:59 +0100 Subject: editor for Python on Linux References: Message-ID: Mladen Adamovic: >I wonder which editor or IDE you can recommend me for writing Python >programs. vi -- Ren? Pijlman From bblais at bryant.edu Thu Feb 16 21:44:26 2006 From: bblais at bryant.edu (Brian Blais) Date: Thu, 16 Feb 2006 21:44:26 -0500 Subject: calculating on matrix indices In-Reply-To: References: Message-ID: <43F5388A.7010905@bryant.edu> Colin J. Williams wrote: > Brian Blais wrote: >> In my attempt to learn python, migrating from matlab, I have the >> following problem. Here is what I want to do, (with the wrong syntax): >> >> from numpy import * >> >> t=arange(0,20,.1) >> x=zeros(len(t),'f') >> >> idx=(t>5) # <---this produces a Boolean array, probably not what you want. >> tau=5 >> x[idx]=exp(-t[idx]/tau) # <---this line is wrong (gives a TypeError) >> > What are you trying to do? It is most unlikely that you need Boolean > values in x[idx] > in this example, as in many that I would do in matlab, I want to replace part of a vector with values from another vector. In this case, I want x to be zero from t=0 to 5, and then have a value of exp(-t/tau) for t>5. I could do it with an explicit for-loop, but that would be both inefficient and unpython-like. For those who know matlab, what I am doing here is: t=0:.1:20; idx=find(t>5); tau=5; x=zeros(size(t)); x(idx)=exp(-t(idx)/tau) is that clearer? I am sure there is a nice method to do this in python, but I haven't found it in the python or numpy docs. thanks, bb -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From xavier.morel at masklinn.net Sun Feb 5 12:20:43 2006 From: xavier.morel at masklinn.net (Xavier Morel) Date: Sun, 05 Feb 2006 18:20:43 +0100 Subject: Learning Python In-Reply-To: <1139158796.288778.244000@z14g2000cwz.googlegroups.com> References: <1139154754.099716.71300@f14g2000cwb.googlegroups.com> <1139156577.897100.69140@g43g2000cwa.googlegroups.com> <1139158796.288778.244000@z14g2000cwz.googlegroups.com> Message-ID: Byte wrote: > http://docs.python.org/tut/node6.html#SECTION006100000000000000000 > --> >>> x = int(raw_input("Please enter an integer: ")) <-- Unless my eyes fail me, it's written "int", not "input", the goal of this line is to convert the return value of raw_input (a string) into an integer. From steve at REMOVETHIScyber.com.au Wed Feb 15 07:06:42 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 15 Feb 2006 23:06:42 +1100 Subject: processing limitation in Python References: <1139935358.128826.58660@g14g2000cwa.googlegroups.com> Message-ID: On Wed, 15 Feb 2006 10:16:07 +0000, Dennis Lee Bieber wrote: > Why bother collecting the "factors" into a list only to print them > at the bottom of the procedure -- you aren't returning a value from > factor(), so I'd suggest dropping the > factors = [] > and > print factors > > replace > factors.append(d) > with > print d #optional , if you want as many on a line as possible This is generally bad practice. You now have a function which can't easily feed its output into any other function (without pipes, file redirection and other tricks). The function is now locked down into one rather limited use: printing the factors. If you need the factors one at a time, the right way is to use a generator, and yield them as they are found. Otherwise, the correct way to solve this problem is to accumulate all the factors in a list and return the list. > Among other things, besides not needing memory to store the entire > list, you also get to see it working as each one is found and printed. The amount of memory needed to store the entire list is trivial for all but the hugest numbers. A number with 1,000 factors would be enormous, and yet the memory needed for a list of 1,000 ints could be as small as 8K -- trivial on modern computers. -- Steven. From zelova at gmail.com Mon Feb 20 08:55:28 2006 From: zelova at gmail.com (zelova) Date: 20 Feb 2006 05:55:28 -0800 Subject: editor for Python on Linux In-Reply-To: References: Message-ID: <1140443728.132362.182870@z14g2000cwz.googlegroups.com> It was said that Boa is good, but I prefer SPE. WingIDE is good but commercial, I tried it but didn't buy. From tomkori at gmx.net Thu Feb 2 05:07:57 2006 From: tomkori at gmx.net (Thomas Korimort) Date: Thu, 02 Feb 2006 11:07:57 +0100 Subject: Fatal Python error: Py_EndInterpreter: thread still has a frame Message-ID: <43e1d9fd$0$1224$91cee783@newsreader01.highway.telekom.at> Hi! Does anyone know the precise circumstances when the error "Fatal Python error: Py_EndInterpreter: thread still has a frame" does occur. I checked the source code of pythonrun.c, which tells me that this error message is thrown in Py_EndInterpreter, when thread->frame is checked for being NULL. Does anyone know, when this pointer is not NULL at the time where Py_EndInterpreter() is called? Greetings, Thomas Korimort. From deets at nospam.web.de Tue Feb 14 05:10:01 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 14 Feb 2006 11:10:01 +0100 Subject: 88k regex = RuntimeError References: <1139900873.361930.135880@g44g2000cwa.googlegroups.com> Message-ID: <45dol6F67rg1U1@uni-berlin.de> > I assume it's hitting some limit, but don't know where the limit is to > remove it. I tried stepping into it repeatedly with Komodo, but didn't > see the problem. That's because it is buried in the C-library that is the actual implementation. There has been a discussion about this a few weeks ago - and AFAIK there isn't much you can do about that. > Suggestions? Yes. Don't do it :) After all, what you do is nothing but a simple word-search. If I had that problem, my naive approach would be to simply tokenize the sources and look for the words in them being part of your function-name-set. A bit of statekeeping to keep track of the position, and you're done. Check out pyparsing, it might help you doing the tokenization. I admit that the apparent ease of the regular expression would have lured me into the same trap. Diez From timr at probo.com Wed Feb 1 02:59:37 2006 From: timr at probo.com (Tim Roberts) Date: Wed, 01 Feb 2006 07:59:37 GMT Subject: simple perl program in python gives errors References: <1138639924.500376.208600@z14g2000cwz.googlegroups.com> <43df635b_1@news.bluewin.ch> Message-ID: <0jq0u1diherpq56ve06m1iu7qqovgp518u@4ax.com> Dan Lowe wrote: > >Not sure if you typo'd that, but that should read: > >a += 200000 * 140000 >print a Did you try to run that? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From techiepundit at futurepundit.com Wed Feb 1 09:57:34 2006 From: techiepundit at futurepundit.com (Randall Parker) Date: 1 Feb 2006 06:57:34 -0800 Subject: Python vs C for a mail server In-Reply-To: References: <1138728303.669646.36940@g49g2000cwa.googlegroups.com> Message-ID: <1138805854.533303.279610@g49g2000cwa.googlegroups.com> Magnus Lycka wrote: > Randall Parker wrote: > > Also, compile time errors get caught sooner. They get caught before > > tests even get written. > > Not if you do Test Driven Tevelopment. Then you write > the tests before you compile your target code! It's > also my experience that the write test - write code > - run test cycle in TDD with Python is often faster > than the plain edit - compile cycle in C++. More > extensive tests take longer, but so does linking of > C++ code... Magnus, I see a problem with your argument: On the one hand you say that Python's lack of type declarations can be compensated for by Test Driven Development. But then you say Python has a bigger advantage in situations where requirements are not well defined. Well, when requirements are in flux and being explored during development it is a waste of time to write tests to test against nebulous requirements. TDD and poor requirements don't mix very well. As for changing argument types: But this is exactly the sort of situation where I find myself getting into trouble in Python. I have to change some type and I forget everywhere I've passed it or returned it. In C++ if I make changes the compiler is going to keep complaining and pointing out type clashes I've introduced due to changing a variable's type. Granted, it is a pain to change type declarations. But visiting those places often makes me think thru the ramifications of changes. Also, I've been on projects where the whole purpose of my code has been to test equations and control laws (this was for space probes to places like Eros and Saturn btw). We were certainly doing test driven development in one sense. But the assumption the systems engineers wanted to make was that the algorithms were written correctly in code and that if the system didn't behave correctly then the problem was in the algorithms, not in the code. We therefore were not in a position to do test drive development on the code itself. From http Tue Feb 21 16:07:10 2006 From: http (Paul Rubin) Date: 21 Feb 2006 13:07:10 -0800 Subject: number ranges References: <1139945386.3346.38.camel@pc1.cole.uklinux.net> <43F8D881.5030804@sympatico.ca> <43F97AA8.50005@REMOVEMEcyber.com.au> <3_WdnUP9qr9XRmTenZ2dnUVZ_sydnZ2d@comcast.com> <1hb1umb.wr2hsk1chby86N%aleaxit@yahoo.com> <1hb2uq1.e7kdkt1z0ge4rN%aleaxit@yahoo.com> <43FAD679.2040305@REMOVEMEcyber.com.au> <1hb3o4u.trzcp41f11vxqN%aleaxit@yahoo.com> Message-ID: <7xacckifpd.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > > for i in (1 to 10 by 3): > > print i > > > > should print 1 4 7. > > But that would be an "attractive nuisance" to many other native speakers > like you, who would instinctively think of a closed interval. Maybe > 'upto' rather than 'to', as somebody else suggested, would ease that. I don't think "upto" is any better. Any distinction that might exist between "to" and "upto" doesn't jump out at me. I notice that Haskell uses closed intervals: [1..5] means [1,2,3,4,5]. Is that an error by Haskell's designers? One possibility is that those intervals don't actually get used in ways likely to cause one-off errors. I haven't used Haskell enough to have any sense of this. Here's something ugly but explicit, somewhat Haskell-inspired: (1 .. ) # infinite generator, like Haskell (1 .. < 10) # semi-closed interval: 1,2,3...,9 (1 .. <= 10) # closed interval: 1,2,3...,10 (1,4 .. < 10) # semi-closed: 1,4,7 (1,4, .. <= 10) # closed: 1,4,7,10 This would be horrible for Python though. From webraviteja at gmail.com Fri Feb 17 02:11:53 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 16 Feb 2006 23:11:53 -0800 Subject: web crawler in python or C? In-Reply-To: <1140069412.051298.242150@g44g2000cwa.googlegroups.com> References: <1140069412.051298.242150@g44g2000cwa.googlegroups.com> Message-ID: <1140160313.229734.38170@g44g2000cwa.googlegroups.com> This is following the pattern of your previous post on language choice wrt. writing a mail server. It is very common for beginers to over emphasize performance requirements, size of the executable etc. More is always good. Right? Yes! But at what cost? The rule of thumb for all your Python Vs C questions is ... 1.) Choose Python by default. 2.) If your program is slow, it's your algorithm that you need to check first. Python strictly speaking will be slow because of its dynamism. However, most of whatever is performance critical in Python is already implemented in C. And the speed difference of well written Python programs with properly chosen extensions and algorithms is not far off. 3.) Remember that you can always drop back to C where ever you need to without throwing all of your code. And even if you had to, Python is very valuable as a prototyping tool since it is very agile. You would have figured out what you needed to do by then, that rewriting it in C will only take a fraction of the time compared to if it was written in C directly. Don't even start with asking the question, "is it fast enough?" till you have already written it in Python and it turns out that it is not running fast enough despite correctness of your code. If it does, you can fix it relatively easily. It is easy to write bad code in C and poorly written C code performance is lower than well written Python code performance. Remember Donald Knuth's quote. "Premature optimization is the root of all evil in programming". C is a language intended to be used when you NEED tight control over memory allocation. It has few advantages in other scenarios. Don't abuse it by choosing it by default. From deets at nospam.web.de Thu Feb 23 06:22:45 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 23 Feb 2006 12:22:45 +0100 Subject: cx_Oracle and UTF8 References: <1140628824.353213.278300@o13g2000cwo.googlegroups.com> Message-ID: <465kbtF9bvemU1@uni-berlin.de> Harald Armin Massa wrote: > Hello, > > I am looking for a method to convince cx_Oracle and oracle to encode > it's replies in UTF8. > > For the moment I have to... > > cn=cx_Oracle.connect("user","password", "database") > cs=cn.Cursor() > > cs.execute("select column1, column2, column3 from table") > > for row in cs.fetchall(): > t=[] > for i in range(0,len(row)): > if hasattr(row[i],"encode"): > t.append(row[i].encode("utf8")) > else: > t.append(row[i]) > print t > > Guess I am to much accustomed to postgresql which just allows "set > client_encoding='utf8'... You can do that in Oracle, too. It's called NLS (national language support), and it is like a locale-setting in python/C. I'm too lazy to google right now, but you should be able to alter the current connection's session to deliver strings in whatever encoding is supportde (utf-8 being amongst these). Diez From bonono at gmail.com Fri Feb 24 05:02:02 2006 From: bonono at gmail.com (bonono at gmail.com) Date: 24 Feb 2006 02:02:02 -0800 Subject: A C-like if statement In-Reply-To: References: <1140742149.011750.321530@z34g2000cwc.googlegroups.com> Message-ID: <1140775322.788083.256970@v46g2000cwv.googlegroups.com> Steven D'Aprano wrote: > On Thu, 23 Feb 2006 16:49:09 -0800, bonono wrote: > > > > > Steven D'Aprano wrote: > >> On Thu, 23 Feb 2006 12:04:38 -0700, Bob Greschke wrote: > >> > >> >> try: > >> >> i = a.find("3") > >> >> print "It's here: ", i > >> >> except NotFound: > >> >> print "No 3's here" > >> > > >> > Nuts. I guess you're right. It wouldn't be proper. Things are added or > >> > proposed every day for Python that I can't even pronounce, but a simple 'if > >> > (I = a.find("3")) != -1' isn't allowed. Huh. It might be time to go back > >> > to BASIC. :) > >> > >> There are *reasons* why Python discourages functions with side-effects. > >> Side-effects make your code hard to test and harder to debug. > >> > > > >>>> "test".index("a") > > Traceback (most recent call last): > > File "", line 1, in -toplevel- > > "test".index("a") > > ValueError: substring not found > >>>> "test".find("a") > > -1 > > > Did you have a point? > It was about your side-effect talk, if you failed to see it, that is fine. BTW, it seems that the term side-effect of function used is a bit different from my understanding of how it is in general used in this field. From peter at engcorp.com Thu Feb 23 19:06:18 2006 From: peter at engcorp.com (Peter Hansen) Date: Thu, 23 Feb 2006 19:06:18 -0500 Subject: time.sleep(1) sometimes runs for 200 seconds under windows In-Reply-To: References: Message-ID: Paul Probert wrote: > Peter Hansen wrote: >>Are you saying that you believe the time.sleep(1) call is actually >>blocking for 200 seconds? Or just that your loop (and we can only guess >>what it looks like) is the one taking that long? > > Yes, I'm doing this: > ..... > oldtime=time.time() > time.sleep(1) > newtime=time.time() > dt=newtime-oldtime > if dt > 2: > print 'dt=',dt,' time=',time.strftime('%Y_%m_%d_%Hh_%Mm_%Ss') > Its happening roughly 4 times a day total on our 20 machines, ie about > once every 5 days on a given machine. So the above is printing "dt=200" or something like that? Or just low values slightly larger than 2s? Or a wide range of values? Can you post samples of the print output for some of those failing runs? -Peter From steve at holdenweb.com Tue Feb 21 10:16:20 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 21 Feb 2006 10:16:20 -0500 Subject: Mutable numbers In-Reply-To: <43fb2462$0$3211$636a55ce@news.free.fr> References: <43fb2462$0$3211$636a55ce@news.free.fr> Message-ID: <43FB2EC4.50201@holdenweb.com> fraca7 wrote: > Suresh Jeevanandam a ?crit : > >># I am new to python. >> >>In python all numbers are immutable. This means there is one object ( a >>region in the memory ) created every time we do an numeric operation. I >>hope there should have been some good reasons why it was designed this way. > > > The memory allocation for integers is optimized. 'Small' integers > (between -5 and 100 IIRC) are allocated once and reused. The memory for > larger integers is allocated once and reused whenever possible, so the > malloc() overhead is negligible. The first bit's right, the second bit isn't: >>> id(12100) 4604168 >>> id(121*100) 4604204 >>> regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From dave.opstad at monotypeimaging.com Mon Feb 20 11:42:51 2006 From: dave.opstad at monotypeimaging.com (Dave Opstad) Date: Mon, 20 Feb 2006 08:42:51 -0800 Subject: Tkinter / Aqua (OS X) question (canvas borders) References: <1140295255.361958.82510@o13g2000cwo.googlegroups.com> Message-ID: In article <1140295255.361958.82510 at o13g2000cwo.googlegroups.com>, "dmsbox2000-list1 at yahoo.com" wrote: > There appears to be an asymmetric "border" > around the inside of the canvas. There was a thread on this last May (you can search for the thread titled "Unusable outer edge of Tkinter canvases?") Fredrik Lundh suggested resetting the coordinate system via: w.xview_moveto(0) w.yview_moveto(0) This seemed to help, but in the end it still seems that there's a narrow border inside the edges of a Canvas which can't be drawn to. And it seems to be different for OS X and Windows. In the end I just made sure everything I draw is no closer than 5 pixels from the edge of the Canvas, and that seems to work on all the platforms I'm deploying on. Dave Opstad From __peter__ at web.de Sun Feb 12 09:48:36 2006 From: __peter__ at web.de (Peter Otten) Date: Sun, 12 Feb 2006 15:48:36 +0100 Subject: breaking from loop References: <1139557074.938577.281250@f14g2000cwb.googlegroups.com> <1139579096.471160.292300@g14g2000cwa.googlegroups.com> Message-ID: Ritesh Raj Sarraf wrote: > def copy_first_match(repository, filename, dest_dir): # aka > walk_tree_copy() > ????for?path,?file?in?files(repository): > ????????if?file?==?filename: > ????????????try: > ????????????????shutil.copy(os.path.join(path,?file),?dest_dir) > ????????????????sys.stdout.write("%s?copied?from?local?cache?%s."?% > (file, repository)) > ????????????except?shutil.Error: > ????????????????sys.stdout.write("%s?is?available?in?%s.?Skipping > Copy!" % (file, dest_dir)) > ????????????return?True > ????return?False > > All I've added is the exception check because in case "file" is > available in "dest_dir", I want to display a message. > Since I'm still new and learning will be great if you let me know if > this is the proper way or not. I prefer to let the exception propagate. As you wrote it, the code calling copy_first_match() has no way of knowing whether a file was copied or not. If you don't want to bother with exceptions in the calling code I'd slightly modify the try...except: try: # copy except (shutil.Error, OSError), e: # print failure message return False I. e. - catch OSError, too. I think shutil.copy() is more likely to raise an OSError than a shutil.Error. - return False if an exception occurs. That way you can test if something went wrong like so: if not copy_first_match(...): print "file not found or unable to copy it" Peter From ian at excess.org Wed Feb 8 17:46:49 2006 From: ian at excess.org (Ian Ward) Date: Wed, 08 Feb 2006 17:46:49 -0500 Subject: Problem with curses and UTF-8 In-Reply-To: <43EA6238.6040004@v.loewis.de> References: <43E9234B.6030108@v.loewis.de> <11ujl0hof3fql62@corp.supernews.com> <43EA6238.6040004@v.loewis.de> Message-ID: <43EA74D9.90902@excess.org> Martin v. L?wis wrote: > If that was Python's configure: don't do that. Instead, hack setup.py > to make it change the compiler/linker settings, or even edit the > compiler/linker line manually at first. Ok, that compiled. Now when I run the same test: import curses s = curses.initscr() s.addstr('\xc3\x85 U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE\n') s.addstr('\xc3\xa5 U+00F5 LATIN SMALL LETTER O WITH TILDE') s.refresh() s.getstr() curses.endwin() This is what I see: +00C5 LATIN CAPITAL LETTER A WITH RING ABOVE +00F5 LATIN SMALL LETTER O WITH TILDE so, the UTF-8 characters didn't appear and the " U" at the beginning became just " ". Ian Ward From kent at kentsjohnson.com Fri Feb 24 08:21:38 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 24 Feb 2006 08:21:38 -0500 Subject: problem(s) with import from parent dir: "from ../brave.py import sir_robin" In-Reply-To: <1140786637.451247.16210@e56g2000cwe.googlegroups.com> References: <1140786637.451247.16210@e56g2000cwe.googlegroups.com> Message-ID: <43ff03d4$1_3@newspeer2.tds.net> per9000 wrote: >>>>from raw2nice_def import raw2nice > ---------- > > When I tried putting this into a program to execute command-line-style: > > from raw2nice_def.py import raw2nice > > output: > >>"C:\another_bridge\python\python.exe" rawhtml2nicehtml_template.py > > ['raw2nice_def.py', 'raw2nice_def.pyc', 'temp'] > Traceback (most recent call last): > File "C:my\holy\grail\that_old_bridge\rawhtml2nicehtml_template.py", > line 10, in ? > from raw2nice_def.py import raw2nice > ImportError: No module named raw2nice_def.py Maybe it will work without the .py extension which is the correct form for an import (and what worked from the command line). Kent From nummertolv at gmail.com Thu Feb 23 10:32:36 2006 From: nummertolv at gmail.com (nummertolv) Date: 23 Feb 2006 07:32:36 -0800 Subject: Using repr() with escape sequences Message-ID: <1140708756.484933.13390@z14g2000cwz.googlegroups.com> Hi, My application is receiving strings, representing windows paths, from an external source. When using these paths, by for instance printing them using str() (print path), the backslashes are naturally interpreted as escape characters. >>> print "d:\thedir" d: hedir The solution is to use repr() instead of str(): >>> print repr("d:\thedir") 'd:\thedir' What I have not been able to figure out is how to handle escape sequences like \a, \b, \f, \v and \{any number} inside the paths. Using repr() on these escape sequences either prints the hex value of the character (if "unprintable" i guess) or some character ( like in the last example below). >>> print repr("d:\thedir\10") 'd:\thedir\x08' >>> print repr("d:\thedir\foo") 'd:\thedir\x0coo' >>> print repr("d:\thedir\100") 'd:\thedir@' Could someone clear this out for me and let me know how I can find the "real" path that I am trying to receive? /Henrik From larry.bates at websafe.com Fri Feb 17 17:46:34 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 17 Feb 2006 16:46:34 -0600 Subject: Does python have an internal data structure with functions imported from a module? In-Reply-To: References: Message-ID: <43F6524A.60202@websafe.com> Carl J. Van Arsdall wrote: > Alright, I attempted to post this question yesterday but I don't see it > as showing up, so I apologize in advance if this is a double post. > > Python Gurus: > > Let me elaborate a bit more on this question. Basically, I want to know > if there is some data structure in python that maps a string function > name to an address of a function or something to that nature. > > If this is confusing, let me describe what I want to do and see if > anyone has any ideas. > > basically we have: > >>>>def functA(): > ... pass > >>>> functA > > > And what I'd like to do is: > >>>>__internalFuncDict__['functA'] > > > This is just for a little experimental project of mine, any help or > pointers to the proper pages in the manual would be greatly > appreciated. Basically, I know that I can create something like this if > I have to but I was very much hoping that something already existed > somewhere that I could get to via python or by writing a C extension. > > Thanks in advance! > > -carl > I would do this as follows: Create dictionary with the function names as keys and the pointer to function definition as value: def printFoo(): print "Foo" return def printFOO(): print "FOO" return fdict={'printFoo': printFoo, 'printFOO': printFOO} functions=('printFoo', 'printFOO') for function in function: if fdict.has_key(function: fdict[function]() else: print "No function named=%s defined" % function -Larry Bates From kent at kentsjohnson.com Thu Feb 9 06:13:50 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 09 Feb 2006 06:13:50 -0500 Subject: module with __call__ defined is not callable? In-Reply-To: References: <43ea0efd$1@nntp0.pdx.net> Message-ID: <43eb1fad$1_3@newspeer2.tds.net> Antoon Pardon wrote: > This make me wonder. Would it be possible to do something with > metaclasses so that after > > class SomeClass(MetaClass): > ... > > SomeClass() will be equivalent to MetaClass.__call__(SomeClass) I think that's already what happens. IIUC type.__call__ implements the standard class creation calling __new__ and __init__. Kent From mrstephengross at hotmail.com Wed Feb 15 12:02:32 2006 From: mrstephengross at hotmail.com (mrstephengross) Date: 15 Feb 2006 09:02:32 -0800 Subject: Embedding a binary file in a python script References: <1140021879.698353.324230@o13g2000cwo.googlegroups.com> Message-ID: <1140022952.353744.323780@g47g2000cwa.googlegroups.com> Ok, this is a neat idea... The uu module deals with files though, not strings. Is there a way in python to make a string act like a file handle? Example: my_string = "uu-encoded-stuf......" my_out_file_handle = ?? # What should this variable look like? import uu uu.decode(my_string, my_out_file_handle) import tarfile tarfile.open(my_out_file_handle) Thanks again, --Steve (mrstephengross at hotmail.com) From claird at lairds.us Sun Feb 19 12:08:26 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 19 Feb 2006 17:08:26 GMT Subject: Python vs. Lisp -- please explain References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> Message-ID: In article , Roy Smith wrote: >DH wrote: >> -python has true closures (although nothing like ruby's blocks) > >What is a "true closure"? Or, maybe what I'm asking is what kind of >closure wouldn't be a true closure? Is there some kind of ersatz closure >other language try to pass off, in violation of truth in closure laws? It's an apt question. What's a "true closure"? That's the easiest part, in some ways: Wikipedia, for example, tells that it's "a function that refers to free variables in its lexical context" , that is the context of the domain of the function's definition. Some languages--Lisp, but also many others--definitely have it. Basic definitely didn't. Tcl ... well, after weeks of discussion , the conclusion was that Tcl almost has as much as it can, given that "lexical context" just doesn't have much standing in Tclonia. So, yes, George Mikan and Allen Iverson both definitely played basketball, and well, but, at the same time, it's useful to distinguish the things they do with a ball. From paul at boddie.org.uk Wed Feb 1 12:45:41 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 1 Feb 2006 09:45:41 -0800 Subject: Python vs C for a mail server References: Message-ID: <1138815941.496813.264030@z14g2000cwz.googlegroups.com> Magnus Lycka wrote: > In C++ it's the opposite. By demanding a particular type, we restrain > ourself to using a set of values which is much smaller than the logic > calls for, or we can throw away all type checks by e.g. casting to void > pointers. The main reason for evading the type system in such a severe fashion in C++ is to break out of class hierarchies (noting that downcasting is achievable in a slightly safer fashion). Ideally, one would design class hierarchies in such a way that such break-outs are avoided, but this can involve a lot of argument/discussion about design/architecture that is mostly unnecessary with Python. > I don't have enough experience with languages that provide interfaces, > such as Java, to understand how useful they are, but it's my impression > that they are too cumbersome to use fully. My experience is the opposite: if one follows the recommended practices with Java, the flavour of object-orientation employed is more interface-oriented than anything else. Ages ago, there was a trend towards describing class relationships using conformance rather than inheritance; that there's still an incentive to rely more on inheritance in Python-based systems has a lot to do with Python's arguably better support for inheritance than Java, that doing away with multiple inheritance in Java forced people to look at other ways to model their information, and that conformance is typically dynamic and implicit in Python anyway. > As far as I understand, most Java APIs use types more than interfaces > for parameters and return values. (I browsed the Java API docs at java.sun.com, > and as far as I see, it seems the APIs always require parameters of distinct > classes or types, and return values of particular types or classes.) I can't comment on "most Java APIs", but if you look at established packages like java.io and java.util, both are heavy on interface usage. > I know that there have been attempts to provide interfaces in Python, > and it seems Zope Interfaces are getting a decent following, but > I don't think anyting like that will ever take the place that type > declarations of all function and class declarations have in e.g. > C++. It's too difficult to make interfaces so convenient and > flexible that they could be used generally in Python without taking > away a lot of power. Generally, interfaces provide a fairly convenient means of expressing the capabilities of objects whilst providing information that can be useful, in conjunction with a suitably designed runtime environment, in the generation of fairly well-optimised code. In a sense, what you say about "taking away a lot of power" is highly appropriate: by imposing an interface system on Python, it's quite likely that one could gain performance and a certain measure of predictability whilst losing certain dynamic aspects of the language. I personally wonder whether it's worth speculatively imposing such prescriptive measures whose burden is on the programmer and where the programmer is likely to spend a lot of time trying to work around them. Paul From peter at engcorp.com Sun Feb 5 15:04:32 2006 From: peter at engcorp.com (Peter Hansen) Date: Sun, 05 Feb 2006 15:04:32 -0500 Subject: translating PHP to Python In-Reply-To: <1139167762.095956.180350@g14g2000cwa.googlegroups.com> References: <1139164228.608430.13120@g44g2000cwa.googlegroups.com> <6ErFf.3267$MJ.1302@fed1read07> <1139167762.095956.180350@g14g2000cwa.googlegroups.com> Message-ID: Dave wrote: > The second point won't work, though, because by parent class I mean, > simply, the object that created the current object, *not* the class the > current class is based on. Good you clarified that, because "parent" definitely isn't used that way by most other people here. And, in fact, there's no requirement that an instance (object) be involved in creating a new object. Python allows functions that are not methods in a class. What would you expect to happen if a mere function was doing the creating? > So, for example: > > class A(object): > def __init__(self): > self.thing = Thing() > self.thing.meth() > > def do_stuff(self): > print "Stuff" > > class Thing(object): > def meth(self): > #now here's what I WANT > self.parent.do_stuff(args) > > Is there a built in way to do this in Python, or do I have to pass > "parent" when I init Thing? It's pretty much standard to pass in references to the caller, or perhaps even more standard to pass in a callable, often in the form of a a "bound method" when an object's method is doing the calling. On the other hand, what you are showing here is something that *would* normally be done with subclassing, and therefore with a parent class involved (using the conventional meaning of "parent"). class A(object): def __init__(self): self.do_stuff() class Thing(A): def do_stuff(self): print "Stuff" But since this was a contrived example, I can't really tell what would work best for you in your real use case. -Peter From tuvas21 at gmail.com Sun Feb 5 22:50:50 2006 From: tuvas21 at gmail.com (Tuvas) Date: 5 Feb 2006 19:50:50 -0800 Subject: Thread imbalance In-Reply-To: References: <1138912272.382474.13170@g44g2000cwa.googlegroups.com> Message-ID: <1139197849.994966.150810@z14g2000cwz.googlegroups.com> The stuff that it runs aren't heavily processor intensive, but rather consistant. It's looking to read incoming data. For some reason when it does this, it won't execute other threads until it's done. Hmmm. Perhaps I'll just have to work on a custom read function that doesn't depend so much on processing power. From jendroska at psychologie.uni-wuerzburg.de Mon Feb 20 07:29:24 2006 From: jendroska at psychologie.uni-wuerzburg.de (Dirk Jendroska) Date: Mon, 20 Feb 2006 13:29:24 +0100 Subject: Scientific Survey: Working Conditions in Open Source Projects Message-ID: <43F9B624.80907@psychologie.uni-wuerzburg.de> We like to invite you to a survey about the working conditions in Free/Open-Source Software development. This survey is conducted by the Open-Source Research Group of the University of W?rzburg (Germany). We will compare work design in open source and proprietary software development. Our findings should be used to adjust the working conditions of software development to the needs of the developers. The results will be published under the Creative Commons License. To start the survey, please click on the following link: http://www.unipark.de/uc/open-source-task/ If you have any questions don't hesitate to contact us! Dirk Jendroska http://wy2x05.psychologie.uni-wuerzburg.de/ao/staff/jendroska.php?lang=en From simon at brunningonline.net Wed Feb 15 09:52:39 2006 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 15 Feb 2006 14:52:39 +0000 Subject: low level data types In-Reply-To: <1140005257.773955.32860@g14g2000cwa.googlegroups.com> References: <1140005257.773955.32860@g14g2000cwa.googlegroups.com> Message-ID: <8c7f10c60602150652u14c64dcs49e0c11a65c6ec76@mail.gmail.com> On 15 Feb 2006 04:07:37 -0800, dementrio wrote: > How can I handle low-level data types in Python? > What I want to do is writing an interface to a C daemon which waits for > stuff like unsigned ints on a socket. For example, I need to craft and > decode data structures that look like this: > > 32-bit unsigned int MSG_LENGTH > 32-bit unsigned int MSG_CODE > 64-bit signed int DATA > 32-bit length + utf-8 characters STRING_DATA > etc. > > What's the right way to do this in Python? Look at the struct module. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From Allerdyce.John at gmail.com Sun Feb 26 14:55:54 2006 From: Allerdyce.John at gmail.com (Allerdyce.John at gmail.com) Date: 26 Feb 2006 11:55:54 -0800 Subject: Do I need to convert string to integer in python? Message-ID: <1140983754.000103.104710@i40g2000cwc.googlegroups.com> Do I need to convert string to integer in python? or it will do it for me (since dynamic type)? In my python script, I have this line: x /= 10; when i run it, I get this error: TypeError: unsupported operand type(s) for /=: 'unicode' and 'int' I want to divide x by 10 and assign that value back to x. Thank you. From raims at dot.com Thu Feb 23 04:52:42 2006 From: raims at dot.com (Lawrence Oluyede) Date: Thu, 23 Feb 2006 10:52:42 +0100 Subject: PyAtom, a Python module for creating Atom syndication feeds References: <87mzgicute.fsf@voodoo.myself> Message-ID: <87hd6qcsgl.fsf@voodoo.myself> "Steve R. Hastings" writes: > Why do you say this? I don't think the code is perfectly polished and > ready to be called version 1.0, but I think it follows PEP 8 more than not. docstrings of method are messed up (why you begin them from the column 0?) and " Function Names Function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility. " you use ThisCase for methods, quit ugly IMHO -- Lawrence - http://www.oluyede.org/blog "Anyone can freely use whatever he wants but the light at the end of the tunnel for most of his problems is Python" From mackstevenson at hotmail.com Sun Feb 5 12:10:04 2006 From: mackstevenson at hotmail.com (MackS) Date: 5 Feb 2006 09:10:04 -0800 Subject: how to kill a python process? Message-ID: <1139159404.912421.251960@g43g2000cwa.googlegroups.com> Hello! This question does not concern programming in python, but how to manage python processes. Is there a way to "name" a python process? At least on Linux, if I have two python programs running, they both run under the name "python" #pidof program1.py [empty line] #pidof program1.py [empty line] # pidof python 1249 854 Is there a way to make them run under their own names, e.g., to make it easier to kill them by name using killall? Or am I stuck with registering the pid of each python process I create and then refer to that list whenever I need to selectively stop one of them? The latter makes managing a long list of processes very cumbersome... Thanks for any help! Mack From fredrik at pythonware.com Thu Feb 2 06:03:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 2 Feb 2006 12:03:34 +0100 Subject: No subject References: <001d01c627ad$afc5a930$6692a543@yourrtmejesvbc> <8c7f10c60602020235x861a571ybc879f086b3a9f9f@mail.gmail.com> Message-ID: Simon Brunning wrote: >> I just got a new computer and pyton 2.2 is on it and I have never heard of >> it What is is for. > > Python is a programming language. It's (loosely speaking) an > interpreted language - that is to say, any software written in Python > needs the Python software around in order to work. > >> Should I keep it on my puter??????????????? > > Yup. It's probably used by some of the vendor supplied tools, which > will stop working if you remove Python. there's also a FAQ about this: http://www.python.org/doc/faq/installed.html From tzot at sil-tec.gr Tue Feb 14 02:50:42 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Tue, 14 Feb 2006 09:50:42 +0200 Subject: Tracking down memory leaks? References: <1139749861.949765.282310@z14g2000cwz.googlegroups.com> Message-ID: On 12 Feb 2006 05:11:02 -0800, rumours say that "MKoool" might have written: >I have an application with one function called "compute", which given a >filename, goes through that file and performs various statistical >analyses. It uses arrays extensively and loops alot. it prints the >results of it's statistical significance tests to standard out. Since >the compute function returns and I think no variables of global scope >are being used, I would think that when it does, all memory returns >back to the operating system. Would your program work if you substituted collections.deque for the arrays (did you mean array.arrays or lists?)? Please test. >Instead, what I see is that every iteration uses several megs more. >For example, python uses 52 megs when starting out, it goes through >several iterations and I'm suddenly using more than 500 megs of ram. If your algorithms can work with the collections.deque container, can you please check that the memory use pattern changes? >Does anyone have any pointers on how to figure out what I'm doing >wrong? I suspect that you have more than one large arrays (lists?) that continuously grow. It would be useful if you ran your program on a fairly idle machine and had a way to see if the consumed memory seems to be swapped out without being swapped in eventually. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From invalidemail at aerojockey.com Sat Feb 11 12:22:51 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 11 Feb 2006 09:22:51 -0800 Subject: appending to a list via properties In-Reply-To: <1hal7v6.1pa7ijfg3np46N%aleaxit@yahoo.com> References: <1139605443.823899.141260@g47g2000cwa.googlegroups.com> <1139670699.632590.148760@g14g2000cwa.googlegroups.com> <1hal7v6.1pa7ijfg3np46N%aleaxit@yahoo.com> Message-ID: <1139678571.008445.10100@g14g2000cwa.googlegroups.com> Alex Martelli wrote: > Carl Banks wrote: > ... > > > class better_list (list): > > > tail = property(None, list.append) > > > > This is an impressive, spiffy little class. > > Yes, nice use of property. > > > growing_lists = foo,qux > > while some_condition: > > for (s,x) in zip(growing_list,calculate_something()): > > list.append(s,x) > > > > No I don't really recommend it. > > Why not? Seems OK. Maybe simplified to: Well, for this simple case I guess. If you have a lot of lists, or you're trying to write a general multiple list appender, it would be fine. Carl Banks From johnjsal at NOSPAMgmail.com Mon Feb 13 16:35:22 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 13 Feb 2006 21:35:22 GMT Subject: how do you pronounce 'tuple'? In-Reply-To: <0mt1v15ei7tg1mr0oclo703b6c92jr9vb4@4ax.com> References: <0mt1v15ei7tg1mr0oclo703b6c92jr9vb4@4ax.com> Message-ID: Dave Hansen wrote: > I've seen "route" pronounced "rout" or "root" depending on the > background and mood of the speaker I actually came up with a method that I use: "rout" for a verb, "root" for a noun. So Route 66 is Root 66, and routing an army is rOUTing an army. :) From lashkariNO at SPAMworldviz.com Wed Feb 15 16:53:20 2006 From: lashkariNO at SPAMworldviz.com (Farshid Lashkari) Date: Wed, 15 Feb 2006 13:53:20 -0800 Subject: How to import a module with spaces in the name In-Reply-To: References: Message-ID: Gregory Pi?ero wrote: > Let's say I have a module named "Excellent Module.py" ExcellentModule = __import__('Excellent Module') -Farshid From bryce.cooper at gmail.com Thu Feb 16 13:29:52 2006 From: bryce.cooper at gmail.com (Bryce Cooper) Date: Thu, 16 Feb 2006 13:29:52 -0500 Subject: Installing python on lynxOS Message-ID: I'm trying to install python2.4.2 onto lynxOS 4.0.0. with gcc 2.95.3. I was wondering if anyone who has done this before could give me some pointers. I'm currently getting the following error when running make: gcc -o python Module/python.o libpython2.4.a -lsocket -lm called2:ld returned 1 exit status libpython2.4.a(pystate.o):In function 'PyThreadState_New': Python2.4.2/pystate.c:191: undefined reference to '_PyGILState_NoteThreadState' called2:ld returned 1 exit status I checked pystate.c and the function _PyGILState_NoteThreadState is defined in the file, so I'm a bit lost here. -- Bryce -------------- next part -------------- An HTML attachment was scrubbed... URL: From martijn at gamecreators.nl Wed Feb 8 09:45:30 2006 From: martijn at gamecreators.nl (martijn at gamecreators.nl) Date: 8 Feb 2006 06:45:30 -0800 Subject: only a simple xml reader value In-Reply-To: <1139409218.480843.317570@g43g2000cwa.googlegroups.com> References: <1139387993.478950.76410@g44g2000cwa.googlegroups.com> <1139409218.480843.317570@g43g2000cwa.googlegroups.com> Message-ID: <1139409929.944215.203740@z14g2000cwz.googlegroups.com> I'm newbie with that xml stuff. The only thing I must read is the response I get from a EPP server. A response like this: Command completed successfully; ending session c-and-a.eu c-and-a_1 2565100006029999 2005-11-08T14:51:08.929Z OK clientref-12310026 eurid-1589 ---------------- // //Command completed successfully; ending session what is the official/best way to handle/parse such xml response ? Thats maybe a better question From markleeds at verizon.net Mon Feb 27 14:56:35 2006 From: markleeds at verizon.net (MARK LEEDS) Date: Mon, 27 Feb 2006 11:56:35 -0800 Subject: newbie : econometrics in python Message-ID: <000801c63bd7$ea5dc8a0$2f01a8c0@m8d4477f3de884> i've used python in the past but only for data processing, writing to files, midifying files, reading from files. now, my boss wants me to do some econometrics using python. would anyone who has done this ( var, vecm, cointegration, ols, kalman filter whatever ) mind sending me some sample code that i could use as a template. i've spent 2 days, going through numpy, scipy, pytrix etc and i still can't figure it out. thanks. mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From raims at dot.com Sun Feb 26 18:50:03 2006 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 27 Feb 2006 00:50:03 +0100 Subject: SyntaxError: can't assign to a function call References: <1140997057.610226.101220@u72g2000cwu.googlegroups.com> Message-ID: <87psl97k9g.fsf@voodoo.myself> "Fuzzyman" writes: >>>> f() += [4] > SyntaxError: can't assign to function call >>>> It's obvious that that line gives you a syntax error. += is the increment operator overloaded for strings and lists and so on. It changes the lhs in place appending the rhs. In this case the rhs is a function call so... how the compiler knows how to assign to a function call? Do the things easily: - x = f() - x += [4] :) -- Lawrence - http://www.oluyede.org/blog "Anyone can freely use whatever he wants but the light at the end of the tunnel for most of his problems is Python" From collinw at gmail.com Fri Feb 10 12:13:40 2006 From: collinw at gmail.com (Collin Winter) Date: Fri, 10 Feb 2006 18:13:40 +0100 Subject: [ANN] functional 0.5 released Message-ID: <43aa6ff70602100913r6d896f16vef201d5d4099608d@mail.gmail.com> Hello all, I have released version 0.5 of my functional module, a collection of higher-order and functional programming tools for Python. Currently offered are tools for function composition, partial function application, plus flip, foldl, foldr, scanl and scanr functions. Two version of the release are available: one is written in pure Python and aims for maximum readability and portability. The other is coded as a C extension module and is focused on raw performance. Where to get it: ######### functional is available at http://oakwinter.com/code/functional/ and from the Python Package Index at http://cheeseshop.python.org/pypi/functional. Both source tarballs and Python Eggs are available for both the pure Python and C releases. I'm open to user-contributed RPM, Deb or other packagings. Release Notes ######## The biggest news in this release is the addition of the C implementation. Also, a number of functions were removed, as I had unknowingly duplicated a lot of functionality from the itertools module. As always, feedback welcome! Collin Winter From carsten at uniqsys.com Fri Feb 3 13:41:08 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 03 Feb 2006 13:41:08 -0500 Subject: MySQLdb question... using table name as arg In-Reply-To: <%cNEf.19800$sA3.14913@fed1read02> References: <%cNEf.19800$sA3.14913@fed1read02> Message-ID: <1138992068.11050.39.camel@dot.uniqsys.com> On Fri, 2006-02-03 at 13:24, Sean Berry wrote: > I have four tables that all have the same column names (50 in each.) > > I have created an admin program to edit, delete and add records to the > tables and would like to use the table name as a variable in each query so > the code can be used for each of the 4 tables. Usually I would do something > like this by having 1 table with special column to categorize the records as > I am doing with each table, but this specific application requires that I do > it with 4 tables instead. > > To ensure that string are quoted properly without any hassle I use the > execute function like so assuming c is my cursor object... > > c.execute("update tableName set col1 = %s, col2 = %s, col3 = %s, ...", > (val1, val2, val3, ...)) > > But, not I want to do this with a variable tableName. If I add it to the > tuple of parameters in the second arg before val1 and replace tableName with > %s, then the tableName will be quoted in the query, causing an error. > > What is the best (easiest) way for me to accomplish this? I know it may be > a stupid question but I just can't figure it out. As you have discovered, the table name is not allowed to be a parameter. You have to build the query string for the appropriate table, then hand it to execute for filling in the actual parameters: queryString = "update "+tableName+" set col1=%s, col2=%s,..." c.execute(queryString, (val1, val2,...)) HTH, Carsten. From steve at REMOVETHIScyber.com.au Sat Feb 18 20:32:12 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 19 Feb 2006 12:32:12 +1100 Subject: Multiplication optimization References: <1140310118.365847.111120@g14g2000cwa.googlegroups.com> Message-ID: On Sat, 18 Feb 2006 16:48:38 -0800, Paul McGuire wrote: > Does Python's run-time do any optimization of multiplication > operations, like it does for boolean short-cutting? Do you know that these shortcuts are optimizations, or are you just assuming it takes less time to do the comparison than it would for the CPU to blast bits around? I have no idea whether your shortcuts are optimizations or pessimizations. I'm just asking whether you know, or if you are making assumptions. -- Steven. From kay.schluehr at gmx.net Fri Feb 24 09:45:59 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 24 Feb 2006 06:45:59 -0800 Subject: Python vs. Lisp -- please explain In-Reply-To: <87r75uz3wb.fsf@wilson.homeunix.com> References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> <43f8ba1e$0$2895$626a54ce@news.free.fr> <43f8cb3f$0$4225$626a54ce@news.free.fr> <87bqx3glb1.fsf@wilson.homeunix.com> <43f984dc$0$27151$626a54ce@news.free.fr> <873bienwlx.fsf@wilson.homeunix.com> <43fbc788@usenet01.boi.hp.com> <87u0ar3gba.fsf@wilson.homeunix.com> <1140612537.685150.68330@o13g2000cwo.googlegroups.com> <7xu0arbkwd.fsf@ruckus.brouhaha.com> <1140614911.243300.67200@g47g2000cwa.googlegroups.com> <1140617119.964479.200780@g44g2000cwa.googlegroups.com> <1140639827.967115.169180@g44g2000cwa.googlegroups.com> <1140692367.189942.50520@z14g2000cwz.googlegroups.com> <87r75uz3wb.fsf@wilson.homeunix.com> Message-ID: <1140792359.326775.106500@u72g2000cwu.googlegroups.com> Torsten Bronger wrote: > Hall?chen! > > "Paul Boddie" writes: > > > Kay Schluehr wrote: > > > >> I would say yes, it is still "proper Python" in that each RPython > >> program is also a CPython program. > > > > I suppose it depends on which direction you're coming from, in > > that many Python programs just wouldn't be able to run in > > RPython. But then I can understand the convenience of having a > > subset of Python that is executable by CPython, but which can also > > be inspected and processed for other purposes, and whose programs > > maintain their semantics in both situations. > > I'm still afraid of the following scenario: Eventually, people might > regard "RPython plus type declarations" (or something similar) as > first-class Python because it's faster and runs on more > implementations, so they try to stick to it. So effectively you > would have changed Python. I wonder why you believe that it would run on more platforms? This assertion is justifiable with regard of tiny target hardware - but else? I do think that "RPython++" could be a viable replacement for C as a systems programming language BECAUSE it is connected closely to Python. It is a kind of upside-down evolution: a low level language emerges from a more high level language. We currently know only the other side of the story. RPython would just be the common denominator or the language interface. Gilad Bracha suggested optional type systems for dynamic languages[1] but as it seems to me RPython would be a fine candidate for a declarative layer, not Python. > Maybe I misunderstood something because I could not follow all of > Kay's text but I think one should not change Python or create a > look-alike to allow for better implementations. The language should > fit my brain rather than an implementation. It should first of all fit the diversity of a programmers needs. C was never considered as a hostile brother of Python so why should it be Pythons own son? Kay From girodt at gmail.com Mon Feb 13 21:37:23 2006 From: girodt at gmail.com (Thomas Girod) Date: 13 Feb 2006 18:37:23 -0800 Subject: listing attributes Message-ID: <1139884643.749492.221140@g43g2000cwa.googlegroups.com> Hi there. I'm trying to get a list of attributes from a class. The dir() function seems to be convenient, but unfortunately it lists to much - i don't need the methods, neither the built-in variables. In fact, all my variables are referencing to objects of the same type. Can anyone suggest me a way to get this list of variables ? Thanks Thomas From lycka at carmen.se Sun Feb 5 17:24:27 2006 From: lycka at carmen.se (Magnus Lycka) Date: Sun, 05 Feb 2006 23:24:27 +0100 Subject: translating PHP to Python In-Reply-To: References: <1139164228.608430.13120@g44g2000cwa.googlegroups.com> <6ErFf.3267$MJ.1302@fed1read07> <1139167762.095956.180350@g14g2000cwa.googlegroups.com> Message-ID: Peter Hansen wrote: > Good you clarified that, because "parent" definitely isn't used that way > by most other people here. Unless they are coding GUIs? I guess it's pretty common that GUI controls are contained in other controls called parents. At least that's how it's done in wxPython. From fuzzyman at gmail.com Sat Feb 18 08:23:09 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 18 Feb 2006 05:23:09 -0800 Subject: Movable python Trial Version In-Reply-To: References: <1140265482.657543.193060@z14g2000cwz.googlegroups.com> Message-ID: <1140268989.867644.86720@z14g2000cwz.googlegroups.com> Felipe Almeida Lessa wrote: > Em S?b, 2006-02-18 ?s 04:24 -0800, Fuzzyman escreveu: > > It is set to expire on the 22nd May, and displays a nag screen on > > startup. Other than that, it is the full version. Have fun. > > Attached is the cracked version with no expiration limit and my own > bitmap on the startup. Enjoy! > I'm sure it wouldn't be that hard to do. Seriously not worth the effort though. ;-) Fuzzy > > Fuzzyman > > http://www.voidspace.org.uk/python/index.shtml > > Just kidding ;-), > Felipe. > > -- > "Quem excele em empregar a for?a militar subjulga os ex?rcitos dos > outros povos sem travar batalha, toma cidades fortificadas dos outros > povos sem as atacar e destr?i os estados dos outros povos sem lutas > prolongadas. Deve lutar sob o C?u com o prop?sito primordial da > 'preserva??o'. Desse modo suas armas n?o se embotar?o, e os ganhos > poder?o ser preservados. Essa ? a estrat?gia para planejar ofensivas." > > -- Sun Tzu, em "A arte da guerra" From steve at holdenweb.com Wed Feb 15 22:42:30 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 15 Feb 2006 22:42:30 -0500 Subject: urllib, caching In-Reply-To: <1140049993.104394.25290@o13g2000cwo.googlegroups.com> References: <1140049993.104394.25290@o13g2000cwo.googlegroups.com> Message-ID: <43F3F4A6.4020708@holdenweb.com> AndrewJ wrote: > I've got code: > > f= urllib.urlopen("http://www.stuff/nb5.php") ; > > This connects to a page that changes in real time. Works ok, and > retrieves the data the first time. > > But then any subsequent calls all return the same data, even though the > web page itself has changed. > > Is there caching going on here? How do I turn it off ? > You can call urllib.urlcleanup() to clear the cache. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From steve at REMOVETHIScyber.com.au Fri Feb 3 11:36:02 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 04 Feb 2006 03:36:02 +1100 Subject: Another try at Python's selfishness References: <1138918102.863033.298700@o13g2000cwo.googlegroups.com> <1138967463.440194.184710@g49g2000cwa.googlegroups.com> <1ha6a71.10mos5m9evcy8N%aleaxit@yahoo.com> Message-ID: On Fri, 03 Feb 2006 07:40:38 -0800, Alex Martelli wrote: > Steven D'Aprano wrote: > ... >> > Why shouldn't >> > def self.x(): >> > declare two new identifiers ("x" and "self"), too? >> >> Sure, but now the call foo.bar > > "call"? Call? Who said anything about a call? *wink* Okay, poor choice of words. I'm not exactly sure what a better choice would be. Token? Too specific. Maybe it would have been better to just have just said "...but now foo.bar has ...". >> has special meaning inside a def statement >> than elsewhere. Elsewhere, foo.bar is an attribute access, looking up >> attribute bar in foo's namespace. > > or setting it, as in foo.bar=23, Conceptually, both setting and getting an attribute involves a "look up" in the general sense: you need to look up the attribute to get its value, or to find out where to put its value. You are correct (of course!) that foo.bar can either be a get or a set, but I'm doing lots of hand-waving here and I didn't think it was necessary to get bogged down in too much detail. > or setting both names, as in > > import foo.bar Ah, I completely forgot about import. But see below. >> Using your syntax, in a def statement >> foo.bar is a pair of declarations: it declares a name "foo", and it >> declares a second name "bar". > > "declares" isn't really pythonic -- let's talk about binding or setting > names, instead. Yes, you're right, it is a bad habit. Years of Pascal don't die easily. >> This inconsistency is, I think, worse than the implicit use of self. > > I don't think there's any inconsistency in deciding that syntax x.y has > different meanings (as to what gets looked up or bound) in different > contexts, because it already does: mostly "look up y in namespace x", > but in x.y=... it's "bind y in namespace x" Which from my perspective are conceptually two sides of the coin. The model I have is "y" is a label in some namespace x, and you have to (in some sense) look up where "y" should go regardless of whether you are setting the value or getting the value. Do you think this model is so far from the actual behaviour of Python that it is useless? Or is it fair to lump getting and setting attributes/names together? > and in "import x.y" it's > "bind x AND then bind y in namespace y". I assume that's a typo and you mean "bind y in namespace x". But even "import x.y" is conceptually a lookup, equivalent to x.y = __import__("x.y"), with the understanding that x = __import__("x") is automagically run first. [hand-waving, hand-waving, hand-waving... of course imports do a lot more than just setting a name in a namespace] But in all three of: foo.bar = something something = foo.bar import foo.bar the hierarchy goes from left to right, with bar being "inside" foo, for some meaning of inside. The Original Poster's syntax would reverse that, with def foo.bar(x,y) creating parameter foo "inside" method bar. -- Steven. From crutcher at gmail.com Sun Feb 26 13:49:48 2006 From: crutcher at gmail.com (Crutcher) Date: 26 Feb 2006 10:49:48 -0800 Subject: xslt queries in xml to SQL queries In-Reply-To: <1140957244.112245.53620@j33g2000cwa.googlegroups.com> References: <1140931098.472396.50620@i39g2000cwa.googlegroups.com> <1140957244.112245.53620@j33g2000cwa.googlegroups.com> Message-ID: <1140979788.315040.285240@t39g2000cwt.googlegroups.com> > I don't know what it is with comp.lang.python/python-list these days > and the cheap put-downs. Unless you know the person you're responding > to personally, and thus the above counts as some kind of banter, you > would do better to keep the insults to yourself. You are completely right, I was overly familiar. Let me restate my central thesis. 1) It is possible to do what he is asking to do. 2) It requires expert knowledge of XSLT to do it well, and then it would still require a bit of work. 3) There are simpler ways to do it, both using and not using xslt, than this. You could also do something like this: and then do an XPath search for sql-hack nodes, and process them with your python. If you are happy staying on the python ranch, you could even do this: %s' % row[0]) ]]> With this, you find the python sections, and exec them in a context with sql defined to do queries against your db and xml defined to parse the xml you give it, and emit it in place of the python element. > But given the existence of XML database systems, > I don't think the idea of accessing them (or things pretending to be like them) > via XML technologies is outrageous at all. No, not outrageous. But this wasn't about quering XML database systems. This was about implementing something which looked like, but did not act like, XSLT. It's just bad design. From erdewit at d-e-l-e-t-e.zonnet.nl Tue Feb 14 05:50:15 2006 From: erdewit at d-e-l-e-t-e.zonnet.nl (Ewald R. de Wit) Date: Tue, 14 Feb 2006 04:50:15 -0600 Subject: cyclic data structures References: Message-ID: John Salerno wrote: > I'm having some slight trouble understanding exactly why this creates an > infinite loop: > > L = [1, 2] > L.append(L) I tried this with Python 2.3.5 and it handles this tailbiter in a very pleasantly surprising way: >>> l = [ 0, 1 ] >>> l.append( l ) >>> l [0, 1, [...]] >>> l[2] [0, 1, [...]] >>> l[2][2][2][2][2][2][2][0] 1 The [...] I have never seen before anywhere, is it documented? -- -- Ewald From fredrik at pythonware.com Fri Feb 3 06:46:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 3 Feb 2006 12:46:07 +0100 Subject: would it be feasable to write python DJing software References: <1138925819.465108.181760@o13g2000cwo.googlegroups.com><1138962918.427815.70300@g14g2000cwa.googlegroups.com><1138966084.385205.254410@g14g2000cwa.googlegroups.com> Message-ID: Ivan Voras wrote: > > Come to that, you're **really** doing it in machine code... > > I've yet to see someone calling > > if a == '5': > print "it's 5" > > machine code. It's the distinction on which level the program's logic is > implemented, not at which level it's executed. uhuh? so why did you just argue that if foo.bar(): bar.aba() means "doing it in C" if bar and aba happens to be parts of an extension library ? From hinnc at yahoo.com Thu Feb 9 15:45:59 2006 From: hinnc at yahoo.com (slogging_away) Date: 9 Feb 2006 12:45:59 -0800 Subject: Too Many if Statements? References: <1139330447.716190.247940@z14g2000cwz.googlegroups.com> <6e2iu1hdb8fvlfkcuulloiiq1khlbhret1@4ax.com> Message-ID: <1139517959.741090.28560@g14g2000cwa.googlegroups.com> It appears it may not be a 'if' statment limitation at all. This is because I added another 800 element array in which to store the various error messages generated when a configuration file error is deteceted based on their severity level. The simple addition of the array caused the same symptom stated in the initial posting. This additional array was removed and the script performs as expected. Adding it back in cause it to not run - no error message - just a return to the >>> in the IDLE console window much as if I had executed the 'Check Module' command. At this point I guess I'll find another way work around this issue via some of the previously suggested methods , etc. It appears to be a bug as far as I can tell. From physci at gmail.com Sun Feb 26 17:40:56 2006 From: physci at gmail.com (physci at gmail.com) Date: 26 Feb 2006 14:40:56 -0800 Subject: wxGlade, wxPython.... pyOpenGL wxWidget? Message-ID: <1140993655.993069.196880@u72g2000cwu.googlegroups.com> I've been combing google for the past week trying to find an appropriate set of tools for a project I'm working on. Simply put, what I need is a GUI, powered by python, (I really don't want to touch any C++ code at all), that has an openGL canvas/scene(?), with a python interpreter sitting beside it. The whole thing should be resizable, and the display (not full screen) should be commanded by user interaction with the interpreter (like the boa-constructor interpreter), where the whole app resides in one window. What would be ideal for me is an "OpenGL wxWidget(?)" that can be imported into wxGlade or Boa. ((Qt has a thing called glViewer (Which I got really excited about, but can't find a way for python to talk with it))) note: This should be cross-platform, MacOSX / Windows / Linux. I feel bad posting this because there is already so much discussion on the topic, however my brain is trying to escape, and I could only appease it by sending this missive. From hancock at anansispaceworks.com Tue Feb 21 14:20:56 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 21 Feb 2006 13:20:56 -0600 Subject: Augmented assignment In-Reply-To: References: Message-ID: <20060221132056.62470312@samwise.anansi> On Tue, 21 Feb 2006 10:55:42 +0530 Suresh Jeevanandam wrote: > Is there any gain in performance because of > augmented assignments. > > x += 1 vs x = x+1 Yep. I perform better when I only type names once. Especially if they are long: length_of_object_I_must_describe_very_carefully += 1 vs length_of_object_I_must_describe_very_carefully = length_of_object_I_must_describe_very_carefully + 1 Oh, you mean performance of the computer? ;-) But Python is all about optimizing the performance of programmers, not computers! Seriously, I think they are usually equivalent internally, at least for immutable objects. -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From grflanagan at yahoo.co.uk Sun Feb 26 17:36:48 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 26 Feb 2006 14:36:48 -0800 Subject: TypeError when subclassing 'list' In-Reply-To: References: <1140992122.723907.263990@z34g2000cwc.googlegroups.com> Message-ID: <1140993408.020744.250760@i39g2000cwa.googlegroups.com> Steve Juranich wrote: > Gerard Flanagan wrote: > > > Hello all > > > > Could anyone shed any light on the following Exception? The code which > > caused it is below. Uncommenting the 'super' call in 'XmlNode' gives > > the same error. If I make XmlNode a subclass of 'object' rather than > > 'list' then the code will run. > ... > > Code: > > > > from elementtree.SimpleXMLWriter import XMLWriter > > > > class XmlNode(list): > > tag = None > > attrib = None > > value = None > > def __init__(self, tag, **attrib): > > #super(list, self).__init__() > > self.tag = tag > > self.attrib = attrib > > I haven't put a lot of study into what you've done, but right off the bat, > your use of "super" is incorrect. It should look like: > > super(XmlNode, self).__init__() > > Not sure if that will fix your problem, though. > > -- > Steve Juranich > Tucson, AZ > USA Thanks Steve, but no - same error. Gerard From deets at nospam.web.de Sun Feb 26 15:36:48 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 26 Feb 2006 21:36:48 +0100 Subject: How can I find the remainder when dividing 2 integers In-Reply-To: <1140985687.324979.153730@e56g2000cwe.googlegroups.com> References: <1140984473.723258.70050@e56g2000cwe.googlegroups.com> <46egiuFanujjU2@uni-berlin.de> <1140985687.324979.153730@e56g2000cwe.googlegroups.com> Message-ID: <46ehr1FarmcsU1@uni-berlin.de> silverburgh.meryl at gmail.com schrieb: > okay, I try you suggestion, and re-write my code like this: > colors = ["#ff0000", "#00FF00", "#0000FF"] > colorIndex = 0 > > def getText(nodelist): > > > for str in strings: > > print colors[colorIndex % colors.length] > colorIndex += 1 > > but i get this error: > print colors[colorIndex % colors.length] > UnboundLocalError: local variable 'colorIndex' referenced before > assignment If I take your code, it works for me. Diez From bronger at physik.rwth-aachen.de Fri Feb 17 11:57:16 2006 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 17 Feb 2006 17:57:16 +0100 Subject: Evil, evil wxPython (and a glimmer of hope) References: <1140116551.116322.12680@g43g2000cwa.googlegroups.com> <8764ned5ib.fsf@rose.polar.local> <1140162638.200378.199010@g44g2000cwa.googlegroups.com> <1140174946.948658.186160@g47g2000cwa.googlegroups.com> <1140180680.326797.69740@g43g2000cwa.googlegroups.com> <1140189486.898380.245900@g14g2000cwa.googlegroups.com> <1140195001.515958.292420@g14g2000cwa.googlegroups.com> Message-ID: <87vevdsz2r.fsf@wilson.homeunix.com> Hall?chen! "Fuzzyman" writes: > vivainio at gmail.com wrote: > >> vivainio at gmail.com wrote: >> >> [...] >> >> Ok, after brief eyeballing & experimenting, it appears that Wax >> is just what I was looking for. The code is simple, concise and >> trivially understandable, the level of wrapping seems about >> right, and examples are helpful. >> >> [...] > > That's good news. I'm about to start using Wax on a couple of > small(ish) projects - so it's nice to know about other users. Has Wax exceeded the critical mass so that one can be quite certain that it will still be maintained, say, next year? (Sincere question since I don't know.) Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus ICQ 264-296-646 From sybrenUSE at YOURthirdtower.com.imagination Tue Feb 14 04:32:34 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 14 Feb 2006 10:32:34 +0100 Subject: Python / Apache / MySQL References: <1139907519.427789.188760@g14g2000cwa.googlegroups.com> Message-ID: vpr enlightened us with: > I want to build an Website using Apache / Python and MySQL. I second Bruno: swap MySQL in favour of PostgreSQL. > e.g. should I be using mod_python ? You could use my framework based on mod_python and Cheetah. I find it really easy to use. Check out http://www.unrealtower.org/webengine > whats the best module for mysql ? I'd use SQLObject. It can handle MySQL (if you really want to stick to it), SQLite and PostgreSQL. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From klachemin at comcast.net Wed Feb 1 17:41:05 2006 From: klachemin at comcast.net (Kamilche) Date: 1 Feb 2006 14:41:05 -0800 Subject: PIL and transparent GIFs In-Reply-To: <43e12849$0$1145$7a628cd7@news.club-internet.fr> References: <43e12849$0$1145$7a628cd7@news.club-internet.fr> Message-ID: <1138833665.400460.232350@f14g2000cwb.googlegroups.com> It can only read transparency, it can't write it. I went looking and found that out a couple weeks ago. From felipe.lessa at gmail.com Sun Feb 12 08:06:29 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 12 Feb 2006 11:06:29 -0200 Subject: Is python very slow compared to C In-Reply-To: <1139747631.858424.145230@z14g2000cwz.googlegroups.com> References: <1139690972.344818.136870@f14g2000cwb.googlegroups.com> <1139694723.857673.263750@z14g2000cwz.googlegroups.com> <1139742200.155197.245490@g14g2000cwa.googlegroups.com> <1139743205.985196.254330@g43g2000cwa.googlegroups.com> <1139747631.858424.145230@z14g2000cwz.googlegroups.com> Message-ID: <1139749589.3967.16.camel@kenshin> Em Dom, 2006-02-12 ?s 04:33 -0800, bonono at gmail.com escreveu: > Felipe Almeida Lessa wrote: > > Em Dom, 2006-02-12 ?s 03:20 -0800, bonono at gmail.com escreveu: > > > However, to me, the strength of python is the batteries that is > > > included(and there are more and more coming). > > > > So .NET is as good as Python? Hmmm... I think the language itself is the > > best part of Python, its library is just a complement (a very good and > > relevant one, though). > .NET is not a language, IMO. You talked about "batteries included", and that isn't related to the language. I said .NET in reference to what you said. The part about the language is my own opinion, I just didn't want to say anything about C#, Boo, J#, Nemerle or any other language that targets the .NET framework. In the case of Python, as well as Java, the language has the same name as the framework, and this may have lead you to mistake me. -- "Quem excele em empregar a for?a militar subjulga os ex?rcitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destr?i os estados dos outros povos sem lutas prolongadas. Deve lutar sob o C?u com o prop?sito primordial da 'preserva??o'. Desse modo suas armas n?o se embotar?o, e os ganhos poder?o ser preservados. Essa ? a estrat?gia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" From martin at v.loewis.de Wed Feb 8 14:04:10 2006 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 08 Feb 2006 20:04:10 +0100 Subject: Python 2.4.2 using msvcrt71.dll on Win and compatibility issues In-Reply-To: References: <43E8F864.6050605@v.loewis.de> <43E922D0.4080407@v.loewis.de> Message-ID: <43ea40aa$0$6793$9b622d9e@news.freenet.de> Christoph Zwerschke wrote: > I think this would only shift the problem. Because then I would have to > convert the msvcr71 stream I get from Python to a msvcrt stream. Using > fileno() (of msvcrt) to get the file descriptor will probably not work. It actually would: #define _fileno(_stream) ((_stream)->_file) This definition is the same in all CRT version, plus the _file member is at the same offset in all CRT versions. Microsoft apparently wants to support linkage of object files build with one CRT version against a different CRT version. It *is* hacky, of course. > But thanks a lot for your help. Sometimes you don't know whether you're > doing something terribly wrong or missing a very easy solution if you > don't discuss with others. Right. I come more and more to the conclusion that you shouldn't really be using the CRT on Win32. Anyway, I just proposed to have Python 2.5 link against msvcrt.dll on python-dev, and got mixed responses. Regards, Martin From ziggy at fakedaddress.com Mon Feb 13 20:04:58 2006 From: ziggy at fakedaddress.com (ziggy) Date: Tue, 14 Feb 2006 01:04:58 GMT Subject: Jedit Message-ID: Just wondering if there is something out there like Jedit, but written in python ( not just supporting, but actually written in it.. ) Nothing large like Stanzi's or Boa.. Just something quick and simple, with code completion, and a debugger.. From joel.hedlund at gmail.com Wed Feb 8 05:03:15 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Wed, 08 Feb 2006 11:03:15 +0100 Subject: Best way of finding terminal width/height? In-Reply-To: <11uhodjciifej02@corp.supernews.com> References: <96nFf.43896$d5.199922@newsb.telia.net> <11uc3dohfitotc5@corp.supernews.com> <11udc0r2bq11042@corp.supernews.com> <43E719EE.3040401@gmail.com> <11ueq4nhn91qm91@corp.supernews.com> <43E8659D.6010101@gmail.com> <11uhcjj2p10mm0d@corp.supernews.com> <43E8D4DD.7040904@gmail.com> <11uhodjciifej02@corp.supernews.com> Message-ID: > sys.stdin.read() will return when ... the > underyling read() call is aborted by a signal. Not "return", really? Won't it just pass an exception? I thought that was what I was catching with the "except IOError" part there? I assumed that sys.stdin.read() would only return a value properly at EOF? It looks to me as if sys.stderr.read() really gets an EOF at the final linebreak fed into the terminal prior to window size change, because the final unterminated line shows up on my shell prompt. Like so: $ python winch.py moo moo cow cowmoo moo $ cow cow In this example I type moo moo[ENTER]cow cow on my keyboard and then resize the window. Now that EOF has to come from somewhere (since there's no IOError or other exception, or the program wouldn't terminate nicely with nothing on stderr) and I'd like to point the blame at the terminal. Or is there something really fishy inside sys.stdin.read() or signal that puts EOFs into streams? But anyway, as long as this behavior only shows up on interactive operation, the user will likely spot it anyway and can react to it. So I think this code would be pretty safe to use. What do you think? > Resign the terminal will abort pending I/O operations on > that terminal. It won't terminal I/O operations pending on > other devices/files. What do you mean by "abort"? I can accept that "aborting" may lead to raising of IOError (which we can catch and retry), but not to arbitrary insertion of EOFs into streams (which we cannot distinguish from the real deal coming from the user). Also: try your example and enter moo moo[ENTER]cow cow[RESIZE][ENTER][RESIZE] Thanks again for your help. /Joel > > >>but it does return as soon as I enter more than one >>line of text and then resize the window (one unterminated line >>is ok). >> >>Example text to type in: >>moo moo >>cow cow >> >>As soon as I have typed in something that includes a newline >>charater through the keyboard and try to resize the terminal, >>sys.stdin.read() will return whatever I put in no far and no >>exception raised. > > > Yup. That does indeed appear to be the way it works. :) > > >>Weird. Could it in fact my terminal that's screwing things up >>for me? > > > No. > > Try this out: > > ---------------------------------------------------------------------- > #!/usr/bin/python > import signal, os, sys > > _bTerminalSizeChanged = False > > def report_terminal_size_change(signum, frame): > global _bTerminalSizeChanged > _bTerminalSizeChanged = True > > signal.signal(signal.SIGWINCH, report_terminal_size_change) > > while True: > try: > s = sys.stdin.read() > if not s: > break > sys.stdout.write(s) > except IOError: > sys.stderr.write("IOError\n") > if _bTerminalSizeChanged: > sys.stderr.write("SIGWINCH recevied\n") > _bTerminalSizeChanged = False > ---------------------------------------------------------------------- > > In that example, I handle IOError on write with the same > exception handler as the one for read. That may not be exactly > what you want to do, but it does demonstrate what > window-resizing does. > > When the window is resized, the SIGWINCH handler will be > called. A pending read() may abort with an IOError, or it may > just return some buffered data. > From xavier.morel at masklinn.net Mon Feb 27 08:55:23 2006 From: xavier.morel at masklinn.net (Xavier Morel) Date: Mon, 27 Feb 2006 14:55:23 +0100 Subject: How to do an 'inner join' with dictionaries In-Reply-To: <1141047580.492771.97130@z34g2000cwc.googlegroups.com> References: <1141047580.492771.97130@z34g2000cwc.googlegroups.com> Message-ID: cyborg4 at walla.co.il wrote: > Let's say I have two dictionaries: > dict1 is 1:23, 2:76, 4:56 > dict2 is 23:A, 76:B, 56:C > > How do I get a dictionary that is > 1:A, 2:B, 4:C > >>> dict1 = {1:23,2:76,4:56} >>> dict2 = {23:'A',76:'B',56:'C'} >>> dict((k, dict2[v]) for k, v in dict1.items()) {1: 'A', 2: 'B', 4: 'C'} >>> ? From cvanarsdall at mvista.com Fri Feb 17 16:23:41 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Fri, 17 Feb 2006 13:23:41 -0800 Subject: Does python have an internal data structure with functions imported from a module? Message-ID: <43F63EDD.5070705@mvista.com> Alright, I attempted to post this question yesterday but I don't see it as showing up, so I apologize in advance if this is a double post. Python Gurus: Let me elaborate a bit more on this question. Basically, I want to know if there is some data structure in python that maps a string function name to an address of a function or something to that nature. If this is confusing, let me describe what I want to do and see if anyone has any ideas. basically we have: >>>def functA(): ... pass >>> functA And what I'd like to do is: >>>__internalFuncDict__['functA'] This is just for a little experimental project of mine, any help or pointers to the proper pages in the manual would be greatly appreciated. Basically, I know that I can create something like this if I have to but I was very much hoping that something already existed somewhere that I could get to via python or by writing a C extension. Thanks in advance! -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From siona at chiark.greenend.org.uk Wed Feb 8 08:56:42 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 08 Feb 2006 13:56:42 +0000 (GMT) Subject: apostrophe or double quote? References: <1139370460.360400.232500@z14g2000cwz.googlegroups.com> Message-ID: Steve Holden wrote: >Huy wrote: >> I've been unable to find information clarifying this but. What is the >> difference between 'somestring' and "somestring"? >It's just easier to have two permitted string quotes. That way, if your >string has an apostrophe in it you can say > > s = "it's" > >and if it has a double quote in it you can say > > s = 'The double quote (") rules' > >So there's really no difference at all. You can also use escaping to >achieve the same end: > > s = "The double quote (\") rules" > >if you prefer. Or triple quoting: s = """The double quote (") rules""" I've seen someone around here use 'somestring' for internal values (dict keys and the like) and "somestring" for values being shown to the user, so it's easy(ish) to tell what may need translating or can otherwise safely be changed. I like this convention (provided it remains a convention). -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From bj_666 at gmx.net Fri Feb 17 18:24:59 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 18 Feb 2006 00:24:59 +0100 Subject: How to run shell commands within python References: <1140074469.258382.24620@f14g2000cwb.googlegroups.com> Message-ID: In , Donn Cave wrote: > You can replace "mv" with os.rename() if you don't > care that it will fail when the destination is on a different > filesystem. Etc. If you care than use `shutil.move()` instead. Ciao, Marc 'BlackJack' Rintsch From jeremy+complangpython at jeremysanders.net Tue Feb 28 06:31:40 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 28 Feb 2006 11:31:40 +0000 Subject: Printing a file References: Message-ID: Fabian Steiner wrote: > Unfortunately I don't know how to realize this, since also some images > and different boxes should be printed out. As the whole application is > based on QT, QPrinter might be used, but I couldn't find any examples > how to use it. QPrinter is easy to use. You just draw to the page the same way as you talk to the screen with a QPainter. prnt = qt.QPrinter() # you can also vary options like colour, doc name, dpi here # display dialog box to user (you can actually leave this out) if prnt.setup(): painter = qt.QPainter() painter.begin(printer) # do stuff to draw to painter painter.end(printer) # do this between each page printer.newPage() # ... more pages can be printed to a painter It's very easy to do. If you want to handle multiple pages and so on, there's a bit of work to do to interface to the dialog to get the user-selected page range, etc. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From deets at nospam.web.de Tue Feb 21 04:44:16 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 21 Feb 2006 10:44:16 +0100 Subject: Writing my own typing monitor program for RSI sufferers... In-Reply-To: <1140496915.106258.190830@z14g2000cwz.googlegroups.com> References: <1140491147.433293.164700@g43g2000cwa.googlegroups.com> <1140496915.106258.190830@z14g2000cwz.googlegroups.com> Message-ID: <4605ngF8ctkkU1@uni-berlin.de> samslists at gmail.com schrieb: > So, so close.... The problem with this implementation is that it > doesn't monitor usb keyboards under linux at all as far as I can > tell....since no keyboard entry will show up in /proc/interrupts with a > usb keyboard. I absolutely need the keyboard monitoring as well. > > Otherwise, your project would be the perfect starting point for me! > > Anyone else have an idea as to what I can use with Python to know when > the keyboard is being used even when I don't have focus? If you can wait a few month, I'll be doing that in python based on this: http://www.frogmouth.net/hid-doco/linux-hid.html I'll be doing it for a art-project that is scheduled some months away. But I think the above information even should help you get started on your own. Diez From dakman at gmail.com Thu Feb 9 09:48:19 2006 From: dakman at gmail.com (dakman at gmail.com) Date: 9 Feb 2006 06:48:19 -0800 Subject: CGI Python FTP Message-ID: <1139496499.898773.230240@g44g2000cwa.googlegroups.com> I know PHP has support for uploading files from the browser to the server, but does python (not mod_py) have any modules for going about this? If not post your ideas on how I should do this. Thanks. From steve at holdenweb.com Sat Feb 18 13:28:47 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 18 Feb 2006 13:28:47 -0500 Subject: Another stupid newbie question In-Reply-To: References: <1140203709.145048.314180@g43g2000cwa.googlegroups.com> <1140205868.660418.234980@z14g2000cwz.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Fri, 17 Feb 2006 11:51:08 -0800, Byte wrote: > > >>Great, thanks all. Now, how come >> >> if x == mx: print x >> break >> >>Dosnt work? > > > Do yourself a HUGE favour and read this before posting any more questions > to comp.lang.python. Trust me, you really will thank us. > > http://www.catb.org/~esr/faqs/smart-questions.html > > > If he doesn't lambast us I'll chalk it up as a win :-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From wbaxter at gmail.com Thu Feb 16 22:35:23 2006 From: wbaxter at gmail.com (Bill Baxter) Date: Fri, 17 Feb 2006 12:35:23 +0900 Subject: [Numpy-discussion] Re: calculating on matrix indices In-Reply-To: <43F5388A.7010905@bryant.edu> References: <43F5388A.7010905@bryant.edu> Message-ID: Howdy, On 2/17/06, Brian Blais wrote: > > Colin J. Williams wrote: > > Brian Blais wrote: > >> In my attempt to learn python, migrating from matlab, I have the > >> following problem. Here is what I want to do, (with the wrong syntax): > >> > >> from numpy import * > >> > >> t=arange(0,20,.1) > >> x=zeros(len(t),'f') This was the line causing the type error. t is type double (float64). 'f' makes x be type float32. That causes the assignment below to fail. Replacing that line with x=zeros(len(t),'d') should work. Or the zeros_like() that Travis suggested. >> > >> idx=(t>5) # <---this produces a Boolean array, probably > not what you want. > >> tau=5 > >> x[idx]=exp(-t[idx]/tau) # <---this line is wrong (gives a TypeError) > >> You could also use idx=where(t>5) In place of idx=(t>5) Although in this case it probably doesn't make much difference, where(expr) is more directly equivalent to matlab's find(expr). See http://www.scipy.org/Wiki/NumPy_for_Matlab_Users for more Matlab equivalents. And consider contributing your own, if you have some good ones that aren't there already. --bb -------------- next part -------------- An HTML attachment was scrubbed... URL: From limodou at gmail.com Tue Feb 7 21:51:46 2006 From: limodou at gmail.com (limodou) Date: Wed, 8 Feb 2006 10:51:46 +0800 Subject: module with __call__ defined is not callable? In-Reply-To: <6ab99bf50602071838m2abd3871q@mail.gmail.com> References: <6ab99bf50602071838m2abd3871q@mail.gmail.com> Message-ID: <505f13c0602071851w7b2f6d62yafd703223d1b16b5@mail.gmail.com> On 2/8/06, adam johnson wrote: > Hi All. > I was wondering why defining a __call__ attribute for a module doesn't make > it actually callable. > > I don't have any reason for doing so, I was just wondering if it worked, and > found out it didn't. > > $ cat mod.py > """ > Test callable module > """ > def __call__(): > return "in mod.__call__" > > > >>> import mod > >>> mod() > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'module' object is not callable > >>> mod.__call__() > 'in mod.__call__' > > > Thanks for any replies, Adam. > > I remebered that __call__() is just used for class, but not module. Am I wrong? -- I like python! My Blog: http://www.donews.net/limodou NewEdit Maillist: http://groups.google.com/group/NewEdit From caseyhHAMMER_TIME at istar.ca Wed Feb 22 17:52:00 2006 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Wed, 22 Feb 2006 22:52:00 GMT Subject: May i customize basic operator (such as 1==3)? References: Message-ID: Cannot one subclass the builtin types? I have heard, that one should always use objects when programming and avoid the builtin types! Then one is prepared to change objects at will and not rely on any special properties of the builtin types! Robert Kern wrote: >Casey Hawthorne wrote: >> I believe you are asking for a side effect from the "==" operator. >> >> Add print statements to the __eq__ method. > >The things is, he wants to make those modifications to builtin types, which he >can't do. -- Regards, Casey From stefan.rank at ofai.at Tue Feb 28 08:33:41 2006 From: stefan.rank at ofai.at (Stefan Rank) Date: Tue, 28 Feb 2006 14:33:41 +0100 Subject: PEP 354: Enumerations in Python In-Reply-To: <1141125265.118619.36500@i40g2000cwc.googlegroups.com> References: <87accdplbj.fsf@rose.polar.local> <1141109451.570616.86140@p10g2000cwp.googlegroups.com> <1141125265.118619.36500@i40g2000cwc.googlegroups.com> Message-ID: <44045135.4080007@ofai.at> on 28.02.2006 12:14 Carl Banks said the following: [snip] > >>> It's a pretty weak case to have a dedicated builtin to prevent >>> duplicates in something that changes maybe once a month, as enums tend >>> to change rather slowly. (At least, that's the way enums in other >>> languages are used, and the design you present here seems to suggest >>> you intend to use them that way as well.) And frankly, a unit test or >>> assertion could check this. >> [snip] >> >> I don't understand what you mean by 'change rather slowly'? > > Construct data structure on-the-fly from an XML file edited by multiple > people every day = changes rather quickly > > Construct data structure from a Python file that was last edited a year > and a half ago = changes rather slowly > > Typically, enums fall into the latter category. You set the enum > values, and then pretty much leave them alone, adding new values only > occasionally. (Come on, how often do the days of the week change?) > All I was saying is, changes to the enum values are infrequent enough > that having a special type just to make sure there are no duplicates is > a waste. The only justification for a built-in enum is the other stuff > you mentioned. agreed >> One thing that is probably missing to allow this, is a enum-set-creation >> with the | operator:: >> >> Weekdays = enum('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun') >> daysihate = Weekdays.mon | Weekdays.thu >> >> (and this discussion needs to move to python-dev ?) > > What's wrong with set((Weekdays.mon,Weekdays.thu))? Explicit is better > than implicit. agreed again. the | idea would only be for (interface) backwards compatibility. >> As for the metaclass versions: For myself, the above version feels more >> natural and straightforward (in the same way as the PEP author describes >> it), though I understand the subclassing ideas. >> >> But are there use cases for subclassing, that aren't better served with >> a new enum or something homegrown? >> Can C++/Pascal/Java enums be subclassed? > > In C++, enum is a type but not a class. Same thing with Ada. Java > didn't have enums last time I checked. Don't know about Pascal. Was more of a question for subclassing use cases in other languages. BTW Java has an enum now, which cannot be subclassed either AFAIK. And it's the same for (Delphi) Pascal. > I > didn't care too much about subclassing; I just thought different enum > constant that couldn't (or, rather, oughtn't) be compared probably > should be instances of a separate class. It doesn't matter much, > though. > Should something like this work: > > day = Weekdays.mon > isinstance(day,Weekdays) > > ? I think in the PyPI package `type(Weekdays)` is `Enum` and `type(Weekdays.mon)` is `EnumValue`, so this would not work. But membership testing `if day in Weekdays: ...` could do the same, and type-checking for enum values `isinstance(day, EnumValue)` would work (might be unpythonic though). In the cookbook recipe `enum('..')` is a function and constructs two new types on the fly, so the values of two different enums would be of a different type, but you would not be able to name it easily... cheers From drevil_53711 at yahoo.com Mon Feb 13 14:46:31 2006 From: drevil_53711 at yahoo.com (Steve Young) Date: Mon, 13 Feb 2006 11:46:31 -0800 (PST) Subject: html source Message-ID: <20060213194631.10759.qmail@web36512.mail.mud.yahoo.com> Hi, I was wondering why when I use urllib2.build_opener().open(url), it doesn't give me the same thing as if I would just click on view--> source on my web browser. It gives me most of html on the page but leaves out lots of scripts and some of the link's urls are truncated. Is there something out there in python that gives me EXACTALLY the same thing as if you were to just do view-->source on the web browser? Thanks for the help. -Steve --------------------------------- What are the most popular cars? Find out at Yahoo! Autos -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Thu Feb 23 03:32:56 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 23 Feb 2006 00:32:56 -0800 Subject: streaming Popen.stdout In-Reply-To: <1140536945.936115.59570@z14g2000cwz.googlegroups.com> References: <1140536945.936115.59570@z14g2000cwz.googlegroups.com> Message-ID: <1140683576.371465.210650@z14g2000cwz.googlegroups.com> Replying to myself ... I cooked up this solution involving os.pipe and os.fork, but I am not especially happy with it; anyway, let me write it. Feedback is welcome, since this was written very quickly and I may have missed something. BTW, are there libraries out there doing something similar? ---- import subprocess import os, sys, time class ReadObject(object): def __init__(self, fileno): self.fileno = fileno self._closed = False self.name = str(self) def readline(self): if self._closed : return '' return ''.join(iter(self.read1, '\n')) + '\n' def read(self): return ''.join(iter(self.read1, '\x00')) def read1(self): c = os.read(self.fileno, 1) if c == '\x00': self._closed = True return '\n' else: return c def __iter__(self): return iter(self.readline, '') class WriteObject(object): def __init__(self, fileno): self.fileno = fileno self.name = str(self) def write(self, text): os.write(self.fileno, text) def flush(self): pass def close(self): self.write('\x00') def callproc(child, *args,**kw): "Run the child procedure in a child process" r, w = os.pipe() R, W = ReadObject(r), WriteObject(w) if os.fork(): # parent return R else: # child sys.stdout = W try: child(*args, **kw) finally: W.close() sys.exit() if __name__ == '__main__': for line in callproc(subprocess.call, [sys.executable, 'hello.py']): print line, From invalidemail at aerojockey.com Tue Feb 28 01:50:51 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 27 Feb 2006 22:50:51 -0800 Subject: PEP 354: Enumerations in Python References: <87accdplbj.fsf@rose.polar.local> Message-ID: <1141109451.570616.86140@p10g2000cwp.googlegroups.com> Ben Finney wrote: > This PEP specifies an enumeration data type for Python. -1 for this particular proposal as a builtin. I feel it's not a great design of something that isn't terribly useful to begin with. +0 for the standard library, only after a couple changes. As I see it, this whole proposal is a minor improvement over doing something like the following, but too minor an improvement to add to the builtin namespace: MON = 'mon' TUE = 'tue' etc. DAYS_OF_WEEK = (MON,TUE,etc.) [snip] > It is possible to simply define a sequence of values of some other > basic type, such as ``int`` or ``str``, to represent discrete > arbitrary values. However, an enumeration ensures that such values > are distinct from any others, and that operations without meaning > ("Wednesday times two") are not defined for these values. Here's why I think it's not too useful to begin with: the benefits of the enum you describe here are pretty weak. It's a pretty weak case to have a dedicated builtin to prevent duplicates in something that changes maybe once a month, as enums tend to change rather slowly. (At least, that's the way enums in other languages are used, and the design you present here seems to suggest you intend to use them that way as well.) And frankly, a unit test or assertion could check this. As for preventing nonsensical operations on enum constants: good idea, but let's face it: a decent programmer knows whether he or she's dealing with a enum value or a piece of string data. This is why I said it's not terribly useful (as opposed to not useful at all). Unfortunately, this proposal fails to prevent a nonsensical operation in the case where it would be most useful to do so. [snip] > Enumerations with no values are meaningless. The exception > ``EnumEmptyError`` is raised if the constructor is called with no > value arguments. No strong feeling on this issue. Probably no use for an empty enum, but no harm either. [snip] > This allows the operation to succeed, evaluating to a boolean value:: > > >>> gym_night = Weekdays.wed > >>> gym_night < Weekdays.mon > False > >>> gym_night < Weekdays.wed > False > >>> gym_night < Weekdays.fri > True > >>> gym_night < 23 > False > >>> gym_night > 23 > True > >>> gym_night > "wed" > True > >>> gym_night > Grades.B > True The nonsensical comparisions should throw value errors. You say that you want to get rid of operations that don't make sense, but it seems misguided that we would get rid of multiplying by a integer (something that's not likely to happen much at all) but retain comparison with other types (something that's going to be much more common). I realize that this is a thoughtful decision on your part, that you have some reason for it and were not just blindly following the example of other Python builtins. However, IMHO, this design decision forsakes the single most useful feature of an enum, and replaces it with confusion. [snip examples of use] One thing I'd add is something like Weekdays.get_constant("wed"). I realize that you can do this with getattr, but you can also do getattr(Weekdays,"__dict__") with getattr, and you ought to have a method that thows and exception if you try to access the __dict__ constant. Also, it blesses the operation, so that people who are trying to access the constant after reading its name from the database don't have to feel guilty about using getattr. [snip] > Metaclass for creating enumeration classes > ------------------------------------------ > > The enumerations specified in this PEP are instances of an ``enum`` > type. Some alternative designs implement each enumeration as its own > class, and a metaclass to define common properties of all > enumerations. > > One motivation for having a class (rather than an instance) for each > enumeration is to allow subclasses of enumerations, extending and > altering an existing enumeration. A class, though, implies that > instances of that class will be created; How so? This is true of classes with metaclass type, but using a different metaclass suggests maybe it isn't like a regular class. In particular, constructing an instance could be a non-op; instead the class creates it's own instances at definition time. I don't see anything that implies that a class can't do that. > it is difficult to imagine > what it means to have separate instances of a "days of the week" > class, where each instance contains all days. I don't understand what you're saying here. It doesn't seem to me hard to imagine that a class could create its own instances, but I'm not sure if that's what you're talking about. > This usually leads to > having each class follow the Singleton pattern, further complicating > the design. Meh. I don't feel too strongly about this, but I'd think an enum as a class is better, because you can't (or, rather, oughtn't) compare constants from different enums. That's a logical demarcation of classes. Sorry if I was a little blunt here. In the end, I really don't see the problems that this enum addresses being all that common; it seems a lot of work for minor benefit. Carl Banks From hipertracker at gmail.com Fri Feb 10 09:31:19 2006 From: hipertracker at gmail.com (Jaroslaw Zabiello) Date: Fri, 10 Feb 2006 14:31:19 +0000 Subject: What editor shall I use? References: <1139410110.389122.215400@z14g2000cwz.googlegroups.com> Message-ID: On 8 Feb 2006 06:48:30 -0800, Lad wrote: > What editor shall I use if my Python script must contain utf-8 > characters? > I use XP The best (and free) are: Eclipse http://www.eclipse.org/ with pydev http://pydev.sourceforge.net/ SPE http://pythonide.stani.be/ Eric3 http://www.die-offenbachs.de/detlev/eric3.html win32 binary: http://www.quadgames.com/download/pythonqt/ All of them contain cool debugger and a lot of usefull options. If you want only plain text editor, you can use SciTe, vim, Notepad++ or whatever. -- Jaros?aw Zabie??o http://blog.zabiello.com From bblais at bryant.edu Sat Feb 18 07:52:27 2006 From: bblais at bryant.edu (Brian Blais) Date: Sat, 18 Feb 2006 07:52:27 -0500 Subject: strange error I can't figure out... Message-ID: <43F7188B.6040809@bryant.edu> Hello, I have an odd kind of Heisenbug in what looks like a pretty simple program. The program is a progress bar code I got at the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/168639 (including the code below) If you uncomment the one print statement I added in the progressBar class, you get the error: File "test_progress2.py", line 19 diffFromMin = float(self.amount - self.min) ^ SyntaxError: invalid syntax yet, without the print statement, it works fine. what am I overlooking here? thanks, bb #------------------------------------------------------------------------ class progressBar: def __init__(self, minValue = 0, maxValue = 10, totalWidth=12): self.progBar = "[]" # This holds the progress bar string self.min = minValue self.max = maxValue self.span = maxValue - minValue self.width = totalWidth self.amount = 0 # When amount == max, we are 100% done self.updateAmount(0) # Build progress bar string def updateAmount(self, newAmount = 0): if newAmount < self.min: newAmount = self.min if newAmount > self.max: newAmount = self.max self.amount = newAmount # print "hello" #<-------------- uncomment line to break # Figure out the new percent done, round to an integer diffFromMin = float(self.amount - self.min) percentDone = (diffFromMin / float(self.span)) * 100.0 percentDone = round(percentDone) percentDone = int(percentDone) # Figure out how many hash bars the percentage should be allFull = self.width - 2 numHashes = (percentDone / 100.0) * allFull numHashes = int(round(numHashes)) # build a progress bar with hashes and spaces self.progBar = "[" + '#'*numHashes + ' '*(allFull-numHashes) + "]" # figure out where to put the percentage, roughly centered percentPlace = (len(self.progBar) / 2) - len(str(percentDone)) percentString = str(percentDone) + "%" # slice the percentage into the bar self.progBar = self.progBar[0:percentPlace] + percentString + self.progBar[percentPlace+len(percentString):] def __str__(self): return str(self.progBar) if __name__ == "__main__": import time prog = progressBar(0, 100, 77) for i in xrange(101): prog.updateAmount(i) print prog, "\r", time.sleep(.05) From hinnc at yahoo.com Tue Feb 7 12:09:38 2006 From: hinnc at yahoo.com (slogging_away) Date: 7 Feb 2006 09:09:38 -0800 Subject: Too Many if Statements? In-Reply-To: <43e8d21b$0$32168$626a54ce@news.free.fr> References: <1139330447.716190.247940@z14g2000cwz.googlegroups.com> <43e8d21b$0$32168$626a54ce@news.free.fr> Message-ID: <1139332178.557744.73030@g47g2000cwa.googlegroups.com> I don't consider myself to be a seasoned programmer so if you mean redesigning the script to make the checks and therefore reduce the number of 'if' statements, I'm not sure if that can be done. The script needs to make numerous checks for the existence of particular strings within the configuration file. It also uses 'if' statements to determine what type of file is being examined, etc.. If an error is encounterd it writes warning messages to a master file. I guess what I am trying to say is that in order to make the many checks on the configuration files I do not know of any other way than to check for the existance of particular statements, (strings), and then report on those if they are incorrect or missing - hence at least one 'if' statement for every check. I appreciate the feedback though! From steve at REMOVETHIScyber.com.au Thu Feb 23 10:38:12 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 24 Feb 2006 02:38:12 +1100 Subject: Unexpected timing results Message-ID: I have two code snippets to time a function object being executed. I expected that they should give roughly the same result, but one is more than an order of magnitude slower than the other. Here are the snippets: def timer1(): timer = time.time func = lambda : None itr = [None] * 1000000 t0 = timer() for _ in itr: func() t1 = timer() return t1 - t0 def timer2(): timer = time.time func = lambda : None itr = [None] * 1000000 t = 0.0 for _ in itr: t0 = timer() func() t1 = timer() t += t1 - t0 return t Here are the results: >>> timer1() 0.54168200492858887 >>> timer2() 6.1631934642791748 Of course I expect timer2 should take longer to execute in total, because it is doing a lot more work. But it seems to me that all that extra work should not affect the time measured, which (I imagine) should be about the same as timer1. Possibly even less as it isn't timing the setup of the for loop. Any ideas what is causing the difference? I'm running Python 2.3 under Linux. Thanks, -- Steven. From michaeltaft at gmail.com Tue Feb 7 17:31:38 2006 From: michaeltaft at gmail.com (mwt) Date: 7 Feb 2006 14:31:38 -0800 Subject: 450 Pound Library Program Message-ID: <1139351498.090768.82270@o13g2000cwo.googlegroups.com> So in a further attempt to learn some Python, I've taken the little Library program (http://groups.google.com/group/comp.lang.python/browse_thread/thread/f6a9ccf1bc136f84) I wrote and added several features to it. Readers now quit when they've read all the books in the Library. Books know how many times they've been read. Best of all, you can now create your own list of books to read! Again, the point of all this is to get used to programming in Python. So although the program is trivial, any feedback on style, structure, etc. would be much appreciated. I'm a convert from Java, so I've probably got some unconscious Javanese in there somewhere. Help me get rid of it! Here's the new, improved program: [code] #!/usr/bin/python # Filename: Library.py # author: mwt # Feb, 2006 import thread import time import threading import random class Library2: def __init__(self, listOfBooks, totalBooks): self.stacks = listOfBooks self.cv = threading.Condition() self.totalBooks = totalBooks def checkOutBook(self, readerName): "'Remove book from the front of the list, block if no books are available'" self.cv.acquire() while len(self.stacks) == 0: self.cv.wait() print "%s waiting for a book..." %readerName book = self.stacks.pop(0) self.cv.release() return book def returnBook(self, returnedBook): "'put book at the end of the list, notify that a book is available'" returnedBook.wasRead() self.cv.acquire() self.stacks.append(returnedBook) self.cv.notify() self.cv.release() class Reader(threading.Thread): def __init__(self, library, name, readingSpeed, timeBetweenBooks): threading.Thread.__init__(self) self.library = library self.name = name self.readingSpeed = readingSpeed self.timeBetweenBooks = timeBetweenBooks self.book = "" self.numberOfBooksRead = 0 def run(self): "'Keep checking out and reading books until you've read all in the Library'" while self.numberOfBooksRead < self.library.totalBooks: self.book = self.library.checkOutBook(self.name) print "%s reading %s" %(self.name, self.book.title), time.sleep(self.readingSpeed) self.numberOfBooksRead += 1 self.library.returnBook(self.book) print "%s done reading %s" %(self.name, self.book.title), print"Number of books %s has read: %d" %(self.name, self.numberOfBooksRead) self.bookName = "" time.sleep(self.timeBetweenBooks) print "%s done reading." %self.name class Book: def __init__(self, author, title): self.author = author self.title = title self.numberOfTimesRead = 0 #print "%s,%s" % (self.author, self.title),#print as books are loaded in def wasRead(self): self.numberOfTimesRead += 1 print "Number of times %s has been read: %d" %(self.title, self.numberOfTimesRead) if __name__=="__main__": print "\nWELCOME TO THE THURMOND STREET PUBLIC LIBRARY" print "Checking which books are avialable...\n" try: theBookFile = open("books.txt", "r")#Create your own list of books! stacks = []#a place to put the books for line in theBookFile.readlines(): L = line.split (",") # a comma-delimited list author = L[0] bookName = L[1] newBook = Book(author, bookName) stacks.append(newBook) theBookFile.close() except IOError: print "File not found!" #string = "How many books would you like in the Library?[1-" + str(len(stacks)) + "]" totalBooks = input("How many books would you like in the Library?[1-" + str(len(stacks)) + "]") stacks[totalBooks: len(stacks)] = [] print "Number of books in the Library is:", len(stacks) library = Library2(stacks, totalBooks) readers = input("\nHow many readers would you like?") print "Number of readers is:", readers, "\n" for i in range(0,readers): newReader = Reader(library, "Reader" + str (i), random.randint(1,7), random.randint(1,7)) newReader.start() [/code] And here's a handy text file of books for you, so you don't have to make your own: [code] Conrad, Heart of Darkness Kafka, Die Verwandlung Hemingway, For Whom the Bell Tolls James Joyce, Dubliners Moliere, Cyrano de Bergerac William Golding, Lord of the Flies Dostoevski, Crime and Punishment Cervantes, Don Quixote Camus, L'Etranger Tolstoy, War and Peace Poe, Tales Faulkner, The Sound and the Fury Orwell, 1984 Fitzgerald, The Great Gatsby Steinbeck, The Grapes of Wrath Huxley, Brave New World Twain, The Adventures of Huckleberry Finn Mann, Der Tod in Venedig Kesey, Sometimes a Great Notion Pynchon, Gravity's Rainbow McEwan, The Cement Garden M?rquez, Cien A?os de Soledad Salinger, The Catcher in the Rye Miltion, Paradise Lost Chapman et al , The Pythons [/code] From johnmc at velseis.com.au Tue Feb 21 19:33:11 2006 From: johnmc at velseis.com.au (John McMonagle) Date: Wed, 22 Feb 2006 10:33:11 +1000 Subject: Basic coin flipper program - logical error help In-Reply-To: <1140567243.251982.255620@g14g2000cwa.googlegroups.com> References: <1140567243.251982.255620@g14g2000cwa.googlegroups.com> Message-ID: <1140568392.31572.5.camel@cornell> On Tue, 2006-02-21 at 16:14 -0800, DannyB wrote: > I'm just learning Python. I've created a simple coin flipper program - > here is the code: > > [source] > #Coin flipper > import random > > heads = 0 > tails = 0 > counter = 0 > > coin = random.randrange(2) > > while (counter < 100): > if (coin == 0): > heads += 1 > counter += 1 > else: > tails += 1 > counter += 1 > > coin = random.randrange(2) > > > print "\nThe coin landed on heads", heads, "times." > print "\nThe coin landed on tails", tails, "times." > [/source] > > << anyway.>>> > > The program runs - however - it will give me 100 heads OR 100 tails. > Can someone spot the logic error? Yes. Put coin = random.randrange(2) inside the while loop. import random heads = 0 tails = 0 counter = 0 coin = random.randrange(2) while (counter < 100): if (coin == 0): heads += 1 counter += 1 else: tails += 1 counter += 1 coin = random.randrange(2) print "\nThe coin landed on heads", heads, "times." print "\nThe coin landed on tails", tails, "times." -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From anothermoi at sbcglobal.net Fri Feb 17 10:28:29 2006 From: anothermoi at sbcglobal.net (Lou G) Date: 17 Feb 2006 07:28:29 -0800 Subject: Checkbuttons in a Text widget Message-ID: <1140190108.192983.287630@g14g2000cwa.googlegroups.com> I'm trying to show a number of Checkbuttons (each with associated text based on a list of names) inside a y-scrollable Text widget like so: [ ] Bob [ ] Carol [ ] Ted [ ] Alice etc. etc. There may be quite a few (as many as 100 or so). I'm uncertain as to the correct way to get these into the Text widget. I've tried text.insert and it doesn't seem to do the job. Help? Thanks, Lou G From mh at pixar.com Tue Feb 7 14:35:48 2006 From: mh at pixar.com (Mark Harrison) Date: Tue, 07 Feb 2006 19:35:48 GMT Subject: creat a DOM from an html document References: Message-ID: Mark Harrison wrote: > Now I can't seem to find this... does anybody have a recommendation > as to a good package to look at? Ahh, it's BeautifulSoup... Thanks All!! From gregpinero at gmail.com Tue Feb 14 11:16:06 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Tue, 14 Feb 2006 11:16:06 -0500 Subject: Python 3000 deat !? Is true division ever coming ? In-Reply-To: <1139928242.726349.221080@g44g2000cwa.googlegroups.com> References: <1139810036.943598.229030@g47g2000cwa.googlegroups.com> <1139928242.726349.221080@g44g2000cwa.googlegroups.com> Message-ID: <312cfe2b0602140816y17326dcbg7f6db0414b8d462a@mail.gmail.com> On 14 Feb 2006 06:44:02 -0800, rainbow.cougar at gmail.com > 5./2.=2.5 is floating point math, with all the round off errors that > incorporates. Thanks Curtis, I never knew that trick. I guess for variables do have true division you have to make them floats? e.g. float(var1)/float(var2)? Or do you know a less typing approach for that? -- Gregory Pi?ero Chief Innovation Officer Blended Technologies (www.blendedtechnologies.com) From tjreedy at udel.edu Mon Feb 6 20:04:31 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 6 Feb 2006 20:04:31 -0500 Subject: Using bytecode, not code objects References: <1138514565.112950.212310@o13g2000cwo.googlegroups.com> <1139263624.553961.236730@g14g2000cwa.googlegroups.com> Message-ID: "Raymond Hettinger" wrote in message news:1139263624.553961.236730 at g14g2000cwa.googlegroups.com... > > Fabiano Sidler wrote: >> with pdb (which I'm surely not using as neatly as it could be). Or is >> there any documentation on it I couldn't find? > > The pysassem module is part of the compiler package: > > http://docs.python.org/lib/compiler.html The 2.4 docs, which the above links to, only has sections on modules compiler, compiler.ast, and compiler.visitor and not on .consts, .future, .misc, .pyassem, .pycodegen, .symbols, and .transformer. However, import compiler help(compiler.ast) gives a few pages of info derived from the module. Terry Jan Reedy From rtilley at vt.edu Sat Feb 11 11:08:13 2006 From: rtilley at vt.edu (rtilley) Date: Sat, 11 Feb 2006 16:08:13 +0000 Subject: Is python very slow compared to C In-Reply-To: <1139690972.344818.136870@f14g2000cwb.googlegroups.com> References: <1139690972.344818.136870@f14g2000cwb.googlegroups.com> Message-ID: diffuser78 at gmail.com wrote: > I have just started to learn python. Some said that its slow. Can > somebody pin point the issue. It depends on what you are doing. Much of Python is just wrapped C. So many things are very fast. From fredrik at pythonware.com Thu Feb 2 02:24:01 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 2 Feb 2006 08:24:01 +0100 Subject: OO conventions References: <5f56302b0602011440o47c07c4h3e2b0e4a1338e4fa@mail.gmail.com> <20060201190903.738b97e4@samwise.anansi> Message-ID: Terry Hancock wrote: > What Lundh is modeling this on is not standard OOP thinking, > but rather the standard way of opening files in Python. > > Or you could say he's using a "factory function". "open" is a factory function, and it picks the right class based on the file you're opening. anyone arguing that this is bad OOP is deluded. From bonono at gmail.com Mon Feb 13 01:45:22 2006 From: bonono at gmail.com (bonono at gmail.com) Date: 12 Feb 2006 22:45:22 -0800 Subject: Is python very slow compared to C In-Reply-To: References: <1139690972.344818.136870@f14g2000cwb.googlegroups.com> <1139694723.857673.263750@z14g2000cwz.googlegroups.com> <1139742200.155197.245490@g14g2000cwa.googlegroups.com> <1139754010.067582.214830@z14g2000cwz.googlegroups.com> <1139793721.739325.235780@z14g2000cwz.googlegroups.com> <43F01749.2000601@REMOVEMEcyber.com.au> <1139809484.447810.17000@g44g2000cwa.googlegroups.com> Message-ID: <1139813121.956510.182710@z14g2000cwz.googlegroups.com> PA wrote: > On Feb 13, 2006, at 06:44, bonono at gmail.com wrote: > > > And if we use market penetration as measure, Perl seems to be easier > > for people ? > > Perl: Shell scripts/awk/sed are not enough like programming languages. > > Python: Perl is a kludge. > > "What Languages Fix" > http://www.paulgraham.com/fix.html > > Cheers Where is the entry for Lua and Haskell, both I found very interesting. From steve at holdenweb.com Tue Feb 14 16:26:19 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 14 Feb 2006 16:26:19 -0500 Subject: How can I find a freelance programmer? In-Reply-To: <43F241B6.9090303@pollenation.net> References: <43F241B6.9090303@pollenation.net> Message-ID: <43F24AFB.4010800@holdenweb.com> Tim Parkin wrote: > Charles wrote: > > >>Hello, >> >>I am looking for a freelance Python programmer to create a cross-platform >>application with wxPython. >>Any idea where I could find one? >>Thanks, >> >> >> > > You could ask Steve Holden? - that'll be 10% commission Steve! ;-) > Hi, Charles How can I help you? I'm fairly experienced with Python, and I'm giving a wxPython tutorial at PyCon in a week's time, so I know the technologies you need. What's the requirement? [Thanks, Tim: can I pay you in beer? :-)] regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From zaatar05 at walla.com Wed Feb 22 15:50:28 2006 From: zaatar05 at walla.com (zaatar05 at walla.com) Date: 22 Feb 2006 12:50:28 -0800 Subject: com inheritance Message-ID: <1140641428.251998.305020@o13g2000cwo.googlegroups.com> Hi I have a python class, which i want to wrap in a COM class Can the COM class inherit all the methods and attributes and thus be used by a COM client? example: class A: __init__(self, Param): self.Param = Param class COMA(A): _public_attributes_ = ["Param"] def __init__(self, Param): A.__init__(self, Param) thanks in advance From renato.ramonda at gmail.com Mon Feb 27 02:45:26 2006 From: renato.ramonda at gmail.com (Renato) Date: 26 Feb 2006 23:45:26 -0800 Subject: Python Indentation Problems In-Reply-To: <1141021286.047172.278030@z34g2000cwc.googlegroups.com> References: <1141021286.047172.278030@z34g2000cwc.googlegroups.com> Message-ID: <1141026326.424249.187030@p10g2000cwp.googlegroups.com> If you use vi (vim, I hope), then place something like this in your .vimrc set ts=4 set sw=4 set expandtab set ai There are a lot more tricks for python in vim (and plugins, and helpers, and so on), but this is the starting point: tabstops of 4 places, autoconverted in spaces. Also, when shifting text with < or > it moves 4 spaces. -- bye, Renato From ram0812 at hotmail.com Thu Feb 9 09:19:27 2006 From: ram0812 at hotmail.com (Raja Raman Sundararajan) Date: 9 Feb 2006 06:19:27 -0800 Subject: Test indexers...how do they work? Message-ID: <1139494767.338556.110030@g44g2000cwa.googlegroups.com> Hello guys, I was investigating how one can use the "text indexers" in python and I stumbled across several ones. eg., pylucene I wanted to know how the algorithm of indexers look like. I have heard people talking about B-Trees. But this info. is simply know enough. I would like to know exactly each part of the indexing flow and the algorightm behind it work. Can someone here point me to the right material? Thanks! From heikki at osafoundation.org Fri Feb 17 18:20:52 2006 From: heikki at osafoundation.org (Heikki Toivonen) Date: Fri, 17 Feb 2006 15:20:52 -0800 Subject: RSA in python In-Reply-To: References: Message-ID: Abhisek Datta wrote: > I am looking for good RSA implementations in python that can import a > public key in PEM format and encrypt a buffer using the imported > public key. I tried m2crypto, but somehow it is giving me exceptions > which I couldnt solve as of now. What you are trying to do should be covered by M2Crypto. Without more context for the error (what was the file you were trying load, etc.) it is hard to say what is wrong. My first guess is that your pem file did not include the BEGIN/END lines. I would suggest you take a look at the tests and samples included in M2Crypto. They do show how to work with PEM files. M2Crypto 0.15: http://wiki.osafoundation.org/bin/view/Projects/MeTooCrypto From grante at visi.com Sat Feb 25 07:55:09 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 25 Feb 2006 12:55:09 -0000 Subject: python-list/python-dev quoting style References: Message-ID: <1200ktdnodqqr26@corp.supernews.com> On 2006-02-25, Michael Hoffman wrote: >> And who is "me", anyway? > > It's hard to believe that you don't understand who "me" is in > a conversation between two people, Since when is a Usenet news group a conversation between two people? > one of whom is identified as "Aahz" and is attributed words > you yourself wrote. -- Grant Edwards grante Yow! Not SENSUOUS... only at "FROLICSOME"... and in visi.com need of DENTAL WORK... in PAIN!!! From apardon at forel.vub.ac.be Thu Feb 9 05:23:18 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 Feb 2006 10:23:18 GMT Subject: module with __call__ defined is not callable? References: <43ea0efd$1@nntp0.pdx.net> Message-ID: Op 2006-02-08, Scott David Daniels schreef : > Steven D'Aprano wrote: >> On Wed, 08 Feb 2006 13:58:13 +1100, Delaney, Timothy (Tim) wrote: >> >>> adam johnson wrote: >>> >>>> Hi All. >>>> I was wondering why defining a __call__ attribute for a module >>>> doesn't make it actually callable. >>> For the same reason that the following doesn't work >> [snip example] >>> The __call__ attribute must be defined on the class (or type) - not on >>> the instance. A module is an instance of . >> >> That's not a _reason_, it is just a (re-)statement of fact. We know that >> defining a __call__ method on a module doesn't make it callable. Why not? >> The answer isn't "because defining a __call__ method on a module or an >> instance doesn't make it callable", that's just avoiding the question. > > You missed it. Steven D'Aprano was telling you why, and all you heard > was the no. He stated a more general principal which controls why > modules in particular are not callable. It is not a design decision > about modules; it is a design decision about classes and instances. > > class SomeClass(object): > def __call__(self): return 'Text' > > class AnotherClass(object): > def __repr__(self): return 'Missive' > > name = SomeClass()() # this works > name = AnotherClass()() # this doesn't > obj = AnotherClass() # build an instance > def fun(*args): return 'more text' # *args so nearly any call works > obj.__call__ = fun # tack a function onto an instance > obj() # note this doesn't call the function. > > Now, if you think the last _should_ do the call, then let's step > back to classes. > > class SomeClass(object): > def __call__(self): return 'Text' > > Now the SomeClass object (which is a subclass of object) has an > attribute named "__call__". Should that define how the expression > SomeClass() > is evaluated? Should that return the string 'Text' or create a > new instance of SomeClass? This make me wonder. Would it be possible to do something with metaclasses so that after class SomeClass(MetaClass): ... SomeClass() will be equivalent to MetaClass.__call__(SomeClass) Just curious. -- Antoon Pardon From rtilley at vt.edu Mon Feb 27 13:28:44 2006 From: rtilley at vt.edu (rtilley) Date: Mon, 27 Feb 2006 13:28:44 -0500 Subject: different ways to strip strings Message-ID: s = ' qazwsx ' # How are these different? print s.strip() print str.strip(s) Do string objects all have the attribute strip()? If so, why is str.strip() needed? Really, I'm just curious... there's a lot don't fully understand :) From bdesth.quelquechose at free.quelquepart.fr Wed Feb 15 18:19:13 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 16 Feb 2006 00:19:13 +0100 Subject: Python, Forms, Databases In-Reply-To: <1140032343.627599.217590@g14g2000cwa.googlegroups.com> References: <1140030788.083799.45060@f14g2000cwb.googlegroups.com> <1140032343.627599.217590@g14g2000cwa.googlegroups.com> Message-ID: <43f395f9$0$916$626a54ce@news.free.fr> Tempo a ?crit : > Larry I do see your point. There does seem to be a lot more support for > PHP and MySQL together than there is Python and ASP. But I want to > first try to accomplish my goal by using Python first before I give up > and revert back to PHP. So if I was going to parse HTML forms and place > the data into a MySQL database, what should I use? CGI module? Zope? > Webware? Thanks for any and all help. Depends on what your hosting provides. Zope seems definitively out of the field - it's not the right tool for the job, and it requires specific, professionnal hosting. I don't know to much about webware. Pure CGI is a PITA. Something that may do the job just fine is Myghty (a slightly enhanced Python port of Perl Mason). A great + for Myghty is that it will scale if your app grows (Myghty runs on CGI, FastCGI, mod_python, WSGI, and even on Python's HTTPServer). My 2 cents From grante at visi.com Thu Feb 23 23:12:28 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 24 Feb 2006 04:12:28 -0000 Subject: time.sleep(1) sometimes runs for 200 seconds under windows References: Message-ID: <11vt1tcq488uj3d@corp.supernews.com> On 2006-02-23, Paul Probert wrote: >>In similar situation I would start to blame the hardware for the >>problem, so below a kind of checklist to go through: > > Thanks for the reply. I should have mentioned, this happens to just > about every machine in our collection of about 20 machines. Each is of a > different age, and the hardware is completely diverse. Each has either > of NT4, win2k, or XP installed. They all belong to our domain Time to dowload a linux CD then, eh? -- Grant Edwards grante Yow! I am KING BOMBA of at Sicily!...I will marry visi.com LUCILLE BALL next Friday! From jm.suresh at gmail.com Thu Feb 16 00:04:47 2006 From: jm.suresh at gmail.com (Suresh Jeevanandam) Date: Thu, 16 Feb 2006 10:34:47 +0530 Subject: mapping functions and lambda In-Reply-To: References: Message-ID: I got it: dict([k.split('=') for k in s.split(',')]) regards, Suresh Suresh Jeevanandam wrote: > Given a string > s = 'a=1,b=2' > > I want to create a dictionary {'a': '1', 'b': '2'} > > I did, > > dict(map(lambda k: k.split('='), s.split(','))) > > Is it possible to get rid of the lambda here, without having to define > another function just for this. > > Is this the easiest/straight-forward way to do this? > > regards, > Suresh From reply.in.the.newsgroup at my.address.is.invalid Thu Feb 16 16:03:31 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 16 Feb 2006 22:03:31 +0100 Subject: define loop statement? References: Message-ID: David Isaac: >I would like to be able to define a loop statement >(nevermind why) so that I can write something like > >loop 10: > do_something > >instead of > >for i in range(10): > do_something > >Possible? If so, how? Yes. By implementing a compiler or an interpreter for your programming language. Or a preprocessor that converts your language to Python, or some other suitable intermediate language. Or a programmer, that converts your pseudocode and some coffee to the desired algorithm :-) -- Ren? Pijlman From kay.schluehr at gmx.net Sun Feb 26 16:17:52 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 26 Feb 2006 13:17:52 -0800 Subject: Tail Call Optimization as a Decorator In-Reply-To: <1140987187.726096.112840@p10g2000cwp.googlegroups.com> References: <1140981639.315995.34860@i39g2000cwa.googlegroups.com> <1140986376.438905.95360@t39g2000cwt.googlegroups.com> <1140987187.726096.112840@p10g2000cwp.googlegroups.com> Message-ID: <1140988672.418596.229930@i39g2000cwa.googlegroups.com> Crutcher wrote: > I've tossed it to python-dev, but how do I submit it to the cookbook? http://aspn.activestate.com/ASPN/Python/Cookbook/ I think it is a good place to stay accessible even if python-dev overlooks it. Kay From peter at engcorp.com Mon Feb 20 16:25:37 2006 From: peter at engcorp.com (Peter Hansen) Date: Mon, 20 Feb 2006 16:25:37 -0500 Subject: Python solutions for old Police software? In-Reply-To: <1140454731.103842.221860@g14g2000cwa.googlegroups.com> References: <1140454731.103842.221860@g14g2000cwa.googlegroups.com> Message-ID: jf.ff at mail.com wrote: > http://www.cityfremontof.com This has nothing to do with Python, nor software. It's totally off-topic spam. Ignore. From vercingetorix52 at yahoo.com Tue Feb 28 14:11:12 2006 From: vercingetorix52 at yahoo.com (vercingetorix52 at yahoo.com) Date: 28 Feb 2006 11:11:12 -0800 Subject: telnetlib problems Message-ID: <1141153872.182746.289830@t39g2000cwt.googlegroups.com> I'm trying to use a python script to access an embedded computer running linux and connected via a crossover ethernet cable using the following script... ...and I realize the username and password is not realistic... I'm still in "proof of concept" stage here :) ######################### import telnetlib tn = telnetlib.Telnet('192.168.100.11') tn.read_until('login: ', 5) tn.write('user\n') tn.read_until('Password: ', 5) tn.write('password\n') tn.read_until('bash-2.05$ ', 5) tn.write('ls\n') print tn.read_very_eager() ######################### As a script, this doesn't work. However, if I execute the same commands interactively, it works fine. If I insert some time delays as follows... ######################### import telnetlib import time tn = telnetlib.Telnet('192.168.100.11') tn.read_until('login: ', 5) time.sleep(2) tn.write('user\n') tn.read_until('Password: ', 5) time.sleep(2) tn.write('password\n') tn.read_until('bash-2.05$ ', 5) tn.write('ls\n') time.sleep(2) print tn.read_very_eager() ######################### ...and it works fine. Can anyone tell me what's going on here? TIA From spe.stani.be at gmail.com Mon Feb 20 15:40:00 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 20 Feb 2006 12:40:00 -0800 Subject: editor for Python on Linux In-Reply-To: <43fa2376$0$1149$7a628cd7@news.club-internet.fr> References: <43F8DA72.8040808@sympatico.ca> <43fa2376$0$1149$7a628cd7@news.club-internet.fr> Message-ID: <1140468000.817123.196120@g14g2000cwa.googlegroups.com> > (I never saw this elsewhere). FYI SPE has these two features as well... Stani --- SPE - http://pythonide.stani.be From cito at online.de Tue Feb 14 07:04:22 2006 From: cito at online.de (Christoph Zwerschke) Date: Tue, 14 Feb 2006 13:04:22 +0100 Subject: listing attributes In-Reply-To: References: <1139884643.749492.221140@g43g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote: > However it is easy to use introspection to get what you need. So just for completeness sake, what Thomas probably wants is the following: from types import MethodType def attributes(obj): return [attr for attr in dir(obj) if not attr.startswith('__') and not isinstance(getattr(obj, attr), MethodType)] # Example: class Parrot(object): ATTR = None join = ''.join # callable, but not a method of Parrot def aMethod(self): return ATTR print attributes(Parrot) # this gives: ['ATTR', 'join'] From dylan.moreland at gmail.com Thu Feb 9 00:47:59 2006 From: dylan.moreland at gmail.com (Dylan Moreland) Date: 8 Feb 2006 21:47:59 -0800 Subject: how to remove
using replace function? References: <1139462640.951603.302830@g44g2000cwa.googlegroups.com> Message-ID: <1139464079.635612.289930@o13g2000cwo.googlegroups.com> I think you want to use the replace method of the string instance. Something like this will work: # See http://docs.python.org/lib/string-methods.html#l2h-196 txt = "an unfortunate
in the middle" txt = txt.replace("
", "") From donn at u.washington.edu Thu Feb 2 17:53:53 2006 From: donn at u.washington.edu (Donn Cave) Date: Thu, 02 Feb 2006 14:53:53 -0800 Subject: Another try at Python's selfishness References: <1138918102.863033.298700@o13g2000cwo.googlegroups.com> Message-ID: In article <1138918102.863033.298700 at o13g2000cwo.googlegroups.com>, n.estner at gmx.de wrote: > Having read previous discussions on python-dev I think I'm not the only > Python programmer who doesn't particularly like python's "self" > parameter: > > class Foo: > def bar(self, a,b): > return a+b > Foo().bar(1,2) => 3 > > The main reason (at least for me) is that there's simply too much > "magic" in it. Why does the expression left of the '.' get promoted to > the first parameter? It even goes further: > > Foo.bar(Foo(), 1,2) > > works, but: > > Foo.bar(1,2,3) > > doesn't, just because of the "magical first parameter" in a member > function. But: > > Foo.__dict["bar"]__(1,2,3) > > Does work. > > The point is, I _do_ think it's a good idea to explicitly write > "self.SomeMember" for member-access, so I thought: why can't we be > equally explicit about member function declaration? Wouldn't it be nice > if I could write (say, in Python 3k, or maybe later): > > class Foo: > def self.bar(a,b): > return a+b > Foo().bar(1,2) => 3 > > That way, the declaration would match the invocation (at least > syntactically), and the "magic"-feeling is gone. In the long run, the > "old-style" syntax (i.e. if there's no '.' in the method name) could be > used for static methods. > > What do you think? I think you make it too complicated. Why shouldn't all functions be declared and called in the same way, that would be the simplest thing for everyone. class Foo def bar(self, a, b): return a + b bar(Foo(), 1, 2) => 3 The virtues of this consistency become more apparent in a more complex functional context: sys.stdin.write(open(file, 'r').read().split(sep)[0]) vs. write(sys.stdin, split(read(open(file, 'r')))[0]) Donn Cave, donn at u.washington.edu From marcus.tettmar at gmail.com Fri Feb 3 11:19:42 2006 From: marcus.tettmar at gmail.com (marcus.tettmar at gmail.com) Date: 3 Feb 2006 08:19:42 -0800 Subject: newbie - script works in PythonWin - fails from Python In-Reply-To: References: <1138960717.927268.22640@g44g2000cwa.googlegroups.com> <1138961665.684357.78060@g44g2000cwa.googlegroups.com> <1138962543.290178.77790@g47g2000cwa.googlegroups.com> <1138978837.557550.144350@f14g2000cwb.googlegroups.com> Message-ID: <1138983582.414125.73330@g14g2000cwa.googlegroups.com> Unfortunately not. Is there any doc anywhere that shows how to make the script run from the command line the same way it does within PythonWin? From gregory.petrosyan at gmail.com Tue Feb 14 08:18:25 2006 From: gregory.petrosyan at gmail.com (Gregory Petrosyan) Date: 14 Feb 2006 05:18:25 -0800 Subject: Pythonic gui format? In-Reply-To: <43f11990$0$667$626a54ce@news.free.fr> References: <1139858810.606052.39130@z14g2000cwz.googlegroups.com> <43f11990$0$667$626a54ce@news.free.fr> Message-ID: <1139923105.939191.200660@z14g2000cwz.googlegroups.com> > > Isn't it ugly a bit? >I'd even say 'ugly 16-bits' !-) You are right of course. Those "examples" are really bad, and, most of all, really un-pythonic. Thanks for JSON. It's more clean&simple than XML, but my main idea is to remove any extra layer between Python and GUI. I want all GUI elements/data to be directly accessible from Python (without extra libraries). Your dicts example is nice, but this approach (and some others) lacks one important feature: ordering of GUI elements. In XML, the order of all elements is specified, and with dicts (or with very clean Georg's model) it is not. (BTW remember topics about ordered dicts...) I think that there should be a way for solving this problem, and I'll certainly try to find it. Thanks for your help. From rtilley at vt.edu Mon Feb 13 14:22:13 2006 From: rtilley at vt.edu (rtilley) Date: Mon, 13 Feb 2006 19:22:13 +0000 Subject: invert the order of a string In-Reply-To: References: <6272v111vee95606gd7fucjdqmec8uhc7e@4ax.com> Message-ID: Dave Hansen wrote: > It's just simple slicing. Well, maybe not so simple, or at least not > so common, but with a syntax similar to the range function. Consider > the following (string chosen to make it obvious what's going on): > > s = "0123456789" > s[::] > s[3::] > s[:3:] > s[::3] > s[::-2] > s[-2::-2] Well, it turns out to be the best way to invert a string, IMO. The reversed() feature returns a reversed object... not a reversed string. In short, I have to fool with it again _after_ it has been inverted. The slicing takes care of the job right away and gives me what I want... no Computer Sciencey > to deal with :) I'm sure the reversed feature is much more generic though for dealing with other types. From bill.scherer at verizonwireless.com Mon Feb 20 07:46:27 2006 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Mon, 20 Feb 2006 07:46:27 -0500 Subject: Python Oracle Interace on Solaris In-Reply-To: <78E6A2FC276AD8428A8E2DBBB540855E038A0BE5@NYOBGCEXMB21.uswin.ad.vzwcorp.com> References: <78E6A2FC276AD8428A8E2DBBB540855E038A0BE5@NYOBGCEXMB21.uswin.ad.vzwcorp.com> Message-ID: <43F9BA23.6020801@verizonwireless.com> Kenny wrote: > Thanks... Im not sure if you would know how to solve this one, but when > I ran my setup python scripts I got the error: library -lclntsh not > found. In the instantclient folder the library exists... is this a > matter of just copying the libraries to a different spot or just > setting up the correct environment variables? > Not sure on Solaris... You might try exporting an LD_LIBRARY_PATH, or editing /etc/ld.so.conf and running ldconfig, if Solaris has such a thing. I would caution against moving the library, it's probably already where it's expected to be. You have ORACLE_HOME set? From xbello at gmail.com Mon Feb 20 06:26:22 2006 From: xbello at gmail.com (XBello) Date: 20 Feb 2006 03:26:22 -0800 Subject: os.mkdir simple help References: <1140335502.110014.35870@g47g2000cwa.googlegroups.com> Message-ID: <1140434782.384240.254110@g44g2000cwa.googlegroups.com> I'm new to python too, but I've read that sys.stdin.readline() is preferred. Is that right? From mailinglist4ken at gmail.com Mon Feb 20 08:32:24 2006 From: mailinglist4ken at gmail.com (Kenneth Xie) Date: Mon, 20 Feb 2006 21:32:24 +0800 Subject: any ftpd written in python? In-Reply-To: References: Message-ID: <43F9C4E8.1020901@gmail.com> garabik-news-2005-05 at kassiopeia.juls.savba.sk wrote: > Kenneth Xie wrote: > >> I need a simple ftpd example in pure python. Is there already such a >> ftpd available? >> Thank you very much in advance. >> > > self-advertising: http://melkor.dnp.fmph.uniba.sk/~garabik/pyftpd.html > it is a bit dated and I do not develop it anymore, but as a base of your > own server software it can be quite good. > > Exactly what I need now, thank you very much. From aleaxit at yahoo.com Thu Feb 9 23:35:46 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Feb 2006 20:35:46 -0800 Subject: Is Python good for web crawlers? References: <1139330008.270988.227170@g44g2000cwa.googlegroups.com> <1hafknf.1ft17us1sux13rN%aleaxit@yahoo.com> Message-ID: <1haief6.149xrav1inly0nN%aleaxit@yahoo.com> John J. Lee wrote: ... > I wonder if that little outfit has considered open-sourcing any of > their web client code? What they've open-sourced so far is listed at -- of these, the only crawl/spider is K?ngul?, so far. Alex From alex.gman at gmail.com Tue Feb 7 20:01:31 2006 From: alex.gman at gmail.com (alex.gman at gmail.com) Date: 7 Feb 2006 17:01:31 -0800 Subject: Xah's Edu Corner: Unix damage: color names References: <1133844932.007824.26780@g43g2000cwa.googlegroups.com> <1134780763.066592.45390@g49g2000cwa.googlegroups.com> <1135405908.381150.133190@o13g2000cwo.googlegroups.com> <1136236586.734775.212440@f14g2000cwb.googlegroups.com> <1137784561.589887.58380@o13g2000cwo.googlegroups.com> <1139356437.987319.59280@g14g2000cwa.googlegroups.com> Message-ID: <1139360491.583628.143830@g43g2000cwa.googlegroups.com> So why don't you use Windows XP then? It's just like what you are using now, but even more awesome! From grante at visi.com Fri Feb 3 19:08:56 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 04 Feb 2006 00:08:56 -0000 Subject: Python on Windows References: <43E3EE2F.9040508@websafe.com> Message-ID: <11u7s4oor8apa49@corp.supernews.com> On 2006-02-03, Larry Bates wrote: >> What would folks suggest is the easiest way to package it to run on >> other windows PCs? Like the man said, my vote is for py2exe + inno-setup >> I would love a single .exe file that would run without ANY OTHER FILES >> even if it was 50 Mb! Do you _really_ want a single exe? I haven't seen a single exe windows program in many years (except for putty, which is many years old). > Use py2exe to create distribution and then use Inno Installer to > create a single setup.exe file that can easily be distributed. Definitely. Nobody does single .exe file windows programs anymore. A single-file installer is almost as easy. -- Grant Edwards grante Yow! Where does it go when at you flush? visi.com From xavier.morel at masklinn.net Sun Feb 5 12:55:53 2006 From: xavier.morel at masklinn.net (Xavier Morel) Date: Sun, 05 Feb 2006 18:55:53 +0100 Subject: Importing a class, please help... In-Reply-To: References: Message-ID: Jorgen Grahn wrote: > You are rude to an obvious newbie here ... please keep in mind that today's > stupid newbies are tomorrow's Python professionals. > I didn't mean to be rude and apologize if that's the way it came out. > Maybe he /is/ running Jython and failed to explain that properly? > No, he explicitely stated that he's using Python 2.4 (I'm pretty sure Jython's latest release is 2.1) and SPE (which didn't handle Jython last time I tried it) > If I > understand things correctly, jar files are not tied to Java but to the java > bytecode format -- which Java and Jython share. > Yes, it's used to store/package compiled java classes (.class bytecode files) and various metadata associated to the classes (resources, ...) and therefore tied to the bytecode (or the JVM) indeed. From claird at lairds.us Thu Feb 9 17:08:03 2006 From: claird at lairds.us (Cameron Laird) Date: Thu, 09 Feb 2006 22:08:03 GMT Subject: Tkinter, X-windows and ebay References: <1tqdncP3Ps7s6XfenZ2dnUVZ_tGdnZ2d@nmt.edu> Message-ID: In article <1tqdncP3Ps7s6XfenZ2dnUVZ_tGdnZ2d at nmt.edu>, Bob Greschke wrote: >When you post something on eBay (and other places) you can use a 'browse' >button on a web page to send a picture file from your hard drive to them for >inclusion in your listing. Can the same kind of thing (not the same exact >thing, of course) be done with a Python/Tkinter program that is running on a >remote machine (that you logged into to start the program), but that's just >using your computer's display (with X11 on a Mac, X-whatever on Linux, >X-Win32 on Windows, etc.)? I've got an inventory program that runs this way >and it would be nice if users could create a text file on their machine, but >then have the program read that file and, for example, update item >quantities according to information in that file. Things like that. . . . In a fairly well-defined sense, no; an X server isn't privileged, in general, to access the host filesystem. This is a *benefit* for security reasons. I'm sympathetic with your desire. One of us should return to the topic later on variations that might suit you. From steve at REMOVETHIScyber.com.au Sun Feb 12 09:27:03 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 13 Feb 2006 01:27:03 +1100 Subject: Tracking down memory leaks? References: <1139749861.949765.282310@z14g2000cwz.googlegroups.com> Message-ID: On Sun, 12 Feb 2006 05:11:02 -0800, MKoool wrote: > I have an application with one function called "compute", which given a > filename, goes through that file and performs various statistical > analyses. It uses arrays extensively and loops alot. it prints the > results of it's statistical significance tests to standard out. Since > the compute function returns and I think no variables of global scope > are being used, I would think that when it does, all memory returns > back to the operating system. I may be mistaken, and if so I will welcome the correction, but Python does not return memory to the operating system until it terminates. Objects return memory to Python when they are garbage collected, but not the OS. > Instead, what I see is that every iteration uses several megs more. > For example, python uses 52 megs when starting out, it goes through > several iterations and I'm suddenly using more than 500 megs of ram. > > Does anyone have any pointers on how to figure out what I'm doing > wrong? How big is the file you are reading in? If it is (say) 400 MB, then it is hardly surprising that you will be using 500MB of RAM. If the file is 25K, that's another story. How are you storing your data while you are processing it? I'd be looking for hidden duplicates. I suggest you re-factor your program. Instead of one giant function, break it up into lots of smaller ones, and call them from compute. Yes, this will use a little more memory, which might sound counter-productive at the moment when you are trying to use less memory, but in the long term it will allow your computer to use memory more efficiently (it is easier to page small functions as they are needed than one giant function), and it will be much easier for you to write and debug when you can isolate individual pieces of the task in individual functions. Re-factoring will have another advantage: you might just find the problem on your own. -- Steven. From bblais at bryant.edu Mon Feb 6 08:28:23 2006 From: bblais at bryant.edu (Brian Blais) Date: Mon, 06 Feb 2006 08:28:23 -0500 Subject: critique my code, please Message-ID: <43E74EF7.6000004@bryant.edu> Hello, I am including at the end of this document (is it better as an attachment?) some code for a small gui dialog. Since I am quite new to this, if anyone has any suggestions for improvements to the code, bad coding practices, poor gui design, etc... I'd love to hear it. This list has been very helpful to me so far, and I hope to be able to return the favor someday when I get good enough to take the training wheels off. :) The code makes a simple class, with some parameters, some of which are numbers, some boolean, and one which is either a string or a number depending on context. There is a dialog class which allows you to edit/change the values, and a wrapper function of the form: new_params <== wrapper(old_params) which calls the dialog, and returns the updated params instance. thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais import wx import copy class SimulationParams(object): def __init__(self): self.epoch_number=500 self.iter_per_epoch=500 self.epoch_per_display=1 self.random_seed='clock' self.keep_every_epoch=0 self.save_input_vectors=0 def __repr__(self): yesno={0:"No",1:"Yes",True:"Yes",False:"No"} s="Epoch Number: %d\n" % self.epoch_number s=s+"Iter Per Epoch: %d\n" % self.iter_per_epoch s=s+"Epoch Per Display: %d\n" % self.epoch_per_display if (isinstance(self.random_seed,str)): s=s+"Random Seed: %s\n" % self.random_seed else: s=s+"Random Seed: %d\n" % self.random_seed s=s+"Keep Every Epoch: %s\n" % yesno[self.keep_every_epoch] s=s+"Save Input Vectors: %s\n" % yesno[self.save_input_vectors] return(s) class SimulationParamsDialog(wx.Dialog): def __init__(self,params,parent=None): self.params=params wx.Dialog.__init__(self, parent, -1, "Simulation Parameters") sizer = wx.BoxSizer(wx.VERTICAL) box = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, -1, "Epoch_Number:") box.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5) self.text1 = wx.TextCtrl(self, -1, str(params.epoch_number), size=(80,-1)) box.Add(self.text1, 1, wx.ALIGN_CENTRE|wx.ALL, 5) sizer.Add(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5) box = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, -1, "Iterations Per Epoch:") box.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5) self.text2 = wx.TextCtrl(self, -1, str(params.iter_per_epoch), size=(80,-1)) box.Add(self.text2, 1, wx.ALIGN_CENTRE|wx.ALL, 5) sizer.Add(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5) box = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, -1, "Epoch Per Display:") box.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5) self.text3 = wx.TextCtrl(self, -1, str(params.epoch_per_display), size=(80,-1)) box.Add(self.text3, 1, wx.ALIGN_CENTRE|wx.ALL, 5) sizer.Add(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5) box = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, -1, "Random Seed:") box.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5) self.text4 = wx.TextCtrl(self, -1, str(params.random_seed), size=(80,-1)) box.Add(self.text4, 1, wx.ALIGN_CENTRE|wx.ALL, 5) sizer.Add(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5) self.cb1 = wx.CheckBox(self, -1, "Keep Every Epoch") self.cb1.SetValue(params.keep_every_epoch) sizer.Add(self.cb1, 1, wx.GROW|wx.ALIGN_CENTRE|wx.ALL, 5) self.cb2 = wx.CheckBox(self, -1, "Save Input Vectors") self.cb2.SetValue(params.save_input_vectors) sizer.Add(self.cb2, 1, wx.GROW|wx.ALIGN_CENTRE|wx.ALL, 5) btnsizer = wx.StdDialogButtonSizer() btn = wx.Button(self, wx.ID_OK) btn.SetHelpText("The OK button completes the dialog") btn.SetDefault() btnsizer.AddButton(btn) btn = wx.Button(self, wx.ID_CANCEL) btn.SetHelpText("The Cancel button cnacels the dialog. (Cool, huh?)") btnsizer.AddButton(btn) btnsizer.Realize() sizer.Add(btnsizer, 1, wx.GROW|wx.ALIGN_CENTRE|wx.ALL, 5) self.SetSizer(sizer) sizer.Fit(self) def SetSimParams(params): new_params=copy.copy(params) dlg=SimulationParamsDialog(params) val=dlg.ShowModal() if val == wx.ID_OK: new_params.epoch_number=eval(dlg.text1.GetValue()) new_params.iter_per_epoch=eval(dlg.text2.GetValue()) new_params.epoch_per_display=eval(dlg.text3.GetValue()) if (dlg.text4.GetValue()=='clock'): new_params.random_seed='clock' else: new_params.random_seed=eval(dlg.text4.GetValue()) new_params.keep_every_epoch=dlg.cb1.GetValue() new_params.save_input_vectors=dlg.cb2.GetValue() print "ok" else: print "cancel" dlg.Destroy() return(new_params) if __name__ == '__main__': app = wx.PySimpleApp(0) params=SimulationParams() new_params=SetSimParams(params); print params print new_params app.MainLoop() From grisha at apache.org Fri Feb 24 10:16:21 2006 From: grisha at apache.org (Gregory (Grisha) Trubetskoy) Date: Fri, 24 Feb 2006 10:16:21 -0500 Subject: [ANNOUNCE] Mod_python 3.2.8 (security) Message-ID: <20060224101312.B97815@grisha.dyndns.org> The Apache Software Foundation and The Apache HTTP Server Project are pleased to announce the release of version 3.2.8 of mod_python. This release addresses a vulnerability in mod_python's FileSession object whereby a carefully crafted session cookie could potentially permit an attacker to execute code on the server. FileSession was introduced in mod_python 3.2.7 released on February 15 2006 and is not enabled by default, therefore only a very small number of installations, if any, are likely to be affected by this issue. There are no other changes or improvements from the previous version in this release. Mod_python is available for download from: http://httpd.apache.org/modules/python-download.cgi For more information about mod_python visit http://www.modpython.org/ Regards, Gregory Trubetskoy From felipe.lessa at gmail.com Sat Feb 18 09:45:54 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sat, 18 Feb 2006 12:45:54 -0200 Subject: Should we still be learning this? In-Reply-To: References: Message-ID: <1140273955.5255.16.camel@kenshin> Em S?b, 2006-02-18 ?s 15:13 +0200, Max escreveu: > > I wonder if they need some updating. > > > > And so does Dive Into Python (our textbook, diveintopython.org) which > has the same deficiencies in its outline. Are they being *paid* for teaching? Then they should overcome this issue of Dive Into Python by either using their own material our by improving Dive Into Python and giving it back to the community. -- "Quem excele em empregar a for?a militar subjulga os ex?rcitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destr?i os estados dos outros povos sem lutas prolongadas. Deve lutar sob o C?u com o prop?sito primordial da 'preserva??o'. Desse modo suas armas n?o se embotar?o, e os ganhos poder?o ser preservados. Essa ? a estrat?gia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" From gherron at islandtraining.com Tue Feb 21 18:38:17 2006 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 21 Feb 2006 15:38:17 -0800 Subject: Module question In-Reply-To: <1140561649.452528.250880@g44g2000cwa.googlegroups.com> References: <1140559897.172126.43820@o13g2000cwo.googlegroups.com> <1140560655.407740.273490@z14g2000cwz.googlegroups.com> <1140561649.452528.250880@g44g2000cwa.googlegroups.com> Message-ID: <43FBA469.6090607@islandtraining.com> Tuvas wrote: >Could I just do this then? > >from foo import x? > > Yes, you can do it that way. (f you have your modules importing each other in a circular fashion, then this can cause trouble as x may not be defined yet, so best to avoid that case.) >One more question now that I've tried this. In my main function, I have >alot of init code. I don't want this code to be re-ran when the second >module imports the first. Is there any way around this? Thanks! > > > It won't be run twice. Module import is a two phase thing: 1. Read/compile the module and run it, creating a module object. (This is done only once -- the first time a module is imported.) 2. Bind values in the importing code to the module or its attributes. (This is done every time a module is imported.) So... Your init code will be executed once -- in phase 1, no matter how many times an import causes phase two to be performed. Gary Herron From cito at online.de Wed Feb 8 18:17:02 2006 From: cito at online.de (Christoph Zwerschke) Date: Thu, 09 Feb 2006 00:17:02 +0100 Subject: Python 2.4.2 using msvcrt71.dll on Win and compatibility issues In-Reply-To: <43ea40aa$0$6793$9b622d9e@news.freenet.de> References: <43E8F864.6050605@v.loewis.de> <43E922D0.4080407@v.loewis.de> <43ea40aa$0$6793$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > Christoph Zwerschke wrote: >> I think this would only shift the problem. Because then I would have to >> convert the msvcr71 stream I get from Python to a msvcrt stream. Using >> fileno() (of msvcrt) to get the file descriptor will probably not work. > > It actually would: > > #define _fileno(_stream) ((_stream)->_file) > > This definition is the same in all CRT version, plus the _file member > is at the same offset in all CRT versions. Microsoft apparently wants > to support linkage of object files build with one CRT version against > a different CRT version. > > It *is* hacky, of course. I see. So this approach could actually work. Thanks for the hint. -- Christoph From flingfly at gmail.com Thu Feb 16 02:44:38 2006 From: flingfly at gmail.com (yy x) Date: Thu, 16 Feb 2006 15:44:38 +0800 Subject: How to call a mothod in a class by the method name string and the instance? Message-ID: hi, all: for example, the following class: class test: def funca(self): print "in funca" def funcb(self): print "in funcb" t = test() t.funca() In the plain way, i will excute the funca by the code "t.funca() ", but if i wanna to excute the funca by "t" and string "funca", how will i do? maybe the idea is similiar to "call(t, "funca") ". best regards. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVETHIScyber.com.au Mon Feb 20 16:05:22 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 21 Feb 2006 08:05:22 +1100 Subject: Python vs. Lisp -- please explain References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> <1140441519.702761.326130@g14g2000cwa.googlegroups.com> Message-ID: On Mon, 20 Feb 2006 05:18:39 -0800, Kay Schluehr wrote: >> What's far more interesting to me, however, is that I think there a good >> reasons to suspect python's slowness is more of a feature than a flaw: I'd not >> be suprised if on the whole it greatly increases programmer productivity and >> results in clearer and more uniform code. > > Yes, it's Guidos master-plan to lock programmers into a slow language > in order to dominate them for decades. Do you also believe that Al > Quaida is a phantom organization of the CIA founded by neocons in the > early '90s who planned to invade Iraq? Of course not. The alternative, that Osama has been able to lug his dialysis machine all over the Pakistan and Afghan mountains without being detected for four years is *much* more believable. *wink* I don't think it was the poster's implication that Guido deliberately created a slow language for the sake of slowness. I think the implication was more that Guido made certain design choices that increased productivity and code clarity. (That much is uncontroversial.) Where the poster has ruffled some feathers is his suggestion that if Guido had only known more about the cutting edge of language design from CS, Python would have been much faster, but also much less productive, clear and popular. I guess the feather ruffling is because of the suggestion that Guido merely _didn't_know_ about language features that would have increased Python's speed at the cost of productivity, rather than deliberately choose to emphasis productivity at the expense of some speed. -- Steven. From fredrik at pythonware.com Sun Feb 5 09:21:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 5 Feb 2006 15:21:10 +0100 Subject: Interpreting Unicode scripts References: Message-ID: Keith MacDonald wrote: > I am considering embedding Python in a C++ application, which works > internally in UTF-16. The only API I can find for running scripts is > PyRun_SimpleString(const char*). Does that mean that Python is unable to > execute scripts containing characters from more than one code page? reading PEP 263 might help: http://www.python.org/peps/pep-0263.html (summary: encode as utf-8, prepend "# coding: utf-8\n", and you're done) From lucaberto at libero.it Fri Feb 24 10:23:14 2006 From: lucaberto at libero.it (luca72) Date: 24 Feb 2006 07:23:14 -0800 Subject: chrtohex Message-ID: <1140794594.653270.242720@e56g2000cwe.googlegroups.com> Hello again my friends here's my new problem. How i can translate chr in to hex or int to integer value? Best Regards Luca From deets at nospam.web.de Thu Feb 9 13:14:40 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 09 Feb 2006 19:14:40 +0100 Subject: Form1.show() In-Reply-To: <1139506127.717796.284930@z14g2000cwz.googlegroups.com> References: <1139506127.717796.284930@z14g2000cwz.googlegroups.com> Message-ID: <451f4fF4ggbvU1@uni-berlin.de> errmaker schrieb: > hi ! iam newbie on python. > how i can make form1 visible ? form just crated by pyqt > > > > class Form1(QMainWindow): > def __init__(self,parent = None,name = None,fl = 0): > QMainWindow.__init__(self,parent,name,fl) > self.statusBar() > > ............ > > if self.MenuBar.findItem(1): > self.MenuBar.findItem(1).setText(self.__tr("&File")) > if self.MenuBar.findItem(2): > self.MenuBar.findItem(2).setText(self.__tr("&Edit")) > if self.MenuBar.findItem(3): > self.MenuBar.findItem(3).setText(self.__tr("&Help")) > > > def fileNew(self): > print "Form1.fileNew(): Not implemented yet" > > ...... > > > def __tr(self,s,c = None): > return qApp.translate("Form1",s,c) > Look at teh examples of PyQt - you need to have an application instanced and calle its event-loop. Diez From grahn+nntp at snipabacken.dyndns.org Sun Feb 5 12:48:18 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 5 Feb 2006 17:48:18 GMT Subject: how to kill a python process? References: <1139159404.912421.251960@g43g2000cwa.googlegroups.com> Message-ID: On 5 Feb 2006 09:10:04 -0800, MackS wrote: > Hello! > > This question does not concern programming in python, but how to manage > python processes. Is there a way to "name" a python process? At least > on Linux, if I have two python programs running, they both run under > the name "python" ... > Is there a way to make them run under their own names, e.g., to make it > easier to kill them by name using killall? Funny, I had to experiment a bit to see how it worked. This is surely a FAQ, because it's important. IMHO, the interpreter for a Unix program should be invisible, so that the program behaves like as a first-class process in every way. $ python foo1.py This one gets called 'python', as expected. $ head -1 foo2.py #!/usr/bin/env python $ ./foo2.py This one gets called 'python', too. I've been using this version because I read somewhere it was the recommended idiom -- but I will stop doing it now that I know it mangles the process name. $ head -1 foo3.py #!/usr/bin/python $ ./foo3.py This is the traditional shebang form used for shell and Perl scripts, and it names the process 'foo3.py' so you can killall(1) it nicely. > Or am I stuck with > registering the pid of each python process I create and then refer to > that list whenever I need to selectively stop one of them? If a program starts another one and needs to kill it, it /should/ remember its pid. You don't want programs which cannot live together on one machine without killing each other's children. But as I wrote above, you /do/ want to have meaningful information in top(1), ps(1) and so on. Having half a dozen processes named python (or java, or whatever) and wanting to kill one specific is not my idea of fun ... /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From 3dbernard at gmail.com Wed Feb 8 10:19:28 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 8 Feb 2006 07:19:28 -0800 Subject: get output of cmd-line command under MS windows In-Reply-To: References: Message-ID: <61d0e2b40602080719q3bcbc3d1x2be109fe378353f9@mail.gmail.com> You should give a go to os.popen( ). Article 6.1.2 and 6.1.3 in the Python Library doc. I recently wrote a program that would create a pipe using the popen() method, and would enter a while loop. At each iteration, it would read one line of the pipe output, and the loop would break when it gets an empty line (indicating the running application is not running in this case). Example: import os oPipe = os.popen( "run C:/program files/my app/executable.exe" ) while 1: sLine = oPipe.read() print sLine if sLine == '': print 'No more line from pipe, exit.' break Cheers Bernard On 2/8/06, calmar wrote: > Hi all, > > unfotunately, 'commands.getstatusoutput(command)' does not work under > windows. > > Would there be any alternative? > > os.system also just provides the exit number I think. > > thanks a lot, > and cheers > marco > > > -- > calmar > > (o_ It rocks: LINUX + Command-Line-Interface > //\ > V_/_ http://www.calmar.ws > -- > http://mail.python.org/mailman/listinfo/python-list > From sybrenUSE at YOURthirdtower.com.imagination Tue Feb 7 04:17:25 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 7 Feb 2006 10:17:25 +0100 Subject: Detecting line endings References: <1139236514.022464.319970@g14g2000cwa.googlegroups.com> <1139262968.081207.259100@f14g2000cwb.googlegroups.com> Message-ID: Fuzzyman enlightened us with: > This is what I came up with. [...] Comments/corrections welcomed. You could use a little more comments in the code, but apart from that it looks nice. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From steve at REMOVETHIScyber.com.au Fri Feb 17 20:22:11 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 18 Feb 2006 12:22:11 +1100 Subject: Class subscripting References: Message-ID: On Sat, 18 Feb 2006 01:09:22 +0100, Ronny Mandal wrote: > Assume we have a class Foo, and instance called bar. > > a variable called baz1 has the value 3.0, baz2 is uninitialized Python doesn't have variables. It has names which are bound to objects. Do you mean that the name baz1 is bound to the value 3.0? Because Python has no variables, you can't have uninitialized variables. You can have names which are bound to values (objects), and you can have names which don't exist yet. Do you mean that baz2 is a name which doesn't yet exist? In other words, just so we are clear, at this point we have the following Python code: class Foo: pass bar = Foo() baz1 = 3.0 # baz2 not yet used. > Is there a way of reflecting the variable with such syntax: > > print bar[], where var_index is a number representing > internal index. > > bar[] = 4.2. #Setting baz2 to 4.2 No. But you can do better: baz = {} # holder for the values of the bazmatron. baz[1] = 3.0 baz[2] = 4.2 baz[25] = 3.9 # Check if we have the third value for the bazmatron. if baz.has_key(3): # "Look before you leap" print baz[3] # Another way to do the same thing. try: print baz[3] except KeyError: print "No third value. Initializing it now." baz[3] = 0.0 # A third way. print baz.get(3, 0) # Prints 0 if no third value exists. # A fourth way: print baz[3] with a default value of 0, # and set the value if it doesn't already exist. print baz.setdefault(3, 0) -- Steven. From techiepundit at futurepundit.com Thu Feb 2 10:32:06 2006 From: techiepundit at futurepundit.com (Randall Parker) Date: 2 Feb 2006 07:32:06 -0800 Subject: Python vs C for a mail server In-Reply-To: References: <1138728303.669646.36940@g49g2000cwa.googlegroups.com> <1138805854.533303.279610@g49g2000cwa.googlegroups.com> Message-ID: <1138894326.142420.158350@f14g2000cwb.googlegroups.com> Magnus Lycka wrote: > Or...don't you have automated tests? Ouch. If you (like me) feel a > little lazy to write a lot of test scripts, you can use a test tool > such as TextTest, that compares output between test runs, rather than > forcing you to write lots of scripts with plenty of assertions. The > effort required to get started is probably bigger there though. (I > don't really know, it was all set up for me at work.) Magnus, The code I'm writing in Python is a test executive to test embedded C code. Then tests get written in Python that the test executive processes. No, I'm not going to write yet another layer of tests in order to compensate for shortcomings in the Python language. > It's also a pain to write unit tests, but it's much more rewarding > than writing type declarations. Not only does it force you to think > through the ramifications of changes, but you also document your > intentions through your tests. I do not have time to write unit tests for the Python classes. I have plenty of unit tests to write in Python for the embedded C modules. When I run and hit a problem in Python I just debug it and fix it. That's a lot faster than writing unit tests. From rtuhin at gmail.com Wed Feb 1 09:53:11 2006 From: rtuhin at gmail.com (rtuhin at gmail.com) Date: 1 Feb 2006 06:53:11 -0800 Subject: calling a class method in a python module Message-ID: <1138805591.636063.301830@g14g2000cwa.googlegroups.com> Hi I am trying to write a C code to call a class function in a python module. Here's my python module: def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result class MyClass: "A simple example class" i = 12345 def f(self): return 'hello world' Can anybody tell me how to call "f" in my C code? Thanks, Tuhin From reply.in.the.newsgroup at my.address.is.invalid Thu Feb 9 15:40:42 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 09 Feb 2006 21:40:42 +0100 Subject: CLI References: <1139507308.888959.320480@f14g2000cwb.googlegroups.com> Message-ID: mwt: >I want to do programmatic terminal commands on unix with python - i.e. >I want my program to issue commands to start and stop scripts, other >programs, etc. I'm sure this must be fairly straightforward, but >haven't been able to find a reference for it. Any help? http://www.python.org/doc/2.4.2/whatsnew/node8.html -- Ren? Pijlman From bobrien18 at yahoo.com Wed Feb 1 22:54:18 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 1 Feb 2006 19:54:18 -0800 Subject: nDimensional sparse histogram in python. In-Reply-To: <1ha3hrb.z9fahb1cxs03zN%aleaxit@yahoo.com> References: <1138848672.791908.90050@g44g2000cwa.googlegroups.com> <1ha3gff.u4comocxo4ddN%aleaxit@yahoo.com> <1138849589.663600.301610@z14g2000cwz.googlegroups.com> <1ha3hrb.z9fahb1cxs03zN%aleaxit@yahoo.com> Message-ID: <1138852458.567178.116980@g43g2000cwa.googlegroups.com> Ok so this is nice.. Just one thing.. When you try to get a value from a dictionary and it isn't found in the dictionary things go bad... Take this for example: class histogram(object): def __init__(self): self.histo = {} def update(self, point): if self.histo.get(point) != None: self.histo[point] = self.histo[point] + 1 else: self.histo[point] = 1 def get(self, point): return self.histo[point] hist = histogram() hist.update((0,0,0)) hist.update((0,0,1)) hist.update((0,0,1)) hist.get((0,0,0)) hist.get((0,0,1)) hist.get((0,0,2)) spews out this error: Traceback (most recent call last): File "histogram.py", line 21, in ? hist.get((0,0,2)) File "histogram.py", line 12, in get return self.histo[point] KeyError: (0, 0, 2) From franck.perez at gmail.com Fri Feb 3 22:44:28 2006 From: franck.perez at gmail.com (Franck PEREZ) Date: Sat, 4 Feb 2006 04:44:28 +0100 Subject: Automatic class attribute In-Reply-To: <43e3dcfb$1@nntp0.pdx.net> References: <43e3dcfb$1@nntp0.pdx.net> Message-ID: On 2/3/06, Kirk McDonald wrote: > Franck PEREZ wrote: > > Hello all, > > > > Considering the following code : > > > > class C(object): > > ...: observers = [] > > ...: > > ...: @classmethod > > ...: def showObservers(cls): > > ...: print cls.observers > > > > class D1(C): > > ...: observers = [] #could it be moved in C ? > > > > class D2(C): > > ...: observers = [] #could it be moved in C ? > > > > I want each child class of C to have it's own "observers" class attribute. > > > > The code I provided works... but I'd like to avoid typing "observers = > > []" in each child class. > > > > Is it possible to define something in C which would basically mean : > > "for each child class, automatically bind a new list attribute called > > observers" ? > > > > Are metaclasses a way ? Is it possible to avoid them ? > > Thanks a lot, > > Franck > > By an astounding coincidence, I was just working on a similar problem. > Metaclasses can do this, no problem: > > class M(type): > def __init__(cls, name, bases, dict): > cls.observers = [] > > def showObservers(cls): > print cls.observers > > class C(object): > __metaclass__ = M > > class D1(C): pass > class D2(C): pass > > -Kirk McDonald > -- > http://mail.python.org/mailman/listinfo/python-list > Works great. Thanks a lot. From duncan.booth at invalid.invalid Mon Feb 20 03:52:09 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Feb 2006 08:52:09 GMT Subject: share function argument between subsequent calls but not between class instances! References: <11vejkega5tbrc5@corp.supernews.com> <87wtfsb9jc.fsf@rose.polar.local> Message-ID: Ben Finney wrote: > Duncan Booth writes: >> If you intend to only use the default some of the time, and at other >> times pass in a different list, then save the 'default' in the >> instance and use a special marker value to indicate when you intend >> the default to be used: > > The most common idiom for such a marker is the None value. > Can you provide any firm evidence that using None is more common? Both uses are common. Use whichever you are happier with (except of course in the case where None is a potential value distinct from the default). From donn at drizzle.com Mon Feb 20 21:51:43 2006 From: donn at drizzle.com (Donn Cave) Date: Tue, 21 Feb 2006 02:51:43 -0000 Subject: Python vs. Lisp -- please explain References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> <43f8ba1e$0$2895$626a54ce@news.free.fr> <43f8cb3f$0$4225$626a54ce@news.free.fr> <87bqx3glb1.fsf@wilson.homeunix.com> <43f984dc$0$27151$626a54ce@news.free.fr> <873bienwlx.fsf@wilson.homeunix.com> <1140454473.335788@jetspin.drizzle.com> Message-ID: <1140490302.639049@jetspin.drizzle.com> Quoth Steven D'Aprano : ... | Nobody denies that Python code running with no optimization tricks is | (currently) slower than compiled C code. That's a matter of objective | fact. Nobody denies that Python can be easily run in interactive mode. | Nobody denies that *at some level* Python code has to be interpreted. | | But ALL code is interpreted at some level or another. And it is equally | true that at another level Python code is compiled. Why should one take | precedence over the other? I have no idea, what precedence? All I'm saying is that Python matches what people think of as an interpreted language. You can deny it, but but it's going to look like you're playing games with words, and to no real end, since no one could possibly be deceived for very long. If you give me a Python program, you have 3 choices: cross your fingers and hope that I have the required Python interpreter version, slip in a 25Mb Python interpreter install and hope I won't notice, or come clean and tell me that your program needs an interpreter and I should check to see that I have it. Donn Cave, donn at drizzle.com From vinay_sajip at yahoo.co.uk Tue Feb 14 06:29:45 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 14 Feb 2006 03:29:45 -0800 Subject: Logging hangs thread after detaching a StreamHandler's terminal In-Reply-To: References: Message-ID: <1139916585.907286.108290@z14g2000cwz.googlegroups.com> python-list.overbored at spamgourmet.com wrote: > Hi all, > > After many hours, I think I've found a bug in the logging module! > > If you add a (stdout) StreamHandler to a logger, then detach the > terminal for that stdout, subsequent calls to log() will hang the > calling thread. > > To reproduce this, write the following scripts (this was a small test > case I came up with - maybe there's something simpler): > [scripts snipped] > Run ./tryhup.bash. It will sit in an idle spin. Monitor the files > /tmp/hup.out and /tmp/lup.out. Hit Ctrl-C on tryhup to kill it. The > python process is still running, but is stalled (the .out files are no > longer changing). > > If you remove the above labeled line, however, this doesn't happen. > > Can anybody please acknowledge this bug? Any temporary workarounds to > this problem? Thanks in advance for looking into this and for hearing > me in! I tried these scripts on Ubuntu 5.10 and did not see the problem you are experiencing. The script continues to run (printing dashes to the console), and hup.out/lup.out are also updated continuously. What's your configuration? Also, note that the logging module merely opens the stream passed to the StreamHander for output, so check if in your configuration you get a hang just doing a write to sys.stderr. Best regards, Vinay Sajip From john_sips_teaz at yahooz.com Sat Feb 4 22:05:00 2006 From: john_sips_teaz at yahooz.com (John M. Gabriele) Date: Sat, 04 Feb 2006 22:05:00 -0500 Subject: fairly large webapp: from Java to Python. experiences? In-Reply-To: References: <1139005746.363918.267370@g47g2000cwa.googlegroups.com> Message-ID: Shalabh Chaturvedi wrote: > john_sips_teaz at yahooz.com wrote: > > A class-to-class and method-to-method rewrite will give some but likely > not the full benefit of moving to Python. A redesign might be necessary > - making it more 'Pythonic' in the process. In my experience, many cruft > classes that exist in a Java design simply disappear when ported to > Python. See also http://dirtsimple.org/2004/12/python-is-not-java.html > > Cheers, > Shalabh > Great link Shalabh. Thanks. :) Googling around, I'd also come across that one. ---J -- (remove zeez if demunging email address) From bearophileHUGS at lycos.com Fri Feb 10 09:33:27 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 10 Feb 2006 06:33:27 -0800 Subject: To paletted image Message-ID: <1139582007.097659.116740@o13g2000cwo.googlegroups.com> Hello, this time I have a question about PIL usage, maybe if Lundh has some time he can answer me. I am experimenting different color quantization algorithms, so having computed the palette with a clustering function, I use the code below to quantize the original image to produce an image without dithering (so I can see better the quantization results). I have seen that the *standard* distance function I use isn't standard enough, because given the fixed palette computed by me, most graphics programs give me a different (better) quantized image. I don't know what's wrong/different in this quantize function, maybe you can tell me. I'd also like to know if there is a simpler code for PIL to do the same thing (given my palette and a truecolor image), but this is less important. I know the dither=Image.NONE for the im.convert() method, but I don't know a good way to use it in this problem. (Note that the quantize function below uses a perceptual-based color distance, but to do the quantization with PIL I can settle with its standard color distance function.) Thank you, bearophile # Input: # im = input truecolor image # palette = a palette computed by me, of about 32 colors # im_out = output image with no dithering def quantize(data, palette_short): out_data = [] for rgb in data: dist_min = 1e100 closest_col = None for col_pos, pal_col in enumerate(palette_short): # Standard distance #dr = rgb[0] - pal_col[0] #dg = rgb[1] - pal_col[1] #db = rgb[2] - pal_col[2] #d = dr*dr + dg*dg + db*db d = perceptualColorDistance(rgb, pal_col) if d < dist_min: dist_min = d closest_col = col_pos out_data.append(closest_col) return out_data #.......... import psyco; psyco.bind(quantize) # Copy of palette, to speed up quantization palette_short = list(palette) # Add duplicated colors (the last one) to produce a palette of 256 colors palette.extend( palette[-1] for i in xrange(256 - len(palette)) ) # Create empty paletted output image im_out = Image.new("P", im.size, 0) # Flatten the list of colors, for PIL #flattened_palette = flatten(palette) flattened_palette = [component for color in palette for component in color] # Put the computed palette in the output image im_out.putpalette(flattened_palette) # quantize the input image with the computed palette out_data = quantize(data, palette_short) # Put the computed data inside the output image im_out.putdata(out_data) # Save computed output image im_out.save(out_filename) From news at grauer-online.de Sun Feb 19 06:38:26 2006 From: news at grauer-online.de (Uwe Grauer) Date: Sun, 19 Feb 2006 12:38:26 +0100 Subject: ANN: FreeImagePy 1.2.2 In-Reply-To: References: <43f43ec3$0$29107$5fc30a8@news.tiscali.it> Message-ID: Andrew Gwozdziewycz wrote: >> Knowing some details about PIL and as good as no details about >> FreeImage, I would like in this context to become enlightened by the >> answer to the question, when does it make sense to use FreeImage instead >> of PIL? >> From what I know up to now I can't see any use for FreeImage :-( . > > both freeimagepy and freeimage are released under the GPL, PIL is not. > > -- > Andrew Gwozdziewycz > http://ihadagreatview.org > http://plasticandroid.org Did you read the PIL licence? Seems to be a more free licence than GPL. """ A. Software License The Python Imaging Library is: Copyright ? 1997-2003 by Secret Labs AB Copyright ? 1995-2003 by Fredrik Lundh By obtaining, using, and/or copying this software and/or its associated documentation, you agree that you have read, understood, and will comply with the following terms and conditions: Permission to use, copy, modify, and distribute this software and its associated documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appears in all copies, and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Secret Labs AB or the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ Uwe From tim.hochberg at ieee.org Tue Feb 21 17:09:57 2006 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Tue, 21 Feb 2006 15:09:57 -0700 Subject: number ranges In-Reply-To: <7xacckifpd.fsf@ruckus.brouhaha.com> References: <1139945386.3346.38.camel@pc1.cole.uklinux.net> <43F8D881.5030804@sympatico.ca> <43F97AA8.50005@REMOVEMEcyber.com.au> <3_WdnUP9qr9XRmTenZ2dnUVZ_sydnZ2d@comcast.com> <1hb1umb.wr2hsk1chby86N%aleaxit@yahoo.com> <1hb2uq1.e7kdkt1z0ge4rN%aleaxit@yahoo.com> <43FAD679.2040305@REMOVEMEcyber.com.au> <1hb3o4u.trzcp41f11vxqN%aleaxit@yahoo.com> <7xacckifpd.fsf@ruckus.brouhaha.com> Message-ID: [Lots of proposals snipped] 90% of my gripes with range disappeared with the addition of enumerate. However, if there's going to be another round of range literal proposals I might as well throw out what seems (to me anyway) like the only halfway obvious choice in the context of Python. 1. a:b:c is equivalent to slice(a,b,c) with the usual rules that missing values are mapped to None: Parentheses would be required where this construct would otherwise be ambiguous. 2. slice(a,b,c) grows an __iter__ method that returns a generator that produces an appropriate sequence of integers. This is easy to define for positive steps, but tricky for negative steps (more on that in a second). Thus: for i in (1::2): print i, => 1 3 5 ... and for i in (:10:3): print i, => 0 3 6 9 The tricky part is deciding what to with negative steps when the start is undefined. It's tempting to use 0 as the start, but I think -1 is actually better if slightly odd. The reason is that I think the following invariant should hold. newlist = [] for i in someslice: try: newlist.append(origlist[i]) except IndexError: break assert(newlist == origlist[slice]) For that to work out, you want: for i in (::-2): print i, => -1 -3 -5 ... etc. I realize that this is quite similar to the rejected PEP 204 syntax, but the addition of generators has reduced many of the problems that that PEP had. I have no great need for range literals, but it seems that if there were to be one, one that fit together with the existing syntax would be better than making up something new. -tim From cfbolz at gmx.de Sun Feb 5 16:14:30 2006 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Sun, 05 Feb 2006 22:14:30 +0100 Subject: Deterministic destruction and RAII idioms in Python In-Reply-To: <7xoe1tmcnd.fsf@ruckus.brouhaha.com> References: <1138652299.351951.36780@z14g2000cwz.googlegroups.com> <1138669303.907322.272550@g47g2000cwa.googlegroups.com> <7xoe1tmcnd.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > plahey at alumni.caltech.edu writes: > >>I looked at pep-0343, it looks interesting. It is not what I really >>want (deterministic destruction) > > > I think it's better. > > >>As far as my comment about "mainstream" Python, I have always taken >>CPython as "Python". I guess this will have to change as Jython and >>IronPython bring interesting things to the table, even if they do take >>some things away in the process. > > > Hopefully PyPy will become "mainstream". How it handles GC, I'm not sure. Right now PyPy gives (at compile-time) the choice between two GCs: naive reference counting and the conservative Boehm garbage collector (http://research.hp.com/personal/Hans_Boehm/gc/). Currently we are working on supporting other garbage collection strategies as well, like mark-and-sweep, a copying collector or some sort of sophisticated generational collector. Cheers, Carl Friedrich Bolz From steve at REMOVETHIScyber.com.au Sun Feb 19 16:43:25 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 20 Feb 2006 08:43:25 +1100 Subject: Python vs. Lisp -- please explain References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> <43f8ba1e$0$2895$626a54ce@news.free.fr> Message-ID: On Sun, 19 Feb 2006 19:26:20 +0000, Alexander Schmolck wrote: > Bruno Desthuilliers writes: > >> DH a ?crit : >> (snip) >> > It is by design. Python is dynamically typed. It is essentially an >> > interpreted scripting language like javascript or ruby or perl, >> >> >> It's not a "scripting" language, and it's not interpreted. > > Of course it is. What do you think happens to the bytecode? By that logic, all languages are interpreted. What do you think happens to the machinecode? -- Steven. From andychambers2002 at yahoo.co.uk Thu Feb 2 16:30:44 2006 From: andychambers2002 at yahoo.co.uk (andychambers2002 at yahoo.co.uk) Date: 2 Feb 2006 13:30:44 -0800 Subject: classmethod and instance method In-Reply-To: References: <1138910923.048674.264840@g49g2000cwa.googlegroups.com> Message-ID: <1138915844.118266.159770@g14g2000cwa.googlegroups.com> Yes that's better. Didn't know about the __class__ attribute. I thought there must be a way to access this but couldn't find it in the docs. Thanks, Andy From steve at hastings.org Thu Feb 23 04:27:33 2006 From: steve at hastings.org (Steve R. Hastings) Date: Thu, 23 Feb 2006 01:27:33 -0800 Subject: PyAtom, a Python module for creating Atom syndication feeds References: <87mzgicute.fsf@voodoo.myself> Message-ID: > you don't follow PEP 8 guidelines Why do you say this? I don't think the code is perfectly polished and ready to be called version 1.0, but I think it follows PEP 8 more than not. > and AFAIK a module must be widespread and used by > the community before can be accepted in the Python core. I said I intend to donate it to PSF. I didn't say they would do anything with it... :-) That's up to them, of course. > Good job :) Thank you. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From reply.in.the.newsgroup at my.address.is.invalid Mon Feb 20 06:01:12 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 20 Feb 2006 12:01:12 +0100 Subject: multiple email recipients References: <1140425098.309890.116610@o13g2000cwo.googlegroups.com> Message-ID: eight02645999 at yahoo.com: >was wondering how to modify the code so as i can send to multiple email >recipients using "TO"? thanks. You add RFC 2822 headers. http://www.ietf.org/rfc/rfc2822.txt ("3.6.3. Destination address fields") -- Ren? Pijlman From kent at kentsjohnson.com Sat Feb 11 08:30:43 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sat, 11 Feb 2006 08:30:43 -0500 Subject: Jython inherit from Java class In-Reply-To: <1139594138.216488.12730@g14g2000cwa.googlegroups.com> References: <1139344211.725580.263660@g47g2000cwa.googlegroups.com> <43eab05b_2@newspeer2.tds.net> <1139594138.216488.12730@g14g2000cwa.googlegroups.com> Message-ID: <43ede2b8$1_1@newspeer2.tds.net> Mark Fink wrote: > Alan, Kent, many thanks this really helped! > But there is still a problem I guess with inheritance. I use the java > testsuit supplied with the original to test the server. If I use the > Java FitServer the testsuite can be completed. I commented everything > out from my class and it does not work?? Since you are getting the same error from the Java server and the Jython subclass maybe you should figure out the Java problem first? It seems to be a problem making a socket connection of some kind. Kent > ###### And the Java FitServer: > D:\AUT_TEST>java -cp D:\\AUT_TEST\\fitnesse\\fitnesse.jar fit.FitServer > localhost 1234 23 > Exception in thread "main" java.net.ConnectException: Connection > refused: connect > at java.net.PlainSocketImpl.socketConnect(Native Method) > at java.net.PlainSocketImpl.doConnect(Unknown Source) > at java.net.PlainSocketImpl.connectToAddress(Unknown Source) > at java.net.PlainSocketImpl.connect(Unknown Source) > at java.net.SocksSocketImpl.connect(Unknown Source) > at java.net.Socket.connect(Unknown Source) > at java.net.Socket.connect(Unknown Source) > at java.net.Socket.(Unknown Source) > at java.net.Socket.(Unknown Source) > at fit.FitServer.establishConnection(Unknown Source) > at fit.FitServer.establishConnection(Unknown Source) > at fit.FitServer.run(Unknown Source) > at fit.FitServer.main(Unknown Source) From zhangchao19 at hotmail.com Fri Feb 24 00:28:06 2006 From: zhangchao19 at hotmail.com (cn.popeye) Date: Fri, 24 Feb 2006 13:28:06 +0800 Subject: Use UltraEdit run Python Message-ID: Use UltraEdit run Python Run UltraEdit Menu :Advanced menu/Tool Configuration command Command Line: python %n%e Working Directory:%p Menu Item Name: run python checked "Save Active File" Command Output (DOS Commands ONLY) checked " Capture the output to a list box " click button "insert" Action: %P Path only ("C:\project\test\") %N fileName only ("test") %E Extension only (".py") %P%N%E is equal to %F which is ("C:\project\test\test.py") in the example above. ------test.py------- #Welcome Messages! This is test! print 'welcome to Python world!!! ' run *.py Menu: Advanced menu/run python -- cn.popeey From localpricemaps at gmail.com Thu Feb 9 02:01:18 2006 From: localpricemaps at gmail.com (localpricemaps at gmail.com) Date: 8 Feb 2006 23:01:18 -0800 Subject: how to remove
using replace function? In-Reply-To: <1139464079.635612.289930@o13g2000cwo.googlegroups.com> References: <1139462640.951603.302830@g44g2000cwa.googlegroups.com> <1139464079.635612.289930@o13g2000cwo.googlegroups.com> Message-ID: <1139465097.718510.291570@g47g2000cwa.googlegroups.com> tried that, didn't work for me From donn at u.washington.edu Tue Feb 21 12:46:27 2006 From: donn at u.washington.edu (Donn Cave) Date: Tue, 21 Feb 2006 09:46:27 -0800 Subject: Python vs. Lisp -- please explain References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> <43f8ba1e$0$2895$626a54ce@news.free.fr> <43f8cb3f$0$4225$626a54ce@news.free.fr> <87bqx3glb1.fsf@wilson.homeunix.com> <43f984dc$0$27151$626a54ce@news.free.fr> <873bienwlx.fsf@wilson.homeunix.com> <1140454473.335788@jetspin.drizzle.com> <1140490302.639049@jetspin.drizzle.com> <43FAD2C2.7080908@REMOVEMEcyber.com.au> Message-ID: In article <43FAD2C2.7080908 at REMOVEMEcyber.com.au>, Steven D'Aprano wrote: ... > Hey Donn, here is a compiled program for the PowerPC, > or an ARM processor, or one of IBM's Big Iron > mainframes. Or even a Commodore 64. What do you think > the chances are that you can execute it on your > x86-compatible PC? It's compiled, it should just > work!!! Right? > > No of course not. If your CPU can't interpret the > machine code correctly, the fact that the code is > compiled makes NO difference at all. > > In other words, I have three choices: > > - cross my fingers and hope that you have the required > interpreter (CPU); > > - slip in an interpreter install (perhaps an emulator) > and hope you won't notice; > > - or come clean and tell you that my program needs an > interpreter ("Hey Donn, do you have a Mac you can run > this on?") and you should check to see that you have it. Sure, all this is true, except for the term "interpreter." You would surely not use the word that way, unless you just didn't want to communicate. Your paragraph above that starts with "No of course not", even omits a point that everyone understands, you can in fact expect a .py file will work independent of machine architecture - like any interpreted language. We all know what native code compilation buys you and what it doesn't. Donn Cave, donn at u.washington.edu From steve at REMOVETHIScyber.com.au Sun Feb 12 12:38:03 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 13 Feb 2006 04:38:03 +1100 Subject: Is Forth for real? References: <1139690972.344818.136870@f14g2000cwb.googlegroups.com> <1139754010.067582.214830@z14g2000cwz.googlegroups.com> <1v44c3-geo.ln1@lairds.us> Message-ID: On Sun, 12 Feb 2006 17:08:02 +0000, Cameron Laird wrote: > In article , > Steven D'Aprano wrote: > . > . > . >>on the web for each language. By comparison, even Forth gives 13 million >>plus hits, and who uses Forth? > . > . > . > The programmers of, among other things, the FedEx bar-code reader, > the Sun boot loader, and parts of the Space Shuttle. Okay, so that's three... *wink* You missed Apple's boot loader. I love Forth. I'm no good at thinking at that low count-the-bytes level, but if I was, I'd much prefer to use Forth than C or assembly. I've got a bunch of Forth books here, and when I'm bored I read them for entertainment, and dream. I love the fact that Forth is still in use. But I'm under no illusions that there are millions of Forth developers getting paid to write in Forth. -- Steven. From carsten at uniqsys.com Fri Feb 17 16:38:38 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 17 Feb 2006 16:38:38 -0500 Subject: Add a month In-Reply-To: <312cfe2b0602171310t59e5dc04ucfae760822e329d7@mail.gmail.com> References: <1140173540.686250.205760@g44g2000cwa.googlegroups.com> <1140178539.803209.84960@g47g2000cwa.googlegroups.com> <312cfe2b0602171308j2e6ed284t2c5dd2c130166db1@mail.gmail.com> <312cfe2b0602171310t59e5dc04ucfae760822e329d7@mail.gmail.com> Message-ID: <1140212318.32102.97.camel@dot.uniqsys.com> On Fri, 2006-02-17 at 16:10, Gregory Pi?ero wrote: > Actually, no wait, that's bad. It doesn't increment the year. > > Does anyone have a simple way to code this? > > -Greg > > > On 2/17/06, Gregory Pi?ero wrote: > > Here's how I do it: > > > > def monthify(anint): > > if anint%12==0:return 12 > > else:return anint%12 > > > > import datetime > > d=datetime.datetime.today() > > dplus1month=datetime.datetime(d.year,monthify(d.month+1),d.day) > > > > We need monthify because adding 1 to 12 is bad otherwise! > > > > -Greg > > > > On 17 Feb 2006 04:15:39 -0800, Paul Boddie wrote: > > > Fredrik Lundh wrote: > > > > > > > > what do you expect d_new to be after the operation ? if the answer > > > > is date(2006,3,17), what's date(2006,1,31) plus one month? > > > > > > February 31st, of course: > > > > > > http://sql-info.de/mysql/gotchas.html#1_14 > > > > > > ;-) > > > > > > Paul > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > -- > > Gregory Pi?ero > > Chief Innovation Officer > > Blended Technologies > > (www.blendedtechnologies.com) > > > > I don't know if this qualifies as simple, but it seems to work: def addmonths(thedate,months): "Add months to ." import datetime y,m,d = thedate.timetuple()[:3] y2, m2 = divmod(m+months-1, 12) return datetime.date(y+y2,m2+1,d) Note that the date constructor will raise an exception if the result happens to be an invalid date such as February 30th or November 31st. -Carsten From frank at chagford.com Tue Feb 7 08:44:33 2006 From: frank at chagford.com (Frank Millman) Date: 7 Feb 2006 05:44:33 -0800 Subject: Problem with odbc (pywin32) and unicode In-Reply-To: <1138360733.866147.29680@g14g2000cwa.googlegroups.com> References: <1138360733.866147.29680@g14g2000cwa.googlegroups.com> Message-ID: <1139319873.933801.173190@z14g2000cwz.googlegroups.com> Frank Millman wrote: > Hi all > > I am using odbc from pywin32 to connect to MS SQL Server. I am changing > my program from the old (incorrect) style of embedding values in the > SQL command to the new (correct) style of passing the values as > parameters. I have hit a problem. > > The following all work - > cur.execute("select * from users where userid = '%s'" % 'frank') # > old style > cur.execute("select * from users where userid = '%s'" % u'frank') > # old style > cur.execute("select * from users where userid = ?", ['frank']) # > new style > > This does not work - > cur.execute("select * from users where userid = ?", [u'frank']) # > new style > > I get the following error - > OdbcError: Found an insert row that didn't have 1 columns [sic] > > It is the combination of new style and unicode that does not work. > > I realise that odbc is not fully DB-API compliant, but I have got away > with it up to now. Does anyone know of a solution to this problem? > > Thanks > > Frank Millman > I am pleased to report that this has been fixed. I have been liaising with Mark Hammond, and he has sent me a revised version which behaves correctly. This is from Mark - "I'd be happy for you to mention this fix will be in build 208 - I just can't tell you when that will be :)" Frank From reply.in.the.newsgroup at my.address.is.invalid Wed Feb 15 11:55:29 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 15 Feb 2006 17:55:29 +0100 Subject: Embedding a binary file in a python script References: <1140021879.698353.324230@o13g2000cwo.googlegroups.com> Message-ID: mrstephengross: >I want to find a way to embed a tar file *in* my python script, and >then use the tarfile module to extract it. That is, instead of >distributing two files (extractor.py and archive.tar) I want to be able >to distribute *one* file (extractor-with-embedded-archive.py). Is there >a way to do this? I guess you can uuencode your tar file, and put the result in a multiline string. See module 'uu'. -- Ren? Pijlman From fuzzyman at gmail.com Wed Feb 22 16:16:14 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 22 Feb 2006 13:16:14 -0800 Subject: Newbie question: Multiple installations of Python on Windows machines In-Reply-To: References: <1140519304.913540.296600@g14g2000cwa.googlegroups.com> Message-ID: <1140642974.386791.107270@o13g2000cwo.googlegroups.com> Don Taylor wrote: > Fuzzyman wrote: > > > A lot of 'exe' installers are special types of zip archvies. You might > > be able to open it using winzip or winrar and do a manual install. > > Interesting suggestion that would never have occured to me. One of the > unzippers I tried (IZArc) did show me a directory of the contents, but > it would still not let me extract the files. > > > Another alternative is to use the free VMWare player to create a fresh > > windows install that will run in a window. You can then install Python > > 2.3 and your application and extract the files you need to see if you > > can make it work under Python 2.4. > > So I tried this and copied the files from my virtual machine to the > site-packages folder on my real Python 2.4 machine, I then ran into > there being a compiled extension. > > > > If the application contains compiled extensions then they won't be > > portable from Python 2.3 to Python 2.4 - however the application will > > almost certainly run with Movable Python 2.3 (which won't interfere at > > all with your Python 2.4 install). > > > > http://www.voidspace.org.uk/python/movpy/ > > I could use a virtual machine with 2.3 installed, but neither option > appeals to me right now as I want to use the rest of my Python installed > stuff (and Eclipse Pydev) stuff - which is why I wanted to continue > with Python 2.4 in the first place. > > I have got a copy of the C source for the extension, can anybody give > me/point me a cookbook recipe for making my own version of the extension > that will play with 2.4? This is for Windows XP and I don't currently > have a C compiler installed. > It means installing a compiler (but I don't see a way around that) - but this worked for me : http://www.vrplumber.com/programming/mstoolkit/index.html So long as the module can be installed with distutils, the instuctions there will work for you. Hefty download though. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > > Fuzzyman > > Some great suggestions. > > Thanks, > > Don. From cito at online.de Wed Feb 8 03:44:16 2006 From: cito at online.de (Christoph Zwerschke) Date: Wed, 08 Feb 2006 09:44:16 +0100 Subject: apostrophe or double quote? In-Reply-To: References: <1139370460.360400.232500@z14g2000cwz.googlegroups.com> Message-ID: Steve Holden wrote: > It's just easier to have two permitted string quotes. That way, if your > string has an apostrophe in it you can say > > s = "it's" It's particularly handy if you are building strings of a language that already has its own quotes, e.g. SQL or XML: sql_snippet = " where name='Max'" html_snippet = ' align="left"' -- Christoph From steve at REMOVETHIScyber.com.au Mon Feb 27 06:18:12 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 27 Feb 2006 22:18:12 +1100 Subject: how do I factor a number down to one digit? References: <1141036302.641818.72570@i39g2000cwa.googlegroups.com> Message-ID: On Mon, 27 Feb 2006 02:31:42 -0800, Allan wrote: > I'm trying to write a numerology program where I have each letter > identified by a numerical value like > a=1 > b=2 > c=3 > as so forth. I then input a name. How do I treat each letter as a > single value? That is, instead of print myname I have to do a print > m+y+n+a+m+e which returns a number. I next want to convert the > resulting two or three digit number to a single digit. Like 123 would > be 1+2+3 returning a 5. I hope this isn't too stupid of a question. Sounds like homework to me. Here is a hint: myname = "steven" for c in myname: do_something_with(c) does some work with each individual letter of myname. You want something that takes 'a', and gives 1, 'b' which gives 2, 'c' which gives 3, and so forth. In other words, you want to map letters of the alphabet to numbers. Hint: experiment with dictionaries. sum = 0 myname = "steven" for c in myname: sum = sum + map_letter_to_number_somehow That's the first half of the problem. Chew on that for a while, and if you still need help, come back and ask. -- Steven. From erniedude at gmail.com Mon Feb 6 11:51:24 2006 From: erniedude at gmail.com (Ernesto) Date: 6 Feb 2006 08:51:24 -0800 Subject: Size of list In-Reply-To: References: <1139243538.269506.214060@f14g2000cwb.googlegroups.com> Message-ID: <1139244684.381944.294440@f14g2000cwb.googlegroups.com> Thanks ! From deets at nospam.web.de Fri Feb 17 06:58:09 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 17 Feb 2006 12:58:09 +0100 Subject: Terminating a function References: Message-ID: <45ls4mF7ch23U1@uni-berlin.de> Astan Chee wrote: > Hi, > Im rather new to threads in python but Im trying to terminate a function > call (or the execution of the function) after a certain period of time > has passed. > Do i need to use threads with this? if i do, how do i go about doing it? Yes and no. As you didn't tell us muc about your actual problem, threads might be what you need. But you _can't_ just stop a thread - however, depending on what you do, you can for example regularly check for a flag inside your function and then terminate: class Foo(threading.Thread): def __init__(self): super(Foo, self).__init__() self.setDaemon(True) self.interrupted = False def run(self): while not self.interrupted: do_some_work_but_make_sure_to_come_back_regularly() f = Foo() f.start() time.sleep(10) f.interrupted = True Diez From grante at visi.com Tue Feb 21 10:07:26 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 21 Feb 2006 15:07:26 -0000 Subject: Print a PDF transparently References: Message-ID: <11vmb5ehmh5ro7f@corp.supernews.com> On 2006-02-20, Tim Golden wrote: > [Daniel Crespo] >| >| > Have you seen this? >| > http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html >| > In particular, the section on using win32print directly. >| >| Yes, I have. The problems is that an external program is launched for >| handling the file and print it. > > [sorry, bit long-winded, but trying to help] > > I think the poster was referring to the situation you > described where the problem reduced to sending a .ps > file directly to a postscript-capable printer. People are still using OS distributions that don't know how to print Postscript or PDF "out of the box"? All of the decent Linux distros have had the ability to print postscript/PDF files "transparently" for many, many years (even to non-postscript printers). Sheesh. -- Grant Edwards grante Yow! Four thousand at different MAGNATES, MOGULS visi.com & NABOBS are romping in my gothic solarium!! From steve at holdenweb.com Tue Feb 21 04:10:22 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 21 Feb 2006 04:10:22 -0500 Subject: fast text processing In-Reply-To: References: Message-ID: <43FAD8FE.2050403@holdenweb.com> Alexis Gallagher wrote: > (I tried to post this yesterday but I think my ISP ate it. Apologies if > this is a double-post.) > > Is it possible to do very fast string processing in python? My > bioinformatics application needs to scan very large ASCII files (80GB+), > compare adjacent lines, and conditionally do some further processing. I > believe the disk i/o is the main bottleneck so for now that's what I'm > optimizing. What I have now is roughly as follows (on python 2.3.5). > > filehandle = open("data",'r',buffering=1000) This buffer size seems, shall we say, unadventurous? It's likely to slow things down considerably, since the filesystem is probably going to naturally wnt to use a rather larger value. I'd suggest a 64k minumum. > > lastLine = filehandle.readline() > I'd suggest lastTokens = filehandle.readline().strip().split(delimiter) here. You have no need of the line other than to split it into tokens. > for currentLine in filehandle.readlines(): > Note that this is going to read the whole file in to (virtual) memory before entering the loop. I somehow suspect you'd rather avoid this if you could. I further suspect your testing has been with smaller files than 80GB ;-). You might want to consider for currentLine in filehandle: as an alternative. This uses the file's generator properties to produce the next line each time round the loop. > lastTokens = lastLine.strip().split(delimiter) The line above goes away if you adopt the loop initialization suggestion above. Otherwise you are repeating the splitting of each line twice, once as the current line then again as the last line. > currentTokens = currentLine.strip().split(delimiter) > > lastGeno = extract(lastTokens[0]) > currentGeno = extract(currentTokens[0]) > If the extract() operation is stateless (in other words if it always produces the same output for a given input) then again you are unecessarily repeating yourself here by running extract() on the same data as the current first token and the last first token (if you see what I mean). I might also observe that you seem to expect only two tokens per line. If this is invariable the case then you might want to consider writing an unpacking assignment instead, such as cToken0, cToken1, newline = currentLine.strip().split(delimiter) to save the indexing. Not a big deal, thugh, and it *will* break if you have more than one delimiter in a line, as the interpreter won;t then know what to do with the third and subsequent elements. > # prepare for next iteration > lastLine = currentLine > Of course now you are going to try and strip the delimiter off the line and split it again when you loop around again. You should now just be able to say lastTokens = currentTokens instead. > if lastGeno == currentGeno: > table.markEquivalent(int(lastTokens[1]),int(currentTokens[1])) > > So on every iteration I'm processing mutable strings -- this seems > wrong. What's the best way to speed this up? Can I switch to some fast > byte-oriented immutable string library? Are there optimizing compilers? > Are there better ways to prep the file handle? > I'm sorry but I am not sure where the mutable strings come in. Python strings are immutable anyway. Well-known for it. It might be a slight problem that you are creating a second terminator-less copy of each line, but that's probably inevitable. Of course you leave us in the dark about the nature of table.markEquivalent as well. Depending on the efficiency of the extract() operation you might want to consider short-circuiting the loop if the two tokens have already been marked as equivalent. That might be a big win or not depending on relative efficiency. > Perhaps this is a job for C, but I am of that soft generation which > fears memory management. I'd need to learn how to do buffered reading in > C, how to wrap the C in python, and how to let the C call back into > python to call markEquivalent(). It sounds painful. I _have_ done some > benchmark comparisons of only the underlying line-based file reading > against a Common Lisp version, but I doubt I'm using the optimal > construct in either language so I hesitate to trust my results, and > anyway the interlanguage bridge will be even more obscure in that case. > Probably the biggest gain will be in simply not reading the whole file into memory by calling its .readlines() method. Summarising. consider something more like: filehandle = open("data",'r',buffering=64*1024) # You could also try just leaving the buffering spec out lastTokens = filehandle.readline().strip().split(delim) lastGeno = extract(lastTokens[0]) for currentLine in filehandle: currentTokens = currentLine.strip().split(delim) currentGeno = extract(currentTokens[0]) if lastGeno == currentGeno: table.markEquivalent(int(lastTokens[1]), int(currentTokens[1])) lastGeno = currentGeno lastTokens = currentTokens > Much obliged for any help, > Alexis Hope this is. one last thought: the bioPython package will potentially save you huge amounts of time. They guys who developed and maintain it have done a lot of genome-slinging, and they appear to know what they are doing. They may have already solved several problems you are struggling with. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From python at hope.cz Tue Feb 14 02:40:56 2006 From: python at hope.cz (Lad) Date: 13 Feb 2006 23:40:56 -0800 Subject: Encoding In-Reply-To: <1139854271.073914.37950@o13g2000cwo.googlegroups.com> References: <1139853781.611888.60230@g44g2000cwa.googlegroups.com> <1139854271.073914.37950@o13g2000cwo.googlegroups.com> Message-ID: <1139902856.631907.105790@o13g2000cwo.googlegroups.com> Yes, 'some data'.decode('utf8').encode('windows-1250') works great. Thanks L.B. From klachemin at comcast.net Wed Feb 15 15:48:51 2006 From: klachemin at comcast.net (Kamilche) Date: 15 Feb 2006 12:48:51 -0800 Subject: Publish/subscribe event manager using weakrefs Message-ID: <1140036531.473680.95360@f14g2000cwb.googlegroups.com> ''' event.py An event manager using publish/subscribe, and weakrefs. Any function can publish any event without registering it first, and any object can register interest in any event, even if it doesn't exist yet. The event manager uses weakrefs, so lists of listeners won't stop them from being garbage collected when they're deleted. Any suggestions are appreciated! Sample output: >>> EVENT init (0 listeners, possibly dead) ('No one is interested in this event',) EVENT ball (0 listeners, possibly dead) ('Look! A ball, but no one is watching.',) *** Fido is interested in Bone *** Fido is interested in Ball EVENT ball (1 listeners, possibly dead) ('Another ball! Watch, Fido!',) *** Fido noses the ball forward *** Fido is dead. EVENT ball (1 listeners, possibly dead) ('No one is watching because Fido is dead.',) Removing from ball *** Snowball is interested in Ball *** Snowball is interested in Yarn *** Snowball is interested in Fluffy chick *** Spot is interested in Bone *** Spot is interested in Ball EVENT bone (2 listeners, possibly dead) ('Only dogs eat bones.',) Removing from bone *** Spot slobbers on the bone EVENT ball (2 listeners, possibly dead) ('Cats and dogs both love this one!',) *** Snowball chases the ball *** Spot noses the ball forward EVENT yarn (1 listeners, possibly dead) ('ball of pink yarn',) *** Snowball bats at the yarn. EVENT raking (0 listeners, possibly dead) ('Humans working in the yard',) EVENT fluffychick (1 listeners, possibly dead) ('Ooh, how cute! An Easter leftover walking in the yard.',) *** Snowball eats the fluffy chick. Removing listener {'name': 'Snowball'} from event fluffychick EVENT fluffychick (0 listeners, possibly dead) ('The cat is full and no longer interested in chicks.',) *** Snowball is dead. *** Spot is dead. EVENT ball (2 listeners, possibly dead) ('Ball anyone? Fluffy? Spot? Fido?',) Removing from ball Removing from ball Done! >>> ''' import weakref _events = {} def Subscribe(eventname, self): " Subscribe to an event, even if it doesn't exist yet." eventname = eventname.lower() eventname = eventname.replace(' ', '') if not eventname in _events: _events[eventname] = [] listeners = _events[eventname] obj = weakref.ref(self) if not obj in listeners: listeners.append(obj) def Unsubscribe(eventname, self): " Unsubscribe from an event, even if it never existed." eventname = eventname.lower() eventname = eventname.replace(' ', '') if not eventname in _events: return listeners = _events[eventname] obj = weakref.ref(self) if obj in listeners: print "Removing listener %s from event %s" % (str(self), eventname) listeners.remove(obj) def Raise(eventname, *args, **kwargs): " Publish an event, no need to register it first." eventname = eventname.lower() eventname = eventname.replace(' ', '') if not eventname in _events: _events[eventname] = [] listeners = _events[eventname] print "EVENT %s (%d listeners, possibly dead) %s" % (eventname, len(listeners), str(args)) i = 0 while i < len(listeners): obj = listeners[i] listener = obj() if listener: fnname = 'On' + eventname[0].upper() + eventname[1:].lower() fn = getattr(listener, fnname, None) if fn == None: fn = getattr(listener, 'OnEvent') fn(eventname, *args, **kwargs) i += 1 else: print "Removing %s from %s" % (str(obj), eventname) listeners.remove(obj) class Listener: ''' Objects that want to be notified of events. They should have an 'OnEventname' function for every event they're interested in, or a single function called 'OnEvent' to receive all events. ''' _listen = [] def __init__(self, **kwargs): self.__dict__.update(kwargs) for eventname in self._listen: Subscribe(eventname, self) print "*** %s is interested in %s" % (self.name, eventname) def OnEvent(self, eventname, *args, **kwargs): print "*** %s(%s, %s)" % (eventname, str(args), str(kwargs)) def __str__(self): return str(self.__dict__) def __del__(self): print "*** %s is dead." % self.name def main(): class Dog(Listener): name = 'Dog' _listen = ['Bone', 'Ball'] def OnEvent(self, eventname, *args, **kwargs): if eventname == 'bone': print "*** %s slobbers on the bone" % self.name elif eventname == 'ball': print "*** %s noses the ball forward" % self.name class Cat(Listener): name = 'Cat' _listen = ['Ball', 'Yarn', 'Fluffy chick'] def OnBall(self, *args, **kwargs): print "*** %s chases the ball" % self.name def OnYarn(self, *args, **kwargs): print "*** %s bats at the yarn." % self.name def OnFluffychick(self, *args, **kwargs): print "*** %s eats the fluffy chick." % self.name Raise('INIT', 'No one is interested in this event') Raise('BALL', 'Look! A ball, but no one is watching.') dog = Dog(name = 'Fido') Raise('BALL', 'Another ball! Watch, Fido!') del dog Raise('BALL', 'No one is watching because Fido is dead.') cat = Cat(name = 'Snowball') dog = Dog(name = 'Spot') Raise('BONE', "Only dogs eat bones.") Raise('BALL', "Cats and dogs both love this one!") Raise('YARN', "ball of pink yarn") Raise('RAKING', 'Humans working in the yard') Raise('Fluffy chick', 'Ooh, how cute! An Easter leftover walking in the yard.') Unsubscribe('fluffy chick', cat) Raise('Fluffy chick', 'The cat is full and no longer interested in chicks.') del cat del dog Raise('BALL', 'Ball anyone? Fluffy? Spot? Fido?') print "Done!" if __name__ == '__main__': main() From saunders2005 at plusdsl.net Sun Feb 5 20:09:42 2006 From: saunders2005 at plusdsl.net (Stephen) Date: Mon, 6 Feb 2006 01:09:42 -0000 Subject: Newbie Help! Message-ID: <43e6a1d4$0$6951$ed2619ec@ptn-nntp-reader02.plus.net> Hi All, im new to python i just have a few questions and was wondering if you could help me?? 1. what programming langaugue does python use? or which is most popular? 2. Does anyone know where i could get hold of practice code 3. Any good ebooks or links to start with. (according to the web this is the best place to start.) i know you probally get asked these questions all the time! but im trying to mirgrate for windows to linux. Cheers all CFR From abhinavduggal at gmail.com Sun Feb 19 10:37:57 2006 From: abhinavduggal at gmail.com (abhinav) Date: 19 Feb 2006 07:37:57 -0800 Subject: Python multithreading on cluster system? Embedding python in PVM? Message-ID: <1140363477.929902.44890@g44g2000cwa.googlegroups.com> Hi guys.I have read that one cannot perform true multithreading in python due to global interpreter lock mechanism.Suppose i have to implement a crawler on a say cluster system like clusterknoppix so that i can use parallel virtual machine (PVM)for programming in multiprocessor environment or say open MPI.Can i integrate python with PVM or MPI.Can i embed python into C for programming in multiprocessor environment.Is there any way of embedding python in PVM or MPI so that i can implement a true cluster based search engine? Any help would be very kind.Thanks. From mike.klaas at gmail.com Mon Feb 27 17:05:30 2006 From: mike.klaas at gmail.com (Klaas) Date: 27 Feb 2006 14:05:30 -0800 Subject: bsddb3 database file, are there any unexpected file size limits occuring in practice? In-Reply-To: References: <1140670193.599122.325800@z34g2000cwc.googlegroups.com> Message-ID: <1141077930.320242.97990@v46g2000cwv.googlegroups.com> Claudio writes: > I am on a Windows using the NTFS file system, so I don't expect problems > with too large file size. how large can files grow on NTFS? I know little about it. > (I suppose it in having only 256 MB RAM available that time) as it is > known that MySQL databases larger than 2 GByte exist and are in daily > use :-( . Do you have more ram now? I've used berkeley dbs up to around 5 gigs in size and they performed fine. However, it is quite important that the working set of the database (it's internal index pages) can fit into available ram. If they are swapping in and out, there will be problems. -Mike From claird at lairds.us Thu Feb 9 22:08:02 2006 From: claird at lairds.us (Cameron Laird) Date: Fri, 10 Feb 2006 03:08:02 GMT Subject: Hi reliability files, writing,reading,maintaining References: <43eb4480$0$11064$e4fe514c@news.xs4all.nl> <1uQGf.274691$vl2.62908@fe2.news.blueyonder.co.uk> Message-ID: In article <1uQGf.274691$vl2.62908 at fe2.news.blueyonder.co.uk>, John Pote wrote: . . . >The motivation to look at http: is the widespread avaiability of internet >connections and standard servers able to run CGI scripts. In particular the >availability of low cost GPRS modems (solar panel and/or wind gen) is very >attractive for remote locations where there is no power, telephone line or >cable company. . . . Ah! I *completely* understand, now. We actually do some of the same ... Now that I have a fuller grasp of your situation, let me think over the weekend. I like projects like this. From bblais at bryant.edu Sun Feb 5 16:26:25 2006 From: bblais at bryant.edu (Brian Blais) Date: Sun, 05 Feb 2006 16:26:25 -0500 Subject: Numeric and matlab Message-ID: <43E66D81.20906@bryant.edu> Hello, Most of my experience is with Matlab/Octave, so I am a Python newbie (but enjoying it! :) ) There are a lot of things that I do in Matlab that I'd like to know the proper way to do in Python. Here are a few: MATLAB: % example vectors a=1:10; b=-5:.1:5; % set all the values above 5 equal to 6 idx=find(a>5); a(idx)=6; % extract elements idx=find(b>0) b=b(idx); % meshgrid...usually to go through all possibly values of a parameter [x,y]=meshgrid(1:10,-5:.1:5) x=x(:); y=y(:); for i=1:length(x) % do something with x(i) and y(i) end I'm sure there are more, but these jump out at me as I'm going. It seems as if the idx=find() stuff can be done with Numeric.nonzeros(), but you can't index with that, like a=Numeric.arange(1,11,1) idx=Numeric.nonzeros(a) a=a[idx] % doesn't work and what about meshgrid? Do I use the fromfunction() in some way? Is there a resource that goes through comparisons like this? thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From aleaxit at yahoo.com Mon Feb 20 12:12:40 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Feb 2006 09:12:40 -0800 Subject: Quesion about the proper use of __slots__ References: <1140424508.393412.79140@o13g2000cwo.googlegroups.com> <43f9825e$0$4777$636a55ce@news.free.fr> <1140426860.033363.237150@o13g2000cwo.googlegroups.com> <1140428016.170547.315710@g47g2000cwa.googlegroups.com> <1140432487.272405.297100@f14g2000cwb.googlegroups.com> <1140434225.164304.230440@z14g2000cwz.googlegroups.com> <1140438776.231178.205500@g43g2000cwa.googlegroups.com> Message-ID: <1hb1w3a.184r7nf13isra3N%aleaxit@yahoo.com> wrote: > Peter Otten wrote: > > > He could be working on a machine with < 1M RAM or some other > > > constraints. > > > > I have 256K, by the way. > > > Impressive, curious to know what kind of environment it is as it has > been a long time I have seen such limited spec. My first x86(IBM PC) > had more than that. I believe some cellphones and similarly limited devices may go as low as 256k, but I don't think anybody's running Python today on any device with less than a MB (and more likely more). The first PC _I_ owned had 4K of RAM (the cheaper model only had 1K, but I splurged for the big one) -- Sinclair ZX80. But I didn't run Python on it (indeed I soon swapped it for one with very similar HW but Forth instead of Basic, called the "Jupiter Ace": Forth's force has always been the ability to run with incredibly-little memory). Alex From mclaugb at nospm.yahoo.com Mon Feb 6 06:38:51 2006 From: mclaugb at nospm.yahoo.com (mclaugb) Date: Mon, 6 Feb 2006 11:38:51 -0000 Subject: Scientific Computing with NumPy References: Message-ID: This page documents the differences. It seems that NumPy is supported and more recent. http://numeric.scipy.org/ "linda.s" wrote in message news:mailman.1482.1139225595.27775.python-list at python.org... On 2/6/06, mclaugb wrote: > Has anyone recompiled the Scientific Computing package using NumPy instead > of Numeric? > I need a least squares algorithm and a Newton Rhaphson algorithm which is > contained in Numeric but all the documentation out there says that Numeric > is crap and all code should be using NumPy. > Thanks, > Bryan > > > -- > http://mail.python.org/mailman/listinfo/python-list > what is the relationship between Numeric and Numpy? From deets at nospam.web.de Mon Feb 20 05:37:56 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 20 Feb 2006 11:37:56 +0100 Subject: cElementTree encoding woes Message-ID: <45tkj3F8d9fpU1@uni-berlin.de> Hi, I've got to deal with a pretty huge XML-document, and to do so I use the cElementTree.iterparse functionality. Working great. Only trouble: The guys creating that chunk of XML - well, lets just say they are "encodingly challanged", so they don't produce utf-8, but only cp1252 instead, together with some weird name (Windows-1252) for that. That is not part of the standard codecs module. cp1252 is, of course. But that won't work for iterparse. So currently, I manually change the encoding given to utf-8, and use a stream-recoder. However, I was wondering if I could teach cElementTree about that encoding name. I tried to register cp1252 under the name Windows-1252, but had no luck - cET won't buy it. Any suggestions? Diez From fuzzyman at gmail.com Thu Feb 2 04:15:40 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 2 Feb 2006 01:15:40 -0800 Subject: changing python script on-the-fly for ActiveX/COM object (win32com) In-Reply-To: <1138845738.717736.222710@g49g2000cwa.googlegroups.com> References: <1138845738.717736.222710@g49g2000cwa.googlegroups.com> Message-ID: <1138871740.436875.83170@g44g2000cwa.googlegroups.com> jd wrote: > I have implemented a COM object in Python and I would like > to be able to change the script without stopping and > restarting the application that's using the COM object. Is > there a way to do this? (I can change the program that > calls the COM object if needed.) > I have no idea about the intracacies of COM, but... You'll probably have to at least implement a Python stub that doesn't change. You can implement everything else in modules. You can override the modules and call 'reload' to force the newer versions to be used. I don't know if that would rebind external references to objects *within* the module (you'd need to experiment or wait for a more knowledgeable opinion). You'd also have to at least *suspend* operations whilst the update takes place. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Thanks... > > -- jeff From mlist at fastwebnet.it Mon Feb 20 03:34:38 2006 From: mlist at fastwebnet.it (billie) Date: Mon, 20 Feb 2006 09:34:38 +0100 Subject: editor for Python on Linux References: <1140423903.462774.193920@g14g2000cwa.googlegroups.com> Message-ID: I really think that IDLE is one of the best around in Python source editing. The only great lacks are tabs. Does somebody know if is there some IDLE modified version including tabbed browsing, out there? From pprobert at wisc.edu Fri Feb 24 17:17:49 2006 From: pprobert at wisc.edu (Paul Probert) Date: Fri, 24 Feb 2006 16:17:49 -0600 Subject: Problem solved: Re: time.sleep(1) sometimes runs for 200 seconds under windows In-Reply-To: References: Message-ID: Thanks everyone for your help. It was the "Abouttime.exe" program, a time synch utility. To get the problem, you have to run it as a service, and possibly it has to have trouble connecting to its time servers. It would cause time.sleep(1) to sometimes block for 200 seconds. Not "about" 200 seconds but always within 199 to 202 seconds. Very strange, but it is good to have the problem gone. Enjoy the weekend! Paul Probert University of Wisconsin From dschuff at purdue.edu Wed Feb 22 11:44:22 2006 From: dschuff at purdue.edu (Derek Schuff) Date: Wed, 22 Feb 2006 11:44:22 -0500 Subject: except clause not catching IndexError Message-ID: I'm sorry if this is a FAQ or on an easily-accesible "RTFM" style page, but i couldnt find it. I have some code like this: for line in f: toks = line.split() try: if int(toks[2],16) == qaddrs[i]+0x1000 and toks[0] == "200": #producer write prod = int(toks[3], 16) elif int(toks[2],16) == qaddrs[i]+0x1002 and toks[0] == "200": #consumer write cons = int(toks[3], 16) else: continue except IndexError: #happens if theres a partial line at the end of file print "indexerror" break However, when I run it, it seems that I'm not catching the IndexError: Traceback (most recent call last): File "/home/dschuff/bin/speeds.py", line 202, in ? if int(toks[2],16) == qaddrs[i]+0x1000 and toks[0] == "200": #producer write IndexError: list index out of range If i change the except IndexError to except Exception, it will catch it (but i believe it's still an IndexError). this is python 2.3 on Debian sarge. any ideas? thanks, -derek From none at no.chance Fri Feb 17 05:49:56 2006 From: none at no.chance (Peter Tillotson) Date: Fri, 17 Feb 2006 10:49:56 +0000 Subject: Python advocacy in scientific computation In-Reply-To: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> Message-ID: Hi, Like it - an area that doesn't come out strongly enough for me is Python's ability to drop down to and integrate with low level algorithms. This allows me to to optimise the key bits of design in python very quickly and then if I still need more poke i can drop down to low level programming languages. Optimise design, not code unless I really need to. To be fair the same is at least partly true for Java ( though supporting JNI code scares me ) but my prototyping productivity isn't as high. The distributed / HPC packages may also be worth noting - PyMPI and PyGlobus. p Michael Tobis wrote: > Someone asked me to write a brief essay regarding the value-add > proposition for Python in the Fortran community. Slightly modified to > remove a few climatology-related specifics, here it is. > > I would welcome comments and corrections, and would be happy to > contribute some version of this to the Python website if it is of > interest. > > === > > The established use of Fortran in continuum models such as climate > models has some benefits, including very high performance and > flexibility in dealing with regular arrays, backward compatibility with > the existing code base, and the familiarity with the language among the > modeling community. Fortran 90 and later versions have taken many of > the lessons of object oriented programming and adapted them so that > logical separation of modules is supported, allowing for more effective > development of large systems. However, there are many purposes to which > Fortran is ill-suited which are increasingly part of the modeling > environment. > > These include: source and version control and audit trails for runs, > build system management, test specification, deployment testing (across > multiple platforms), post-processing analysis, run-time and > asynchronous visualization, distributed control and ensemble > management. To achieve these goals, a combination of shell scripts, > specialized build tools, specialized applications written in several > object-oriented languages, and various web and network deployment > strategies have been deployed in an ad hoc manner. Not only has much > duplication of effort occurred, a great deal of struggling up the > learning curves of various technologies has been required as one need > or another has been addressed in various ad hoc ways. > > A new need arises as the ambitions of physical modeling increase; this > is the rapid prototyping and testing of new model components. As the > number of possible configurations of a model increases, the expense and > difficulty of both unit testing and integration testing becomes more > demanding. > > Fortunately, there is Python. Python is a very flexible language that > has captured the enthusiasm of commercial and scientific programmers > alike. The perception of Python programmers coming from almost any > other language is that they are suddenly dramatically several times > more productive than previously, in terms of functionality delivered > per unit of programmer time. > > One slogan of the Python community is that the language "fits your > brain". Why this might be the case is an interesting question. There > are no startling computer science breakthroughs original to the > language, Rather, Python afficionados will claim that the language > combines the best features of such various languages as Lisp, Perl, > Java, and Matlab. Eschewing allegiance to a specific theory of how to > program, Python's design instead offers the best practices from many > other software cultures. > > The synergies among these programming modes is in some ways harder to > explain than to experience. The Python novice may nevertheless observe > that a single language can take the place of shell scripts, makefiles, > desktop computation environments, compiled languages to build GUIs, and > scripting languages to build web interfaces. In addition, Python is > useful as a wrapper for Fortran modules, facilitating the > implementation of true test-driven design processes in Fortran models. > > Another Python advocacy slogan is "batteries included". The point here > is that (in part because Python is dramatically easier to write than > other languages) there is a very broad range of very powerful standard > libraries that make many tasks which are difficult in other languages > astonishingly easy in Python. For instance, drawing upon the standard > libraries (no additional download required) a portable webserver > (runnable on both Microsoft and Unix-based platforms) can be > implemented in seven lines of code. (See > http://effbot.org/librarybook/simplehttpserver.htm ) Installation of > pure python packages is also very easy, and installation of mixed > language products with a Python component is generally not > significantly harder than a comparable product with no Python > component. > > Among the Python components and Python bindings of special interest to > scientists are the elegant and powerful matplotlib plotting package, > which began by emulating and now surpasses the plotting features of > Matlab, SWIG, which allows for runtime interoperability with various > languages, f2py which specifically interoperates with Fortran, NetCDF > libraries (which cope with NetCDF files with dramatically less fuss > than the standard C or Fortran bindings), statistics packages including > bindings to the R language, linear algebra packages, various > platform-specific and portable GUI libraries, genetic algorithms, > optimization libraries, and bindings for high performance differential > equation solvers (notably, using the Argonne National Laboratory > package PetSC). An especially interesting Python trick for runtime > visualization in models that were not designed to support it, pioneered > by David Beazley's SWILL, embeds a web server in your model code. > > See especially http://starship.python.net/~hinsen/ScientificPython/ and > http://scipy.org as good starting points to learn about scientific uses > of Python. > > mt > From grante at visi.com Tue Feb 28 15:42:46 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 28 Feb 2006 20:42:46 -0000 Subject: Thread Question References: <1141155072.500444.215130@v46g2000cwv.googlegroups.com> <1209cbiq1kjbh06@corp.supernews.com> Message-ID: <1209de6pu05iuc5@corp.supernews.com> On 2006-02-28, Felipe Almeida Lessa wrote: > # He meant calling direct vs. subclassing. In your example you called > the Thread class directly, but you could have subclassed it. Yup. I should have realized that. > # In your case, Edwards, I'd prefer subclassing because then you could > put some states in the class. A (bad) example: [...] Good example. It's probably bad style, but in my programs the "state info" like that usually ends up being global variables since it's also "attached" to thinks like GUI buttons and indicators. I never have more than one instance of the thread, so I can get away with it. If you need multiple instances of stateful threads, you really do want to subclass Thread. -- Grant Edwards grante Yow! I'm in DISGUISE as a at BAGGAGE CHECKER....I can visi.com watch the house, if it's ORANGE... From scott.daniels at acm.org Fri Feb 24 11:33:58 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 24 Feb 2006 08:33:58 -0800 Subject: chrtohex In-Reply-To: <1140794594.653270.242720@e56g2000cwe.googlegroups.com> References: <1140794594.653270.242720@e56g2000cwe.googlegroups.com> Message-ID: <43ff33ce$1@nntp0.pdx.net> luca72 wrote: > Hello again my friends > > here's my new problem. > > How i can translate chr in to hex or int to integer value? > > Best Regards > > Luca > By demonstrating that you have tried to solve the problem yourself. See: http://www.catb.org/~esr/faqs/smart-questions.html --Scott David Daniels scott.daniels at acm.org From mikeisgreat at gmail.com Thu Feb 2 13:47:42 2006 From: mikeisgreat at gmail.com (mikeisgreat at gmail.com) Date: 2 Feb 2006 10:47:42 -0800 Subject: learning python, using string help Message-ID: <1138906062.727850.177960@g14g2000cwa.googlegroups.com> hi all, I have a simple snippet I am trying to keep the format the same as plain text, though I want to embed it in html ... basically, print "Content-type:text/plain\n\n"; getrup = os.popen('ruptime').read() print getrup is the same format as if I ran 'ruptime' from the command line. If I use... print "Content-type:text/html\n\n"; getrup = os.popen('ruptime').read() print getrup I can just split the lines and loop through it ... but I am not sure how to keep the tab spacing the same I'm sure its something so simple I am missing .... thanks for helping someone learning.. --mike From johnjsal at NOSPAMgmail.com Fri Feb 10 15:43:15 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 10 Feb 2006 20:43:15 GMT Subject: installing python on a server? In-Reply-To: References: Message-ID: Rene Pijlman wrote: > John Salerno: >> Can anyone tell me how complicated it might be to install Python on my >> server so I can use it for web apps? > > 2 on a scale from 1 to 10. > >> Is it a one-time process, or something to maintain? > > Both :-) > > I installed Python 2.2 - 2.4 from source on Linux with no problem > whatsoever. I now plan about 5 minutes installation time per new release, > that's 2 minutes to make coffee, 2 minutes to skim the release notes and > README and 1 minute to watch ./configure; make; make install do it's > magic. > > There are some details to watch out for, such as having the required > libraries and include files around before installation, to enable specific > functionality (e.g. SSL support in socket). But that's no big deal. > Hmm, sounds easy, yet I don't know where to start. What do I actually use to install it onto the server? I've never dealt with server stuff before, so I might not be familiar with the terminology. From eoinrogers at gmail.com Fri Feb 17 15:02:02 2006 From: eoinrogers at gmail.com (Byte) Date: 17 Feb 2006 12:02:02 -0800 Subject: Another stupid newbie question In-Reply-To: References: <1140203709.145048.314180@g43g2000cwa.googlegroups.com> Message-ID: <1140205198.880333.210960@f14g2000cwb.googlegroups.com> Great, thanks all (the point of x = 2 was that i dont understand exactly what True is on while True:) -- /usr/bin/byte From grflanagan at yahoo.co.uk Thu Feb 16 16:19:24 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 16 Feb 2006 13:19:24 -0800 Subject: Merging two lists of data (Pythonic way) References: <8k5Jf.27896$sA3.57@fed1read02> <1140122391.823206.74580@g14g2000cwa.googlegroups.com> <5iq9v11peim9ehamh39v2fcilq3ndq1s52@4ax.com> Message-ID: <1140124764.380238.146800@f14g2000cwb.googlegroups.com> Dave Hansen wrote: > On Thu, 16 Feb 2006 12:51:24 -0800 in comp.lang.python, "SMB" > wrote: > > > > >"Jonathan Gardner" wrote in message > >news:1140122391.823206.74580 at g14g2000cwa.googlegroups.com... > >> codes = map(lambda x: x[0], list1) > >> for d in list2: > >> if d['code'] in codes: > >> d['VERIFIED'] = 1 > >> > >> Is this what you were looking for? > >> > > > >That is exactly what I was looking for. I will have to take a look at map. > > You might also look at list comprehensions. Replacing the first line > in the above with > > codes = [x[0] for x in list1] > > should yield the same result. > > Regards, > -=Dave > > -- > Change is inevitable, progress is not. What about : A = [ a[0] for a in LIST1 ] for d in [ d for d in LIST2 if d['code'] in A ]: d['VERIFIED'] = 1 ? Gerard From sambyerly at netscape.net Fri Feb 17 15:27:52 2006 From: sambyerly at netscape.net (nick) Date: 17 Feb 2006 12:27:52 -0800 Subject: Click this link, scroll to the bottom, and get your own free mall!! Message-ID: <1140208072.846039.111450@g47g2000cwa.googlegroups.com> http://www.telebay.com/esolutions/mall.html From codecraig at gmail.com Fri Feb 10 08:51:58 2006 From: codecraig at gmail.com (py) Date: 10 Feb 2006 05:51:58 -0800 Subject: Create dict from two lists Message-ID: <1139579518.129742.265680@o13g2000cwo.googlegroups.com> I have two lists which I want to use to create a dictionary. List x would be the keys, and list y is the values. x = [1,2,3,4,5] y = ['a','b','c','d','e'] Any suggestions? looking for an efficent simple way to do this...maybe i am just having a brain fart...i feel like this is quit simple. thanks. From szabolcs.berecz at gmail.com Thu Feb 16 11:04:43 2006 From: szabolcs.berecz at gmail.com (szabi) Date: 16 Feb 2006 08:04:43 -0800 Subject: pythonic way of 'b = list(a); b.append(4)" Message-ID: <1140105883.069632.262530@g43g2000cwa.googlegroups.com> Hi! I have a list of three values and want to call a function with four parameters. I would like to write something like: a = [1, 2, 3] f(*a, 4) This is syntactically wrong, so is there a function which appends a value to a list and returns the new value, so that I could write something like this: f(list(a).functional_append(4)) I can't modify 'a'. Thanks, Szabi From claes_lillieskold at hotmail.com Mon Feb 27 15:05:55 2006 From: claes_lillieskold at hotmail.com (claes_lillieskold at hotmail.com) Date: 27 Feb 2006 12:05:55 -0800 Subject: PDB on a large threaded application (QMTest) Message-ID: <1141070755.231208.325620@i39g2000cwa.googlegroups.com> Hi, I'm trying to debug QMTest from Code Sourcery with PDB from inside Emacs. My problem is that without PDB, I have no problem, but when I'm using PDB, I get exceptions thrown. Has anyone else tried using PDB on QMTest? My python is 2.2, and QMTest is 2.0.3. Thanks / Claes From felipe.lessa at gmail.com Sat Feb 18 12:01:12 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sat, 18 Feb 2006 15:01:12 -0200 Subject: share function argument between subsequent calls but not between class instances! In-Reply-To: References: <11vejkega5tbrc5@corp.supernews.com> Message-ID: <1140282072.11250.6.camel@kenshin> Em S?b, 2006-02-18 ?s 16:50 +0000, Duncan Booth escreveu: > marker = object() > > class Test(object): > def __init__(self): > self.L = [] > > def f(self,a, L=marker): > if L is marker: > L = self.L > L.append(a) > return L As hasattr(None, "append") == False, you could also do: class Test(object): def __init__(self): self.L = [] def f(self, a, L=None): if L is None: L = self.L L.append(a) return L -- "Quem excele em empregar a for?a militar subjulga os ex?rcitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destr?i os estados dos outros povos sem lutas prolongadas. Deve lutar sob o C?u com o prop?sito primordial da 'preserva??o'. Desse modo suas armas n?o se embotar?o, e os ganhos poder?o ser preservados. Essa ? a estrat?gia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" From steve at REMOVETHIScyber.com.au Fri Feb 10 19:12:47 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 11 Feb 2006 11:12:47 +1100 Subject: cmd References: Message-ID: On Sat, 11 Feb 2006 00:47:14 +0100, Gerber wrote: > I'd like some documentation on the cmd module, besides the regular > docs, in help() and docs.python.org... Is this a trick question? You'd like some documentation apart from the documentation? Have you tried reading the source code to the module? Have you tried googling? Have you tried using Python's extensive introspection capabilities on the module? Failing that, do you have a specific question you would like to ask? -- Steven. From grahn+nntp at snipabacken.dyndns.org Mon Feb 6 17:46:17 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 6 Feb 2006 22:46:17 GMT Subject: Best way of finding terminal width/height? References: <96nFf.43896$d5.199922@newsb.telia.net> <11uc3dohfitotc5@corp.supernews.com> <11udc0r2bq11042@corp.supernews.com> <43E719EE.3040401@gmail.com> <11ueq4nhn91qm91@corp.supernews.com> Message-ID: On Mon, 06 Feb 2006 15:17:43 -0000, Grant Edwards wrote: > On 2006-02-06, Joel Hedlund wrote: [finding the terminal dimensions] >> access to the termios module either. So, in the latter case >> I'm back to square one, which is arbitrary guesswork. > > Yes, that's probably true. In that case, most people assume > 80x24. And, I might add, as a Unix user that is what I expect programmers to do -- stick to 80x24 or 80 x any-height-they-need. If it's not a full-screen program (which would use curses anyway), I don't expect them to work harder than that. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From tjreedy at udel.edu Mon Feb 27 19:22:52 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 27 Feb 2006 19:22:52 -0500 Subject: str.count is slow References: <1141073696.107136.318600@j33g2000cwa.googlegroups.com> <1141083127.970403.147100@v46g2000cwv.googlegroups.com> Message-ID: "Ben Cartwright" wrote in message news:1141083127.970403.147100 at v46g2000cwv.googlegroups.com... > Your evidence points to some unoptimized code in the underlying C > implementation of Python. As such, this should probably go to the > python-dev list (http://mail.python.org/mailman/listinfo/python-dev). > > The problem is that the C library function memcmp is slow, and > str.count calls it frequently. See lines 2165+ in stringobject.c > (inside function string_count): > > r = 0; > while (i < m) { > if (!memcmp(s+i, sub, n)) { > r++; > i += n; > } else { > i++; > } > } > > This could be optimized as: > > r = 0; > while (i < m) { > if (s[i] == *sub && !memcmp(s+i, sub, n)) { > r++; > i += n; > } else { > i++; > } > } > > This tactic typically avoids most (sometimes all) of the calls to > memcmp. Other string search functions, including unicode.count, > unicode.index, and str.index, use this tactic, which is why you see > unicode.count performing better than str.count. If not doing the same in str.count is indeed an oversight. a patch should be welcome (on the SF tracker). From rphillips at engineer.co.summit.oh.us Wed Feb 15 06:47:36 2006 From: rphillips at engineer.co.summit.oh.us (paron) Date: 15 Feb 2006 03:47:36 -0800 Subject: Embedding an Application in a Web browser References: <1139930045.408507.151440@g43g2000cwa.googlegroups.com> Message-ID: <1140004056.893486.291280@g44g2000cwa.googlegroups.com> You may already know this, but I don't think anyone has mentioned it explicitly. You can run a Python web server (I like CherryPy) on the local machine, and serve pages to "localhost." Everything else is just plain old Python, and talking to the OS is no problem. Ron From tzot at sil-tec.gr Tue Feb 14 02:50:41 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Tue, 14 Feb 2006 09:50:41 +0200 Subject: OT: Another try at Python's selfishness References: <1138918102.863033.298700@o13g2000cwo.googlegroups.com> Message-ID: On Thu, 9 Feb 2006 10:35:37 +0100, rumours say that "Frithiof Andreas Jensen" might have written: >If one was trying to detect fanatics of any creed, a certain indicator would >be that they have absolutely no sense of humour - they suffer from a >yet-to-be-described variant of autism I.M.O. Although I generally agree, I've seen images of fanatics laughing madly when they employ their fanatism; so they might have some sense of humour, even if a perverted one (perverted relative to your or my sense of humour, obviously :) They tend to lack self-sarcasm, though. Anyway, someone wiser than me (probably so much wiser that I subconsciously forgot their name!) said: "The difference between a saint and a fanatic is that the saint fights the evil inside him/herself..." -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From rridge at csclub.uwaterloo.ca Sun Feb 26 12:46:16 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 26 Feb 2006 09:46:16 -0800 Subject: Pure python implementation of string-like class References: <20060225.102645.74687871.kayama@st.rim.or.jp> <1140891600.822510.189140@v46g2000cwv.googlegroups.com> <1140915354.024788.25720@z34g2000cwc.googlegroups.com> Message-ID: <1140975976.471949.20940@t39g2000cwt.googlegroups.com> Ross Ridge wrote: > Akihiro Kayama in his original post made it clear that he wanted to use > a character set larger than entire Unicode code space. Xavier Morel wrote: > He implies that ... He explictly said that character set he wanted to use wouldn't fit in UTF-16. >... but in later messages he > 1. Implies that he wants to use the Unicode private spaces, which are in > the Unicode code space He explictly said that he wanted to use the "U+60000000...U+7FFFFFFF" range which is outside of the Unicode code space, despite him mistakenly calling them Unicode characters. > 2. Says explicitly that his needs concern Kanji encoding... I have no clue whether he really needs such a large character set, but if he does then it makes sense for him to want to use an encoding that's wider than UTF-16. As for the problem he actually posed, I'd suggest using tuples rather than lists, since tuples are immutable like strings. That would make it easier for the class to be used as key in a dictionary. Hmm... thiking about it, it might actually make sense to use strings as the internal representation as a lot operations can be implemented by using the standard string operation but multipling the offsets and lengths by 4. Ross Ridge From robert.kern at gmail.com Wed Feb 15 19:05:58 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 15 Feb 2006 18:05:58 -0600 Subject: Scientific Computing with NumPy In-Reply-To: <1140047987.435267.194220@g43g2000cwa.googlegroups.com> References: <1d987df30602100415o16ad3d02n71aca12686667ff@mail.gmail.com> <1140047987.435267.194220@g43g2000cwa.googlegroups.com> Message-ID: Tariq wrote: > Has anyone been able to successfully install numpy 0.9.4 on python 2.4 > under cygwin? > > I'm getting a few errors, especially while it installs the C source. I don't know of anyone compiling numpy under cygwin, but we will be happy to help you on numpy-discussion at lists.sourceforge.net if you will give us some more information like what arguments you gave to the setup script and the exact error messages that you are seeing. -- Robert Kern robert.kern at gmail.com "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From pparkkin at gmail.com Wed Feb 8 08:57:48 2006 From: pparkkin at gmail.com (enjoying the view) Date: 8 Feb 2006 05:57:48 -0800 Subject: a question regarding call-by-reference In-Reply-To: <1139250105.744691.110440@o13g2000cwo.googlegroups.com> References: <1139250105.744691.110440@o13g2000cwo.googlegroups.com> Message-ID: <1139407068.309448.7450@z14g2000cwz.googlegroups.com> Thank you everyone for your helpful replies! I think the problems that arise with nested and overly large lists and dictionaries, and difficulties of handling other mutable datatypes will make my little assignment just too difficult. I'll just specify that call-by-reference isn't supported and leave it at that. Between floors. Going down. Enjoying the view. From steven.bethard at gmail.com Wed Feb 15 23:14:56 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 15 Feb 2006 21:14:56 -0700 Subject: Safe Python Execution In-Reply-To: <1140058830.477028.26620@f14g2000cwb.googlegroups.com> References: <1140058830.477028.26620@f14g2000cwb.googlegroups.com> Message-ID: Graham wrote: > The way i'm controlling functionality is with some games and exec, so > if 'code' was the text code you wanted to execute i run: > > exec code in {'__builtins__':None"} > > obviously this doesn't give you much to play with, but it does remove > file access and importing as far as i can tell. Can anyone think of a > hack around this? I assume if it was this easy it would be a module > already but i figured i would ask. Search the newsgroups, but one of the major problems is that all subclasses of object are available through object.__subclasses__(): >>> (1).__class__.__bases__[0].__subclasses__() [, , , , ... , , ] Note that this also includes any classes you define that are subclasses of object: >>> class C(object): ... dont_change_this = 42 ... >>> exec '''\ ... subclasses = (1).__class__.__bases__[0].__subclasses__() ... C, = [cls for cls in subclasses if cls.__name__ == 'C'] ... C.dont_change_this = 'bwahahaha' ... ''' in {'__builtins__':None} >>> C.dont_change_this 'bwahahaha' So if you're really concerned about your objects being manipulated with users, the ``exec code in {'__builtins__':None}`` technique is not going to help you out. However, the code will be executed in restricted mode, so things like the file constructor won't work. Not sure if that's enough for you... STeVe From peter at engcorp.com Fri Feb 3 18:00:16 2006 From: peter at engcorp.com (Peter Hansen) Date: Fri, 03 Feb 2006 18:00:16 -0500 Subject: web.py + cheetah delivering incomplete pages In-Reply-To: <1139001423.549772.325090@f14g2000cwb.googlegroups.com> References: <1138977432.206287.16130@g47g2000cwa.googlegroups.com> <1138988779.571240.209970@g43g2000cwa.googlegroups.com> <1139001423.549772.325090@f14g2000cwb.googlegroups.com> Message-ID: wolfgang.lipp at gmail.com wrote: > yeah, posted it there too, but, you see, there are but 95 members in > that group -- guess it's more productive to ask this right here. we'll > see. There's a good chance that about 80 of those 95 people read this newsgroup regularly, and that this newsgroup has only a small handful of people who know anything about web.py but who aren't in that set of 95... and some of them might not notice your posting. But, as you said, we'll see. ;-) -Peter From sybrenUSE at YOURthirdtower.com.imagination Fri Feb 24 05:16:25 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 24 Feb 2006 11:16:25 +0100 Subject: How to send an email with non-ascii characters in Python References: <1140775736.341876.314070@t39g2000cwt.googlegroups.com> Message-ID: Lad enlightened us with: > Can anyone give an example how to send email with non-ascii > characters( both in subject and body). I would like to use > windows-1250 code page I'd use Latin-1 or UTF-8, since they are both cross-platform instead of windows-specific... Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From nyamatongwe+thunder at gmail.com Fri Feb 17 22:14:49 2006 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sat, 18 Feb 2006 03:14:49 GMT Subject: commenting out blocks of code In-Reply-To: References: <20060217231846.87613.qmail@web36708.mail.mud.yahoo.com> Message-ID: Hi Steven, > I see the developers of Scite are either newbies to GUI programming, or > they operate in a world of their own. Ctrl-Q is reserved for Quit (or > Exit) in every GUI API I know of. I am the developer responsible for SciTE and the Ctrl+Q decision. Ctrl+Q is not reserved for Quit on every platform. Perhaps you have never used Windows where Exit does not normally have a distinct command key of its own but can be performed with Alt+F4 (Close) for single window applications. Since exiting an application is a far less common action than modifying the data within that application, it doesn't deserve one of the more easily typed key bindings. Some applications use Ctrl+Q but, of the applications I currently have open, Firefox, Internet Explorer, Explorer, iTunes, Visual Studio .NET, WordPad, QuickTime, PythonWin, and WinMerge don't respond to Ctrl+Q by quitting and Thunderbird does. Windows guidelines: http://msdn.microsoft.com/library/en-us/dnwue/html/appxB.asp > It is *easy* to detect when a line is already commented. It starts with a > #. The ~ is superfluous. It is not usual to change a line from being code to being a comment as most lines of code make no sense as English text. If you do sometimes want to do this, the "#" key can be pressed at the beginning of a line. Ctrl+Q exists to allow commenting out sections of code that you do not want to be active. The "~" acts to differentiate these different uses of one language feature and makes it easy to apply the operation over ranges that include comments and then invert the operation. > Commenting and uncommenting should be two different commands: the whole > point of nested comments is that it allows you to comment a block of text > which may already contain comments. Having one command do both commenting > and uncommenting according to the presence or absence of semantic clues in > the text is a recipe for failure ("No you stupid computer, I want to > COMMENT that block, not uncomment it!!!"). Comments and commented out code are distinct. Using the same marker for both is ambiguous. Few languages support true nested comments. SciTE's implementation of Ctrl+Q is very popular although you can change the text inserted/removed from "#~" to "#" if you prefer and SciTE also includes a command to add stream style comments for languages like /* C++ */. > Imagine if your text editor used cntl-C for both copy and paste, somehow > guessing whether you wanted to copy selected text or paste over it > according to some subtle clue in the text itself. Wouldn't that be fun? Your imaginary command makes no sense as it is described. What are its full semantics? Why was it implemented this way? BTW, I have been implementing GUIs for over 20 years so maybe me and the other SciTE users are in our own world. It does feel like a friendly, enjoyable, comfortable world, though. Neil From malvert at telenet.be Wed Feb 8 14:02:33 2006 From: malvert at telenet.be (malv) Date: 8 Feb 2006 11:02:33 -0800 Subject: Dual Core outlook In-Reply-To: References: <1139329268.695421.191340@g47g2000cwa.googlegroups.com> <1139335428.970958.170320@o13g2000cwo.googlegroups.com> Message-ID: <1139421972.144837.51610@f14g2000cwb.googlegroups.com> Hi All, Thank you for your commentaries. In the meantime, I read up in Python-Dev and came across a post by Johnatan LaCour which kind of nicely sums up the state of affairs: "Its really a shame. There seems to be some consensus about multi-processing, but not a whole lot of interest in making it easier out of the box. When it comes to multi-processing, batteries really _aren't_ included. Sure, you have lead dioxide and some sulphuric acid, but you have to put them together to make your battery. This isn't the end of the world, but I find it tedious, and I am sure it confuses and frustrates people new to Python." Possibly things are not much brighter for other languages. I'll keep on trying malv From erniedude at gmail.com Wed Feb 1 09:57:14 2006 From: erniedude at gmail.com (Ernesto) Date: 1 Feb 2006 06:57:14 -0800 Subject: Capture Windows command line output - put in text file Message-ID: <1138805834.790265.93130@g44g2000cwa.googlegroups.com> I'm looking for a way to capture command line output from a cmd session. Is there a way to use python to launch the application from the beggining.... then stream all of the output to a text file ? From lycka at carmen.se Fri Feb 24 04:01:19 2006 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 24 Feb 2006 10:01:19 +0100 Subject: why don't many test frameworks support file-output? In-Reply-To: References: Message-ID: kanchy kang wrote: > i browsed the following frameworks briefly: nose, OOBTest, > testosterone, py.test, Sancho ... and found out they do support > imediate screen-output only. Look at TextTest. From samslists at gmail.com Mon Feb 20 22:05:47 2006 From: samslists at gmail.com (samslists at gmail.com) Date: 20 Feb 2006 19:05:47 -0800 Subject: Writing my own typing monitor program for RSI sufferers... Message-ID: <1140491147.433293.164700@g43g2000cwa.googlegroups.com> Hi... I want to write a program that will let me know after thirty minutes of typing that I need to take a five minute typing break. But when I stop typing it's smart enough to pause the 30 minute timer automatically. This is under the X-Window System (Linux). The tricky part is obviously knowing when the mouse and keyboard are being used....especially when my application doesn't have the focus. Obviously I can't do this with just the base python install. Is there an add on library that I can use to monitor the keyboard and mouse? Which is it? Maybe one of the graphical libraries, like wx, or qt, or gtk? Which functions do I need? Thanks From thierry.t.chevalier at gmail.com Tue Feb 28 10:38:36 2006 From: thierry.t.chevalier at gmail.com (tooper) Date: 28 Feb 2006 07:38:36 -0800 Subject: Python advocacy in scientific computation In-Reply-To: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> Message-ID: <1141141116.113568.257280@e56g2000cwe.googlegroups.com> Maybe I'd also emphasize the nice COM interface that allow your wrapped Fortran to be made available in your Excel macros in a snap. It happens that Fortran programmers/users tends to be poor Office users except for Excel which they master at unbelievable level... My own best low work/high user satisfaction ever is just this, wrap LOWTRAN call to make is usable from Excel, a 1/2h work and a 100+ users 2 days later ! From ptmcg at austin.rr._bogus_.com Wed Feb 22 11:14:31 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 22 Feb 2006 16:14:31 GMT Subject: Basic coin flipper program - logical error help References: <1140567243.251982.255620@g14g2000cwa.googlegroups.com> <1140578858.586591.243900@g43g2000cwa.googlegroups.com> Message-ID: "Paul McGuire" wrote in message news:yURKf.22750$UN2.3873 at tornado.texas.rr.com... > wrote in message > news:1140578858.586591.243900 at g43g2000cwa.googlegroups.com... > sort, then groupby. > > > import itertools > import random > h,t = [len(list(g)) for k,g in itertools.groupby(sorted([random.randrange(2) > for i in xrange(100)]))] > print h,t > > By the way, sort + groupby generalizes beyond just coin-flipping. Here is a modified version that simulates die rolls. -- Paul import itertools import random NUM_ROLLS = 1000 dieRolls = [random.randrange(6)+random.randrange(6)+2 for i in xrange(NUM_ROLLS)] # create dummy list entries for impossible rolls of 0 and 1 rolls = [None,None] rolls += [len(list(g)) for k,g in itertools.groupby(sorted(dieRolls))] # print out nice histogram for i,r in enumerate(rolls): if i > 1: print "%2d - %s" % (i,"*"*int(round(r/10.0))) prints: 2 - *** 3 - ***** 4 - ********* 5 - ********** 6 - *************** 7 - ****************** 8 - ************** 9 - ********* 10 - ******* 11 - ******* 12 - *** From jzgoda at o2.usun.pl Fri Feb 24 14:49:28 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 24 Feb 2006 20:49:28 +0100 Subject: MySQLdb slow on MySQL 5 In-Reply-To: References: <1140716394.225560.27920@t39g2000cwt.googlegroups.com> <1140727082.800917.44550@i40g2000cwc.googlegroups.com> Message-ID: Magnus Lycka napisa?(a): > For those who don't know, Oracle bought a small Finnish > company which developed the transaction-aware table- > backend for MySQL. As far as I understand, this means > nothing for GPL licensed MySQL installations, but if > MySQL sells commercial MySQL-database with transaction > support, I guess they need to share their incomes with > Oracle now, and I suppose Oracle is completely in charge > of future development and price setting for InnoDB. Of > course, MySQL has support for swapping table backends, > and the logical next step might be to use the major open > source transactional low level database Berkeley DB, > which is also dual licensed, and developed by SleepyCat. > Unfortuantely, Oracle just bought them... I'm sure there > are other ways out though. MySQL owns MaxDB, which was > previously SAP DB, a derivate ot the German Adabas D. > I'm not sure how easy it is to rip out the table back- > end of that though. I guess it's not built to be a > separate component. They just hired Jim Starkey. Perhaps MySQL AB hopes he will write a transactional engine for MySQL, as he previously wrote one for Interbase (which is known to be one of the best a man could imagine). Anyway, we got far off topic, so we better go somewhere else. -- Jarek Zgoda http://jpa.berlios.de/ From nephish at xit.net Mon Feb 6 12:00:16 2006 From: nephish at xit.net (nephish at xit.net) Date: 6 Feb 2006 09:00:16 -0800 Subject: in over my head ascii Message-ID: <1139245216.350356.272170@z14g2000cwz.googlegroups.com> Hello there, i need to write a script that can transfer info back and forth with a data server at so-and-so ip. i have Programming Python, which covers socket programming. So thats cool. But what i need to know how to do is make a message in ascii that is what the server is looking for. for example , to send a request, the first three bytes have to be ascii "STX" then there has to be 4 bytes that show the length of the message then the actual message then the last three bytes have to be "ENX" also all int variables must me unsigned long-int (32 bit). so here is what i need to know, 1 how do i make something in ascii bytes to send off to this server ? 2 how can i make sure something is a 32bit unsigned long int. ? If the answers i am looking for are pretty straightforward, please let me know., If they are long and complicated, please point me to some good documentation . thanks for all, sk From mwilliams at mgreg.com Sun Feb 5 16:10:34 2006 From: mwilliams at mgreg.com (Michael Williams) Date: Sun, 5 Feb 2006 16:10:34 -0500 Subject: what's wrong with my popen reasoning? In-Reply-To: References: Message-ID: <01631058-436B-409A-ABC9-B0FDE3AF13A2@mgreg.com> Hello, I would possibly look into using Pexpect (http:// pexpect.sourceforge.net/) and the python "time" module for things of this nature. It gives you a bit more granular control over what happens when. Regards, Michael On Feb 5, 2006, at 2:57 PM, python-list-request at python.org wrote: > From: Rick Spencer > Date: February 5, 2006 1:39:18 PM EST > To: python-list at python.org > Subject: what's wrong with my popen reasoning? > > > Hi all, > > I am very new to Python programming. I am writing a program to manage > wireless connections, this is for GNOME on Linux. I present the > user with > a "connect" button. I want to handle the connection for them slightly > different depending on whether or not the wireless access point > they are > trying to connect to is secure. In either case, I have a similar > question. > > In the first case, the wireless access point is secured. I want to > bring > up the GNOME applet for configuring a wireless access interface. I > can > pass the command line commands to bring it up, but I can't figure > out how > to bring it up in a modal fashion, so that my Python program waits > for the > user to dismiss it before my program gets control again. > > In the second case, the access point is not secured. I just want to > fire > off the command line utility (iwconfig) for connecting. In this > case, I > want my program to wait until iwconfig is done before continuing on. I > figure that I could just write a line of code to read in from the > console, > but I thought there might be a more pythonic way of doing it. > > Here's my function so far, with variables replaced with constants > to make > it easier to read: > > def connect_clicked(self, widget, data=None): > if locked: > os.popen("sudo network-admin -c ath0") > self.emit('connection-attempted', "ath0") > > else: > os.popen("sudo iwconfig ath0 ap 00:0F:B3:31:CB:01") > self.emit('connection-attempted', "ath0") > > Thanks much! > > Cheers, Rick > -------------- next part -------------- An HTML attachment was scrubbed... URL: From s323 at mail.ru Tue Feb 14 07:12:37 2006 From: s323 at mail.ru (Sergey) Date: Tue, 14 Feb 2006 15:12:37 +0300 Subject: file names longer than MAX_PATH under Windows 2003 References: Message-ID: "Steven D'Aprano" wrote in message news:pan.2006.02.14.12.09.41.447607 at REMOVETHIScyber.com.au... > Are you passing a unicode object to the function? > > f = file(u"E:\\files\\...\\something.dat", "r") I pass variable c into functions: >>> c u'\\\\.\\e:\\files\\\u041f\u0420\u041e\u0414\u041e \u041c\u0435\u043d\u0435\u043 [many unicode chars skipped] 44b\u0439_\u0411\u044e\u0434\u0436\u0435\u0442.xls' From sbaush at gmail.com Thu Feb 2 18:37:43 2006 From: sbaush at gmail.com (Sbaush) Date: Fri, 3 Feb 2006 00:37:43 +0100 Subject: Control if a input text is IP In-Reply-To: References: Message-ID: thanks!! your ipcheck is perfect fo me!! 2006/2/3, Fredrik Lundh : > > Sbaush wrote: > > > My app has in input an ip address in IPv4 notation. > > is there a function that control if input is a string in IPv4 notation? > > here's one way to do it: > > def ipcheck(s): > try: > a, b, c, d = [chr(int(c)) for c in s.split(".")] > except ValueError: > return False > else: > return True > > another way is to use regular expressions; see > > http://www.regular-expressions.info/examples.html > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Sbaush -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Thu Feb 16 22:14:28 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 16 Feb 2006 21:14:28 -0600 Subject: calculating on matrix indices In-Reply-To: <43F50D7F.8010108@bryant.edu> References: <43F50D7F.8010108@bryant.edu> Message-ID: Brian Blais wrote: > Hello, > > In my attempt to learn python, migrating from matlab, I have the following problem. > Here is what I want to do, (with the wrong syntax): > > from numpy import * > > t=arange(0,20,.1) > x=zeros(len(t),'f') Also, you probably don't want to be using literal typecode strings. It's easy to forget which code corresponds to which type. They are only accepted in numpy for compatibility with Numeric. Use the real dtype objects instead: numpy.float32, numpy.float64, etc. The builtin type objects int and float are also accepted for convenience and correspond to the C types that underlie the respective Python objects. -- Robert Kern robert.kern at gmail.com "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From wolfgang.lipp at gmail.com Fri Feb 3 16:17:03 2006 From: wolfgang.lipp at gmail.com (wolfgang.lipp at gmail.com) Date: 3 Feb 2006 13:17:03 -0800 Subject: web.py + cheetah delivering incomplete pages In-Reply-To: <1138988779.571240.209970@g43g2000cwa.googlegroups.com> References: <1138977432.206287.16130@g47g2000cwa.googlegroups.com> <1138988779.571240.209970@g43g2000cwa.googlegroups.com> Message-ID: <1139001423.549772.325090@f14g2000cwb.googlegroups.com> yeah, posted it there too, but, you see, there are but 95 members in that group -- guess it's more productive to ask this right here. we'll see. _w. From claudio.grondi at freenet.de Wed Feb 15 22:15:37 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 16 Feb 2006 04:15:37 +0100 Subject: Xah's Edu Corner: accountability & lying thru the teeth In-Reply-To: References: <1133844932.007824.26780@g43g2000cwa.googlegroups.com> <1136236586.734775.212440@f14g2000cwb.googlegroups.com> <1137784561.589887.58380@o13g2000cwo.googlegroups.com> <1139909629.798938.284160@g47g2000cwa.googlegroups.com> Message-ID: Anno Siegel wrote: > Xah Lee wrote in comp.lang.perl.misc: > > >>...a mechanism, so that any fuckhead tech geekers with their >>loud cries will hurt badly when they open their mouths in public... In this above I hear the voice of someone badly disappointed seeking an apology and excuse for being in that condition in the world around and not inside himself. My guess from the experience of being, as Usenet newbie, first a victim of Xah trolls and from the experience of watching Xah activities over currently more than one year, is that: The turning point, when one could start to be like Xah is, when suddenly for oneself some simple truths which has not been recognized for so long before, get revealed before the inner mental eye. One finds himself in a situation where own past stupidity becomes so apparent, that it is hard to accept this fact as it is. The ways to manage such condition can be very different. One of the possibilities is to look for the 'outside' reasons and make them responsible for the misery. There was, is and will be always enough idiocy around, disguised as by many people fully accepted absolute truths, which can be made guilty of keeping a believing them individual relatively stupid for a very long time (or even forever). The revelation of the simply fact, that one was 'cheated' for so long by from the just achieved point of view as impertinent insulting and stupid considered authorities without being able to see it directly already in the past, hurts so much, that it results in strong emotional reaction manifestating itself often also in using many dirty words. It almost appears in this context, that the past ignorance could be considered a blessing ... After the first caused by the above effect deep depressions has been overcome, it can happen, that one starts to hope to manage the misery by getting in touch with others to share the just reached level of enlightenment in order to progress towards getting rid of eventually still existing remaining wrong believes. The result of this approach can be the experience, that there is as good as none to oneself meaningful response and instead of being understood one is accused of trolling. At that point two aspects important in someones life can start to compete against each other: the accumulated experience and insight, that it makes not much sense to ask the most important to oneself questions publicly and the need for staying in active relationship and mental exchange with others. The outcome of such battle can be, that the only way out of this dilemma is to actually start to troll to get some fun out of the responses and to get the feeling of having impact on others. There are sure many other ways to manage the situation of becoming smarter than before and of staying in contact with many others - Xah has chosen to become a troll as one of the most easy variant out of them. I hope, that one day, he stops to misjudge own level of enlightenment and starts to gain satisfaction out of searching for an also for another people valuable way out of the misery his intellect is trapped in instead of continuing his mostly trolling motivated postings. By the way: I found _this_ posting by Xah very interesting and even if maybe not at first glance noticeable, very close related to what is all the time and continuously hot discussed in the programming related newsgroups. I don't expect Xah to read and reply to this posting, but in spite of this, I would be glad to hear from him here, how my guess is close to his actual motivation. > > > Yeah, good idea! Sure it would be very interesting to see the bets and the reasoning behind the pro and contra. Claudio > > Anno From m.wanstall at gmail.com Sun Feb 19 04:28:06 2006 From: m.wanstall at gmail.com (m.wanstall at gmail.com) Date: 19 Feb 2006 01:28:06 -0800 Subject: os.mkdir simple help In-Reply-To: References: <1140335502.110014.35870@g47g2000cwa.googlegroups.com> Message-ID: <1140341286.223872.48930@g47g2000cwa.googlegroups.com> That's got it, thanks Steven! From sybrenUSE at YOURthirdtower.com.imagination Mon Feb 6 10:17:36 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 6 Feb 2006 16:17:36 +0100 Subject: Detecting line endings References: <1139236514.022464.319970@g14g2000cwa.googlegroups.com> Message-ID: Fuzzyman enlightened us with: > My worry is that if '\n' *doesn't* signify a line break on the Mac, > then it may exist in the body of the text - and trigger ``ending = > '\n'`` prematurely ? I'd count the number of occurences of '\r\n', '\n' without a preceding '\r' and '\r' without following '\n', and let the majority decide. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From cookedm+news at physics.mcmaster.ca Fri Feb 10 20:11:08 2006 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 10 Feb 2006 20:11:08 -0500 Subject: Scientific Computing with NumPy References: Message-ID: "linda.s" writes: > where to download numpy for Python 2.3 in Mac? > Thanks! > Linda I don't know if anybody's specifically compiled for 2.3; I think most of the developers on mac are using 2.4 :-) But (assuming you have the developer tools installed) it's really to compile: python setup.py build && python setup.py install. Do you need Tiger (10.4) or Panther (10.3) compatibility? -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From haraldarminmassa at gmail.com Thu Feb 23 08:30:45 2006 From: haraldarminmassa at gmail.com (Harald Armin Massa) Date: 23 Feb 2006 05:30:45 -0800 Subject: cx_Oracle and UTF8 In-Reply-To: <465kbtF9bvemU1@uni-berlin.de> References: <1140628824.353213.278300@o13g2000cwo.googlegroups.com> <465kbtF9bvemU1@uni-berlin.de> Message-ID: <1140701445.217566.239200@z14g2000cwz.googlegroups.com> Dietz, thank you for your answer. > It's called NLS (national language support), >and it is like a locale-setting in python/C. I'm too lazy to google right Sad thing: I allready googled that and had to learn: you CAN definitely change some parameters, that is sort order and language for error messages with alter session set NLSREGION and set NLSLANGUAGE The only part about the charset is with NLSLANG, which could be set to German_Germany.UTF8 BUT ... NLSLANG is no per-session parameter, not setable per alter session, it needs to get set within the environment to make SQLPLUS recognize it. (and, I do of course use python not sqlplus= In another of the WWW I learned that NLSLANG has to be set on per connection basis; not on per cursor / session basis; so my primary suspect is cx_Oracle.Connection ... but those objects to not have a visible method with any "encoding" in it. Harald From andre.burgaud at gmail.com Sun Feb 12 20:03:15 2006 From: andre.burgaud at gmail.com (Andre Burgaud) Date: Sun, 12 Feb 2006 19:03:15 -0600 Subject: Python equivilant to msgbox() In-Reply-To: <7CQHf.2690$7C3.1780@trnddc08> References: <7CQHf.2690$7C3.1780@trnddc08> Message-ID: <158731350602121703u73515f6dhb74ac0bd1a722fa@mail.gmail.com> Hi, If you target Windows, you may try ctypes http://starship.python.net/crew/theller/ctypes/: >>> from ctypes import * >>> windll.user32.MessageBoxA(None, "MessageBox Text", "MessageBox Caption", 0) 1 >>> or win32api http://starship.python.net/crew/mhammond/win32/: >>> import win32api >>> win32api.MessageBox(0, "Text", "Title") 1 >>> Regards, Andre http://www.burgaud.com/ On 2/12/06, LittlePython wrote: > > Is there an equivalent to a msgbox() or wscript.echo (via wcsript) . I > would like to call this instead of print (to the screen) . I would like to > write a simple script that is not an event drive gui but calls input boxes, > message boxes, or maybe even a file open browser box as well? > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospamformeSVP at gmail.com Sun Feb 26 17:01:45 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Sun, 26 Feb 2006 17:01:45 -0500 Subject: Use of __slots__ Message-ID: Hi: I am puzzled about the following piece of code which attempts to create a class that can be used as record or struct with a limited set of allowed attributes that can be set into an instance of the class. class RecordClass(object): __slots__ = ["foo"] def __init__(self, args): print "Initial slots = ", RecordClass.__slots__ RecordClass.__slots__ = list(args) print "Final slots = ", RecordClass.__slots__ pass def new_record(slotlist): return RecordClass(slotlist) if __name__ == "__main__": record1 = new_record(["age", "name", "job"]) record1.age = 27 record1.name = 'Fred' record1.job = 'Plumber' record1.salary = 50000 When executed I get: Initial slots = ['foo'] Final slots = ['age', 'name', 'job'] Traceback (most recent call last): File "D:\ProgrammingProjects\JustForTesting\recordclasses.py", line 37, in ? record1.age = 27 AttributeError: 'RecordClass' object has no attribute 'age' I don't understand why I cannot set an attribute 'age' into record1. Thanks, Don. From *firstname*nlsnews at georgea*lastname*.com Thu Feb 9 23:04:02 2006 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Fri, 10 Feb 2006 04:04:02 GMT Subject: super(...).__init__() vs Base.__init__(self) References: <43eb5a9d$1_2@newspeer2.tds.net> <43eba7f7$0$507$9b4e6d93@newsread4.arcor-online.net> Message-ID: <*firstname*nlsnews-14ADC6.23042609022006@news.verizon.net> In article <43eba7f7$0$507$9b4e6d93 at newsread4.arcor-online.net>, Jan Niklas Fingerle wrote: > ...Super is a good tool to use, when dealing with > diamond shape inheritance. In any other case I would use the direct > calls to the base classes. In fact, i've yet to find a non-textbook-case > where I really need diamond shape inheritance. ... As long as you don't use multiple inheritance with new-style classes, you'll be fine. ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From python-url at phaseit.net Mon Feb 27 18:19:16 2006 From: python-url at phaseit.net (Cameron Laird) Date: Mon, 27 Feb 2006 23:19:16 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Feb 27) Message-ID: QOTW: "Actually, Python has the distinction of being both a great tool language *and* a great Zen language. That's what makes Python so cool ;-)))" - Ron Stephens "It is probably possible to do the whole thing with a regular expression. It is probably not wise to do so." - John Zenger (among MANY other wise people) Steve Holden generates abundant volume of PyCon reportage when executive responsibilities don't tether him: http://holdenweb.blogspot.com/ A question from Brian Blais on the simplest non-trivial sorting elicits a satisfying range of expressions: http://groups.google.com/group/comp.lang.python/browse_thread/thread/560fda5a309a08ab/ Use the 'Net for backups in a far more sophisticated way: http://www.csua.berkeley.edu/~emin/source_code/dibs/ A beta release of the updated official Python site will go live on 5 March 2006: http://wiki.python.org/moin/PyCon2006/Sprints/PydotorgSprint ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From amorgan at xenon.Stanford.EDU Wed Feb 8 13:57:19 2006 From: amorgan at xenon.Stanford.EDU (Alan Morgan) Date: Wed, 8 Feb 2006 10:57:19 -0800 (PST) Subject: Too Many if Statements? References: <1139330447.716190.247940@z14g2000cwz.googlegroups.com> <1139384021.290153.120470@g14g2000cwa.googlegroups.com> Message-ID: In article <1139384021.290153.120470 at g14g2000cwa.googlegroups.com>, Pierre Quentel wrote: >This is because Python has a hidden mechanism to detect programs >generated by Perl scripts, and make them crash with no explanation In my case it turned out to be python having a hidden method to detect when you are using an ancient version of python. Retesting with a newer version didn't find any problems. Alan -- Defendit numerus From onurb at xiludom.gro Tue Feb 14 07:16:40 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 14 Feb 2006 13:16:40 +0100 Subject: [OT] Pythonic gui format? In-Reply-To: References: <1139858810.606052.39130@z14g2000cwz.googlegroups.com> <43f11990$0$667$626a54ce@news.free.fr> Message-ID: <43f1ca45$0$7339$626a54ce@news.free.fr> Christoph Zwerschke wrote: > Bruno Desthuilliers schrieb: > >> Gregory Petrosyan a ?crit : >> >>> I am currently seeking for pythonic alternative for XML. >> >> (snip) > Bruno, before writing another simple GUI, Sorry, Christoph, wrong attribution !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rtilley at vt.edu Wed Feb 8 08:34:35 2006 From: rtilley at vt.edu (rtilley) Date: Wed, 08 Feb 2006 08:34:35 -0500 Subject: os.walk() dirs and files In-Reply-To: References: Message-ID: rtilley wrote: > Hello, > > When working with file and dir info recursively on Windows XP. I'm going > about it like this: > > for root, dirs, files in os.walk(path): > for f in files: > ADD F to dictionary > for d in dirs: > ADD D to dictionary > > Is it possible to do something such as this: > > for root, dirs, files in os.walk(path): > for f,d in files, dirs: > ADD F|D to dictionary Just to clarify. In this particular case, I do not need to differentiate between files and dirs... so would it be possible to do something such as this: for root, dirs, files in os.walk(path): for fs_object in files, dirs: ADD fs_object to dictionary From cipherpunk at gmail.com Sun Feb 19 03:43:13 2006 From: cipherpunk at gmail.com (Robert J. Hansen) Date: 19 Feb 2006 00:43:13 -0800 Subject: Python vs. Lisp -- please explain In-Reply-To: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> Message-ID: <1140338593.555029.63860@g43g2000cwa.googlegroups.com> > what [is it] about Python that is so different from Lisp that it > can't be compiled into something as fast as compiled Lisp? IMO, it's the lack of competing implementations. LISP has a very well-defined ANSI specification. Lots of different people have written LISPs, from Franz to Steel Bank to GNU to... etc. Each of these competes with the others on different grounds; some are purely interpreted (ala CLISP), some are compiled (CMUCL), some are... etc. They all implement substantially the same language, but the plethora of different implementations has been a tremendous boon for the development of efficient compilers, interpreters and garbage collectors. By comparison, Python lacks anywhere near as many competing implementations. In some respects the lack of competing implementations is a Good Thing. In some respects it's a Bad Thing. On balance it's just a thing. From timr at probo.com Wed Feb 15 03:15:47 2006 From: timr at probo.com (Tim Roberts) Date: Wed, 15 Feb 2006 08:15:47 GMT Subject: how to write a C-style for loop? References: Message-ID: <8oo5v11ssquc1ota7j8ualtv9ugdgrn5ql@4ax.com> John Salerno wrote: > >I assume this is the way for loops are written in C, but if it helps to >be specific, I'm referring to C# for loops. The Python for loop seems to >be the same (or similar) to C#'s foreach loop: > >foreach int i in X > >But how would you write a C# for loop in Python? Do you rework a while >loop, or use the range() function? > >Here's an example: > >for (int i = 0; i < 50; i += 5) > >How would that go in Python, in the simplest and most efficient way? for i in range(0,50,5): print i -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sw at wordtech-software.com Sat Feb 11 12:03:42 2006 From: sw at wordtech-software.com (Kevin Walzer) Date: Sat, 11 Feb 2006 12:03:42 -0500 Subject: Yet another GUI toolkit question... In-Reply-To: References: <9eae7$43ed2ce5$4275d90a$5719@FUSE.NET> <1139674743.846644.281840@z14g2000cwz.googlegroups.com> Message-ID: <43EE18EE.2010006@wordtech-software.com> Steve Holden wrote: > Robert Hicks wrote: >> Wow you are so wrong about Tk on OSX. Soon this is just not going to be >> the case at all for any of the system Tcl/Tk runs on. The Tcl folks >> have come out with a package called "Tile" that is going to be rolled >> in. It gives you native L&F on OSX, Windows, Linux. >> > This is good news if it happens, but right now it's just another dose of > "real soon now". > > regards > Steve Not true. It's already available. I've shipped three open-source and one commercial application making use of Tile. The Tkinter wrapper is here: http://mfranklin.is-a-geek.org/docs/Tile/index.html The server is down at the moment but is supposed to be back online shortly. -- Kevin Walzer iReveal: File Search Tool http://www.wordtech-software.com From sw at wordtech-software.com Sun Feb 12 11:36:07 2006 From: sw at wordtech-software.com (Kevin Walzer) Date: Sun, 12 Feb 2006 11:36:07 -0500 Subject: ANN: PyGUI 1.6 In-Reply-To: References: Message-ID: <41ec2$43ef63f7$4275d90a$28603@FUSE.NET> greg wrote: > PyGUI 1.6 is now available: > > http://www.cosc.canterbury.ac.nz/~greg/python_gui/ > > The major change in this version is that the Mac version > is based on Cocoa instead of Carbon. This should provide a > much better base for future development, but it does mean > that MacOSX will now be required. (This isn't as big a > change as it seems, since the Carbon version actually > required MacOSX too, despite being Carbon.) > > There have been numerous other changes and improvements > as well. See the CHANGES file in the distribution or on > the web site for full details. > Does anyone actually use this toolkit? How does it compare to wxPython, for instance? -- Kevin Walzer iReveal: File Search Tool http://www.wordtech-software.com From fakeaddress at nowhere.org Wed Feb 15 21:04:59 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 16 Feb 2006 02:04:59 GMT Subject: is socket thread safe? In-Reply-To: References: <1139912679.559724.131020@f14g2000cwb.googlegroups.com> Message-ID: Carl J. Van Arsdall wrote: > Steve Horsley wrote: > >> e2wugui at gmail.com wrote: >> >> >>> thread1: >>> while 1: >>> buf = s.read() >>> process(buf) >>> >>> thread2: >>> while 1: >>> buf = getdata() >>> s.write(buf) >> >> >> It is safe, but watch out for this gotcha: If thread B calls s.close() >> while thread A is blocked in s.read(), thread A will never return from >> the read. My preferred solution is to set socket timeout to a few >> seconds, and loop checking a status flag so I know when to quit. Certainly one needs timeouts to avoid hanging should the remote side stop. Sockets don't have a read() method, and hanging on recv() doesn't seem to have anything to do with close(). I didn't find any definitive doc, so I tested using Python sockets on Linux (Debian/Ubuntu current) and WinXP. A recv() started before the close() will block/return just as if close() were never called. The close() neither triggers recv() to abort, nor prevents it from receiving data and detecting shutdown. > I think a better thing would be to use something like a condition object > to tie the two threads together and not use any polling loops. > > i.e. consumer goes to sleep while data buffer is empty, producer > produces and signals condition object, consumer wakes up and consumes. I can infer two producer-consumer relationships from the example, but they don't allow a condition object; the writer's consumer and the reader's producer are on the remote end of the socket. The socket will already handle the blocking and wake-up. > To take this a step further, you have a status flag that is set to > something like QUIT or CONSUME and when the condition is triggered wake > up, then examine the status flag to determine if the consumer should > then quit, consume, or whatever else you'd want your consumer thread to do. What problem are you trying to solve? Normal socket sending, receiving, and shutdown discipline work fine. When the writer is done writing, it should call sock.shutdown(socket.SHUT_WR). When the reader gets zero bytes from recv(nonzero), that means the remote end has finished writing, so the reader may call sock.shutdown(socket.SHUT_RD). -- --Bryan From grahn+nntp at snipabacken.dyndns.org Mon Feb 13 17:19:54 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 13 Feb 2006 22:19:54 GMT Subject: Netstat in python. Does it's possible? References: <43EE0286.5020409@v.loewis.de> <43EE7B7E.5050802@v.loewis.de> <43efaef5$0$29674$9b622d9e@news.freenet.de> Message-ID: On Sun, 12 Feb 2006 22:56:06 +0100, Martin v. L?wis wrote: > Jorgen Grahn wrote: >> I was thinking mostly about /proc, /sys and related file systems. I have a >> feeling parts of them they change quite frequently under Linux, and of >> course under other Unices they may look completely different, or be absent. >> >> Like Mr Laird said elsewhere, the best thing might be to popen() netstat >> and parse its output. > > Hmm. And the netstat output cannot change, and is identical across all > systems? I was going to mention that complication, but I didn't want to depress the original poster any more ... /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From smitty_one_each at bigfoot.com Sat Feb 11 21:40:38 2006 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Sat, 11 Feb 2006 21:40:38 -0500 Subject: Inserting record with Microsoft Access References: <43EB0355.9000603@compuscan.co.za> <1139658741.918706.60230@g44g2000cwa.googlegroups.com> Message-ID: <87zmkx8fkp.fsf@bigfoot.com> >>>>> "Frank" == Frank Millman writes: Frank> SELECT @@IDENTITY returns the most recent of all Frank> inserts. If you have a complex transaction which triggers Frank> inserts into other tables, it may not return the one you Frank> want. Frank> This one allows you to specify the tablename, and it will Frank> return the most recent key inserted into that table. Frank> I got this from the built-in help for SQLServer. I cannot Frank> say whether it works for Access as well. Frank> Frank I've used SELECT @@IDENTITY to good effect, but I agree that there is no telling what the scope of the variable holding @@IDENTITY is, and it could turn out to be a kick in the naughty bits. Depending on the criteria, you might effect the INSERT for a parent record, and contiue any child record INSERTs by means of the DLookup() function (Access-only syntactic sugar around nested SELECTs) without ever having to know the key you would have discovered through SELECT @@IDENTITY. R, Chris From lycka at carmen.se Fri Feb 10 07:01:40 2006 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 10 Feb 2006 13:01:40 +0100 Subject: Too Many if Statements? In-Reply-To: <1139517959.741090.28560@g14g2000cwa.googlegroups.com> References: <1139330447.716190.247940@z14g2000cwz.googlegroups.com> <6e2iu1hdb8fvlfkcuulloiiq1khlbhret1@4ax.com> <1139517959.741090.28560@g14g2000cwa.googlegroups.com> Message-ID: slogging_away wrote: > Adding it back in > cause it to not run - no error message - just a return to the >>> in > the IDLE console window much as if I had executed the 'Check Module' > command. What happens if you run it from the command line instead of IDLE? After all, it might be some problem in IDLE involved here. Even if it doesn't work correctly outside IDLE, I was thinking that IDLE might swallow some kind of error message. From lucaberto at libero.it Thu Feb 23 08:10:56 2006 From: lucaberto at libero.it (luca72) Date: 23 Feb 2006 05:10:56 -0800 Subject: Pyserial never read In-Reply-To: References: <1140105936.408387.88130@z14g2000cwz.googlegroups.com> <1140219414.143448.234450@z14g2000cwz.googlegroups.com> <1140302110.028540.176210@g43g2000cwa.googlegroups.com> <1140599901.082142.262540@f14g2000cwb.googlegroups.com> Message-ID: <1140700256.017002.177580@f14g2000cwb.googlegroups.com> Hello ALSO... YOU NEVER SPECIFY A VARIABLE TO RECEIVE THE DATA -- ANYTHING YOU DO READ IS BEING DUMPED ON THE FLOOR! I see the read data with a sniffer. with the same serial caracteristic in delphi i obtain the right answer. I use serial writestr and serial readstr. If the serial package is anything like regular file I/O, that line will buffer/block until a new-line character is received, then return data upto/including the new-line. If the inbound data has multiple lines, you need individual readlines. For example i i send D0360000EC the right answer is D0360000EC0000FFBC35DC44 etc... i need new Line? why if i use ser.read(10) i see only the first 5 byte and not the rest, why if i use the inwaigth i answer that i have only 5 byte to read. Regards Luca From martin at v.loewis.de Tue Feb 7 14:43:32 2006 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 07 Feb 2006 20:43:32 +0100 Subject: Python 2.4.2 using msvcrt71.dll on Win and compatibility issues In-Reply-To: References: Message-ID: <43E8F864.6050605@v.loewis.de> Christoph Zwerschke wrote: > Is there a general strategy to avoid this kind of problems? In general, the only Microsoft-supported strategy is that you must use only a single msvcrt in the entire application. So either recompile PostGres, or recompile Python. In the specific case, having PQprint print to a string (rather than to a file) might work. OTOH, it appears there is no "print to string" code in postgres. So here is another strategy: flush the stream before going into postgres, then obtain the fileno() of the stream, and fdopen it with postgres' iostreams library. That might also be tricky to implement, but could work. Regards, Martin From fredrik at pythonware.com Mon Feb 13 13:27:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Feb 2006 19:27:10 +0100 Subject: Location of Python modules References: <1139854184.504114.46690@z14g2000cwz.googlegroups.com> Message-ID: "Byte" wrote: > Pretty much self explanatry, where are Python modules stored in Linux? > (i.e. in /usr/bin/local, or where?) it depends on how and where Python is installed. to see where they are on your install, use $ python -c "import sys; print sys.path" ['', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages', ... to check where a given module is installed, you can do $ python -c "import cgi; print cgi.__file__" /usr/lib/python2.4/cgi.pyc hope this helps! From LittlePython at lost.com Tue Feb 14 21:37:14 2006 From: LittlePython at lost.com (LittlePython) Date: Wed, 15 Feb 2006 02:37:14 GMT Subject: Python equivilant to msgbox() References: <7CQHf.2690$7C3.1780@trnddc08> <43efd40a$1_2@newspeer2.tds.net> <6WQHf.2700$7C3.2665@trnddc08> <3buIf.32386$lo3.16580@trnddc07> Message-ID: I am glad you did remind me of WScript.Shell ... I have to keep in mind that most if not all of what I have been using in VBS is avail to me. Thx "Claudio Grondi" wrote in message news:dstup1$rm$1 at newsreader3.netcologne.de... > LittlePython wrote: > > I am no VB programmer just dabble in vbscripting abit. The only one I am > > aware of is the popup as self closing. I never thought of using com. > Ok, so my remarks about COM were not for you. > > > > Do you know of any thing for a busy box in the same vain as easygui > No, I don't, but it doesn't mean, that there is none considering myriads > of various available COM components. My idea was to make you aware, that > you can use your VB compiler for creating any ActiveX/COM components for > usage with Python the way I have described, but as you write it seems > not to be an option for you. > > So I have to admit, that EasyGUI is in your case apparently > >>> exactly what you was looking for ... > > :-) > > Claudio > > > > > > "Claudio Grondi" wrote in message > > news:dsq6oc$lb8$1 at newsreader3.netcologne.de... > > > >>LittlePython wrote: > >> > >>>That is exactly what I was look for .. thx > >> > >>Surprised to hear that. > >> > >>As VisualBasic programmer I would expect you to have experience with > >>ActiveX on Windows, where the best way to go with Python is to reuse all > >>the ActiveX components and their known user interfaces (i.e. constants > >>to use as parameter and constants for interpretation of return values) > >>directly from within Python. > >> > >>A message box goes e.g. this way: > >> > >> >>> import win32com.client > >> >>> axWshShell = win32com.client.Dispatch("WScript.Shell") > >> >>> axWshShell.Popup(u"(MsgText)This axWshShell.Popup closes itself > >>after 45 seconds", 45, u"(MsgTitle)Testing WScript.Shell object:", 1) > >> > >>By the way: is there a ready for direct use timed self closing Ok/Cancel > >>message box in any of the proposed GUI packages? > >> > >>Claudio > >> > >>> > >>>"Kent Johnson" wrote in message > >>>news:43efd40a$1_2 at newspeer2.tds.net... > >>> > >>> > >>>>LittlePython wrote: > >>>> > >>>> > >>>>>Is there an equivalent to a msgbox() or wscript.echo (via wcsript) . I > >>>>>would like to call this instead of print (to the screen) . I would like > >>>>>to write a simple script that is not an event drive gui but calls input > >>>>>boxes, message boxes, or maybe even a file open browser box as well? > >>>> > >>>>Take a look at EasyGUI: > >>>>http://www.ferg.org/easygui/ > >>>> > >>>>Kent > >>> > >>> > >>> > > > > From steve at hastings.org Fri Feb 24 21:24:56 2006 From: steve at hastings.org (Steve R. Hastings) Date: Fri, 24 Feb 2006 18:24:56 -0800 Subject: list assignment using concatenation "*" References: <1140832774.530010.251930@j33g2000cwa.googlegroups.com> Message-ID: > if I do: > > a = [ [0] * 3 ] * 3 > a[0][1] = 1 > > I get > > a = [[0,1,0],[0,1,0],[0,1,0]] The language reference calls '*' the "repetition" operator. It's not making copies of what it repeats, it is repeating it. Consider the following code: >>> a = [] >>> b = [] >>> a == b True >>> a is b False >>> >>> a = b = [] >>> a is b True >>> a.append(1) >>> a [1] >>> b [1] Each time you use [], you are creating a new list. So the first code sets a and b to two different new lists. The second one, "a = b = []", only creates a single list, and binds both a and b to that same list. In your example, first you create a list containing [0, 0, 0]; then you repeat the same list three times. >>> a = [[0]*3]*3 >>> a [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> a[0] is a[1] True >>> a[0] is a[2] True When you run [0]*3 you are repeating 0 three times. But 0 is not mutable. When you modify a[0] to some new value, you are replacing a reference to the immutable 0 with some new reference. Thus, [0]*3 is a safe way to create a list of three 0 values. When you have a list that contains three references to the same mutable, and you change the mutable, you get the results you discovered. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From fredrik at pythonware.com Sun Feb 19 09:45:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Feb 2006 15:45:28 +0100 Subject: Any Tkinker based rich text widget? References: <1140329900.341774.175600@f14g2000cwb.googlegroups.com> Message-ID: sullivanz.pku at gmail.com wrote: > I am using the standard python GUI Tkinter as my program's main > interface. Although I know wxPython has some widget to support rich > text widget, but I do not have time to shift to wx---- series. Does > anyone know any Tkinter based widget that support: > > 1. Blod, Italic, Underline and their combinations. > 2. Several most commonly used fonts, like Times New Roman and Arial > 3. Multiline text > 4. Cross platform support. Available in Linux-RedHat and Mac OS series > and Windows 2000 or above. > 5.Image embedding. Support jpeg, gif, bmp. The more the better. > > and better support: > Hyperlink, Text color, the more the better. Tkinter's standard Text widget can do all this, of course: http://effbot.org/tag/Tkinter.Text by default, Tkinter only supports GIF and PPM, but you can use PIL's ImageTk.PhotoImage class instead of Tkinter's own PhotoImage to get support for ~30 more formats: http://www.pythonware.com/products/pil/ http://effbot.org/tag/PIL.ImageTk to deal with hyperlinks, use tag event bindings: http://effbot.org/zone/tkinter-text-hyperlink.htm ::: there's in fact a complete browser built on top of Tk's Text widget: http://grail.sourceforge.net/ but I don't know how much work it would be to "widgetize" that application. hope this helps! From sbaush at gmail.com Thu Feb 23 19:21:10 2006 From: sbaush at gmail.com (Sbaush) Date: Fri, 24 Feb 2006 01:21:10 +0100 Subject: Fail in sending UDP packet In-Reply-To: References: Message-ID: No one of you has a idea?? On 2/23/06, Sbaush wrote: > > Hi all. I've attached my SendReceive class. I have e a big problem! > My program create a packet, then call the send function to send this. the > first time the packet is not sent, then it works perfectly! > WHY??? Have you idea?? > > -- > Sbaush > -- Sbaush -------------- next part -------------- An HTML attachment was scrubbed... URL: From erniedude at gmail.com Fri Feb 3 17:34:21 2006 From: erniedude at gmail.com (Ernesto) Date: 3 Feb 2006 14:34:21 -0800 Subject: Launch Windows command window.... In-Reply-To: <1139005568.749960.261980@g44g2000cwa.googlegroups.com> References: <1139003975.837861.141680@o13g2000cwo.googlegroups.com> <1139004370.221885.190540@f14g2000cwb.googlegroups.com> <1139005568.749960.261980@g44g2000cwa.googlegroups.com> Message-ID: <1139006061.109731.187830@z14g2000cwz.googlegroups.com> jay graves wrote: > > This should work but only lightly tested. > subprocess.Popen("start telnet.exe -f C:\Folder\output.txt localhost > 6000",shell=True) Thanks a lot, but this still didn't launch a seperate telnet window. I just want the telnet window to open up and do "it's thing" in the background. Thanks again. From wrongbad at gmail.com Fri Feb 3 14:09:28 2006 From: wrongbad at gmail.com (I V) Date: 3 Feb 2006 11:09:28 -0800 Subject: OO conventions In-Reply-To: <1138971920.353603.38040@f14g2000cwb.googlegroups.com> References: <1138971920.353603.38040@f14g2000cwb.googlegroups.com> Message-ID: <1138993768.634863.166250@f14g2000cwb.googlegroups.com> Nicola Musatti wrote: > I don't think this is all there is to it. Even though a class such as > Image might not have a sensible default, initial state it still might > not be reasonable to burden it with the ability to collect the > information needed to reach such an initial state. To put it it another > way: a car is a car, it isn't a car factory. What's the "burden", though? Surely the only burden is that the class needs to take the relevant parameters to its __init__ method, which is no more of a burden than providing some other initialization method that takes the relevant parameters. > Factory functions (or classes) are there to solve this problem and > still allow a clean separation of concerns. Although instances of Klass > are created uninitialized, they only live in this state within their > factory and only reach trhe outside world only when they are in a > usable state. This may be my limited imagination, but I can't think of a situation when you would prefer something like: def factory(info): k = Klass() data = get_initial_data(info) k.set_data(data) return k to: def factory(info): data = get_initial_data(info) return Klass(data) What would be the value of doing the initialization in a separate method, rather than the constructor? From fabioz at esss.com.br Thu Feb 2 04:53:18 2006 From: fabioz at esss.com.br (Fabio Zadrozny) Date: Thu, 02 Feb 2006 07:53:18 -0200 Subject: howto catch an Exception and still print the TraceBack? In-Reply-To: <43e1af8b$0$343$5fc30a8@news.tiscali.it> References: <43e073bd$0$341$5fc30a8@news.tiscali.it> <43e1af8b$0$343$5fc30a8@news.tiscali.it> Message-ID: <43E1D68E.5030709@esss.com.br> Saizan wrote: >Thanks, I had completely missed the module traceback... >I'll use traceback.print_exc(), it seems the most straightforward way. >The only flaw is that the traceback starts in the method where i catch the exception and not from "__main__", but I guess it can't be helped. > > Actually, I guess that if you wanted to check the 'upper stack', you could do it by checking sys._getframe() to get the current frame and then go upwards with frame.f_back (that's how debbugers work), that way you could get info on all the stacks you currently have... so if you think it's worth it... ;-P Cheers, Fabio From matt at pollenation.net Thu Feb 2 09:09:15 2006 From: matt at pollenation.net (Matt Goodall) Date: Thu, 02 Feb 2006 14:09:15 +0000 Subject: psycopg2 In-Reply-To: References: Message-ID: <43E2128B.1060204@pollenation.net> Jane Goldman wrote: > Hello, > > I bigginer Python programmer. I am working on web application that > access PostgreSQL on backend. After I imported PSYCOPG2 module in my > program I started to get unwanded debug output into my web bowser. It is > something like that: > > initpsycopg: initializing psycopg 2.0b6.2 (dec dt ext pq3) > typecast_init: initializing NUMBER typecast_new: new type at = 00962920, > refcnt = 1 typecast_new: typecast object created at 00962920 > typecast_add: object at 00962920, values refcnt = 2 typecast_add: adding > val: 20 typecast_add: adding val: 23 typecast_add: adding val: 21 > typecast_add: adding val: 701 typecast_add: adding val: 700 > typecast_add: adding val: 1700 typecast_add: base caster: 00000000 > typecast_init: initializing LONGINTEGER typecast_new: new type at = > 00962960, refcnt = 1 typecast_new: typecast object created at 00962960 > typecast_add: object at 00962960, values refcnt = 2 typecast_add: > > and so on ... > > I use Cheetah template to generate HTML code. I run Active python 2.4 in > Windows XP enviroment. > > Any help how to stop get this garbage in my web browser would be highly > appreciated. It looks you installed a version that has the PSYCOPG_DEBUG flag turned on. That flag causes psycopg2 to emit gobs of useless information ;-). I would recommend downloading the latest beta release from http://initd.org/. Alternatively you can remove the PSYCOPG_DEBUG from setup.cfg in the version you already have and reinstall. Hope this helps. - Matt -- __ / \__ Matt Goodall, Pollenation Internet Ltd \__/ \ w: http://www.pollenation.net __/ \__/ e: matt at pollenation.net / \__/ \ t: +44 (0)113 2252500 \__/ \__/ / \ Any views expressed are my own and do not necessarily \__/ reflect the views of my employer. From singletoned at gmail.com Tue Feb 7 09:01:42 2006 From: singletoned at gmail.com (Ed Singleton) Date: Tue, 7 Feb 2006 14:01:42 +0000 Subject: Question about idioms for clearing a list In-Reply-To: <1139300825.858426.12680@o13g2000cwo.googlegroups.com> References: <1139231464.914400.37100@g44g2000cwa.googlegroups.com> <43E7F59B.9070009@REMOVEMEcyber.com.au> <1139300825.858426.12680@o13g2000cwo.googlegroups.com> Message-ID: <34bb7f5b0602070601i2aca76a0r@mail.gmail.com> On 7 Feb 2006 00:27:05 -0800, Raymond Hettinger wrote: > There was a pithy Tim Peters quotation to the effect that he was > unpersuaded by language proposals predicated on some hypothetical > average programmer not being smart enough to understand something that > the rest of us find to be basic. The problem is that the average programmer in question isn't hypothetical in this case. I'm a fairly average programmer (better than average compared to my immediate colleagues). I've read every tutorial I can get my hands on, but I have no _memory_ of ever coming across the del keyword, let alone that it is fundamental to Python, and I have no idea what collections school is. I doubtless have read of it at some point, but as no importance has ever been attached to it, I have probably not remembered it. Similarly, I remember slices simply because they are handy, not because I have ever heard of them being fundamental before. (I don't argue their fundamentalness one way or other, it's just that you seem to think that all people who have learned Python have some knowledge of this hugely important feature). The other problem with your use of the quote is that the smartness of the average programmer, or their ability to understand the feature, is not in question. It is their ability to know of the existence of the feature, or to find out about it. As a general rule of thumb, I would say that if a person is struggling with a language, it is primarily a problem with the language, and than problem with the documentation, and lastly a problem with the person. Ed From littlejohn.75 at news.free.fr Sat Feb 18 08:35:54 2006 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 18 Feb 2006 13:35:54 GMT Subject: GDI in python>? References: <1140242543.204760.174390@g44g2000cwa.googlegroups.com> Message-ID: <43f722ba$0$29607$626a54ce@news.free.fr> Le 17 Feb 2006 22:02:23 -0800, al pacino a ?crit : > hi, > > is it possible to address the 'screen pixels' using python , like > analogous to older dos( functions that graphics.h provides') or win api > calls for gdi. Some possibilities (all on Win32 only): ctypes by Thomas Heller venster (uses ctypes) on sourceforge win32all by Marc Hammond > > what i want is to display clusters (in differetn colours) on screen > using python. > > thanks. > From "jay\" at (none) Sat Feb 25 10:41:57 2006 From: "jay\" at (none) (none) Date: Sat, 25 Feb 2006 08:41:57 -0700 Subject: Problem with Property Message-ID: I'm trying to implement a simple repeateable property mechansism so I don't have to write accessors for every single instance variable I have. ------------ classMyObject: def __init__ (self): self.initialize() def initialize(self): self._value=None def _setProperty (self, name, value): print "set property" setattr (self, name, value) def _getProperty (self, name): print "get property" return getattr (self, name) #properties value = property (lambda self: self._getProperty("_value"), lambda self, value: self._setProperty("_value", value)) def testObject(): o = MyObject() print o.__dict__ print o.value o.value = 123 print o.value print o.__dict__ if __name__ == "__main__": testObject() --------- The outout looks like this ------------ {'_value': None} get property None 123 {'_value': None, 'value': 123} ----------- As you can see, the _getProperty() method gets called properly when I do 'o.value' but 'o.value = 123' does not seem to use the property stucture. I can't figure out why 'o.value=123' does not call _setProperty() Any ideas? Jay From roy at panix.com Tue Feb 7 15:34:39 2006 From: roy at panix.com (Roy Smith) Date: 7 Feb 2006 15:34:39 -0500 Subject: Python Class use References: <1139344110.219073.244830@f14g2000cwb.googlegroups.com> Message-ID: S Borg wrote: > I am running Python on Mac OS X. The interpreter has been great for > learning the basics, but I would now like to be able to reuse code. Excellent. Code reuse is what it's all about! > How do I write reusable code? I have done it "The Java way": write > the class, and save it to my home directory, then call it from the > interpreter That's pretty much what you do in Python. Write your class into a file called foo.py and save it. Then, start up an interpreter and do "import foo". You might want to read about "modules" in the Python tutorial (http://docs.python.org/tut/node8.html). From lee at ricis.com Mon Feb 6 13:44:00 2006 From: lee at ricis.com (Lee Leahu) Date: Mon, 6 Feb 2006 12:44:00 -0600 Subject: threads and memory In-Reply-To: References: Message-ID: <20060206124400.351bc0c8@tiger.ricis.com> Hi List, > >I am trying to write a simple threaded application which will simulate 1000 > >connections to a remote service in order to "stress test" that the remote > >service can handle that many connections. > [...] > >Is there a way to accomplish what I am trying to do, perhaps in a more > >memory-friendly way? > > Yes. You don't need one thread per connection: > http://docs.python.org/lib/module-asyncore.html I am running into a problem where asyncore is through a filedescriptor error if I try to launch more that 1023 connections: ------------------------------------ Traceback (most recent call last): File "./test.py", line 46, in ? asyncore.loop() File "/usr/lib/python2.4/asyncore.py", line 192, in loop poll_fun(timeout, map) File "/usr/lib/python2.4/asyncore.py", line 122, in poll r, w, e = select.select(r, w, e, timeout) ValueError: filedescriptor out of range in select() ------------------------------------ Is there a limitation on the number of simultaneous connects that can be made with asyncore ? Attached is the updated source code. Thanks! -- Lee Leahu RICIS, Inc. Internet Technology Specialist 866-RICIS-77 Toll Free Voice (US) lee at ricis.com 708-444-2690 Voice (International) http://www.ricis.com/ 866-99-RICIS Toll Free Fax (US) 708-444-2697 Fax (International) RICIS, Inc. is a member of the Public Safety Alliance Group This email and any attachments that are included in it have been scanned for malicious or inappropriate content and are believed to be safe. -------------- next part -------------- A non-text attachment was scrubbed... Name: test.py Type: text/x-python Size: 1080 bytes Desc: not available URL: From petr at tpc.cz Thu Feb 23 20:44:07 2006 From: petr at tpc.cz (Petr Jakes) Date: 23 Feb 2006 17:44:07 -0800 Subject: pyserial In-Reply-To: <1140702690.396244.142370@g43g2000cwa.googlegroups.com> References: <1140702690.396244.142370@g43g2000cwa.googlegroups.com> Message-ID: <1140745447.632878.286140@p10g2000cwp.googlegroups.com> Few notes from the Python beginner :) HTH. I do not understand what do you mean by the expression: ".... I can read data without try and try again....." Can you be more specific please. I do not understand what do you exactly mean. AFIK the pyserial is waiting while the data occur on the serial port (so called blocking read) so it is not necessary to do some "polling" (checking the serial port periodically) . Following snippets of code is running in infinitive loop, but it is not necessary too be worried about processor utilization because the readline waits for the data on the serial port and the code continues to run when data occurs or when timeout passes. import serial s = serial.Serial(port=0,baudrate=4800, timeout=20) while 1: line = s.readline() # byte = s.read(1) # or you can read No. of bytes according your needs Alternatively you can monitor buffer of the serial port and while data in it, you can read it. while fd.inWaiting() != 0: s.read(1) you can find plenty of examples about pyserial here http://tinyurl.com/p8tt5 What I am not able to figure out is why are you trying to print out input and output buffers (print self.ser.flushInput()) Does it print out something? Petr Jakes From codecraig at gmail.com Thu Feb 16 09:38:22 2006 From: codecraig at gmail.com (abcd) Date: 16 Feb 2006 06:38:22 -0800 Subject: Win32_Process.Create -- not starting process In-Reply-To: References: Message-ID: <1140100702.342629.162920@f14g2000cwb.googlegroups.com> Tim, I am skipping using the batch file and only executing the python script directly...and so far it works fine. So now I have: pid, retVal = wmi.WMI("1.2.3.4").new("Win32_Process").Create(CommandLine="c:\python\python.exe c:\some_script.py") Thanks again...not sure why when using the batch file to start it wouldnt always work, but as long is it works now! From rrr at ronadam.com Mon Feb 27 18:21:00 2006 From: rrr at ronadam.com (Ron Adam) Date: Mon, 27 Feb 2006 17:21:00 -0600 Subject: sort one list using the values from another list In-Reply-To: <44034b68$1@nntp0.pdx.net> References: <1140981038.788111.93500@j33g2000cwa.googlegroups.com> <9bpMf.109707$4l5.58949@dukeread05> <1140990438.693026.14600@p10g2000cwp.googlegroups.com> <00sMf.109743$4l5.9230@dukeread05> <1hbdmux.1uvypp25sjx7jN%aleaxit@yahoo.com> <44034b68$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Ron Adam wrote: >> Ron Adam wrote: >> This probably should be: >> >> def psort11(s1, s2): >> d = dict(zip(s2,s1)) >> assert len(d) == len(s1) >> s1[:] = list(d[v] for v in sorted(d)) > > You could do this to avoid all of those lookups: > > def psort_xx(s1, s2): > pairs = sorted(dict(zip(s2, s1)).iteritems()) > assert len(pairs) == len(s1) > s1[:] = [s1_value for s2_value, s1_value in pairs] This version takes twice as long on my system, although the result may vary on other platforms. Dictionary lookups are very fast. Although replacing zip with izip cut the time in half. def psort11(s1, s2): d = dict(izip(s2,s1)) assert len(d) == len(s1) s1[:] = list(d[v] for v in sorted(d)) Ron From max at alcyone.com Sat Feb 4 17:23:11 2006 From: max at alcyone.com (Erik Max Francis) Date: Sat, 04 Feb 2006 14:23:11 -0800 Subject: A problem with some OO code. In-Reply-To: <1139075482.510942.71640@z14g2000cwz.googlegroups.com> References: <1139055710.688193.81000@z14g2000cwz.googlegroups.com> <1139075482.510942.71640@z14g2000cwz.googlegroups.com> Message-ID: <9LSdnb2RLcHNtHjeRVn-pw@speakeasy.net> TPJ wrote: > I understand your POV and I really appereciate your reply, but I doubt > that I could simplify my code to make it small *enough* to fit in one > post and not look too long. The pont of the exercise of taking non-working code and trying to cut away parts that aren't part of the problem is to isolate where the problem is. This is especially true in dynamic languages like Python, where problems usually consist of something not being what you expected it to be, but it's true in all other languages as well. Even if it means creating a standalone program that's a simplified version of the particular logic that's failing, this is good. It makes it easy for others to find where the problem is without having to tangle through your other (working) code. But in my view this is only the side benefit. The _real_ benefit is that a very significant fraction of the time, going through this exercise will actually help _you_ figure out your problem on your own. Taking a tangle of code that isn't working for reasons you don't understand and then pulling out threads to see where the problem is so you can show it to someone else to get help will usually allow _you_ to see where the problem was in the process. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis God said: "Let Newton be"; and all was light. -- Alexander Pope From darthbob88 at gmail.com Wed Feb 22 22:31:12 2006 From: darthbob88 at gmail.com (darthbob88 at gmail.com) Date: 22 Feb 2006 19:31:12 -0800 Subject: "Temporary" Variable Message-ID: <1140665472.203495.7570@g44g2000cwa.googlegroups.com> Problem: I wish to run an infinite loop and initialize a variable on each iteration. Sort of like, "Enter Data", test it, "No good!", "Next Try?", test it, etc. What I've tried is simply while 1: var1 = raw_input, test var1, then run through the loop again. What results is var1 gets and keeps the first value it receives. If this is in the FAQ, my apologies, I did not find it. Thank you in advance. From sriramk at gmail.com Sun Feb 19 15:43:51 2006 From: sriramk at gmail.com (Sriram Krishnan) Date: Mon, 20 Feb 2006 02:13:51 +0530 Subject: editor for Python on Linux In-Reply-To: References: Message-ID: <43F8D887.1020602@gmail.com> Mladen Adamovic wrote: > Hi! > > I wonder which editor or IDE you can recommend me for writing Python > programs. I tried with jEdit but it isn't perfect. > Check out http://wiki.python.org/moin/PythonEditors. I personally use Emacs -- Sriram From davidworley at gmail.com Mon Feb 6 00:32:59 2006 From: davidworley at gmail.com (Dave) Date: 5 Feb 2006 21:32:59 -0800 Subject: translating PHP to Python In-Reply-To: <1139164228.608430.13120@g44g2000cwa.googlegroups.com> References: <1139164228.608430.13120@g44g2000cwa.googlegroups.com> Message-ID: <1139203979.623011.290430@f14g2000cwb.googlegroups.com> So thanks, all for the help. Turns out that the solution is simple enough, as are most solutions in Python: PHP: parent::__construct(args) does translate to the Python: super(ParentClass, self).__init__(args) The example, that of referencing an object's creator object (if that's the technospecificalist terminosity) has to be done by passing a reference to the creator object to the created object. So: class A(object): def create_child(self): self.child = B() self.child.do_stuff(self) class B(object): def do_stuff(self, parent): self.parent = parent if self.parent.__class__.__name__ == 'A': print "I'm a child of an A!" else: print "Well, I'm a motherless child. Does that mean I can kill Macbeth?" (Bonus points for lame, contrived, and sort of offensive Shakespeare reference) The project I'm working on is a CSS preprocessor. Watch this space. It's totally going to be famous. From aleaxit at yahoo.com Sun Feb 12 22:02:39 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 12 Feb 2006 19:02:39 -0800 Subject: Downloading Large Files -- Feedback? References: <1139773494.245577.102870@g47g2000cwa.googlegroups.com> <1hanf3e.1j28qll1hnvr5qN%aleaxit@yahoo.com> <1139793676.885331.295390@g14g2000cwa.googlegroups.com> <1hanqts.1ebz9k41w8qll3N%aleaxit@yahoo.com> <1139798543.353098.280610@g44g2000cwa.googlegroups.com> Message-ID: <1hanu4z.1os501a32vyqfN%aleaxit@yahoo.com> mwt wrote: ... > import urllib > > def download_file(filename, URL): > f = urllib.urlretrieve(URL, filename, reporthook=my_report_hook) If you wanted to DO anything with the results, you'd probably want to assign to f, m = ... not just f. This way, f is the filename, m a message object useful for metadata (e.g., content type). Otherwise looks fine. Alex From nogradi at gmail.com Fri Feb 10 06:20:59 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 10 Feb 2006 12:20:59 +0100 Subject: pythonic exec* spawn* In-Reply-To: References: Message-ID: <5f56302b0602100320l177dbe8ep184dbe2c6a17fc6a@mail.gmail.com> > >> os.fork() does that (on Mac and Unix). > > > >Okay, but how? > > Sorry, fork() is implemented strictly on a 'need to know' basis :-) > > >It seems to me that if the process which issued os.fork() ends, then > >the forked process also ends. > > No, no, they're not a quantum mechanic photon pair. Every process decides > for itself if and when to end. As long as it's not signalled/killed, that > is. > > >But the execute of longer( data ) should keep going even though the > >original program ended. I'm pretty sure it's something basic and > >probably I'm not aware of the right concepts and that's why I can't > >find the right place to look in the docs. > > You can search for "daemonize". > > Here's a recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 > > The concept is best explained in this book: > http://www.kohala.com/start/apue.html Okay, thanks a lot, I'll look into that. From bpeng at rice.edu Fri Feb 24 19:16:38 2006 From: bpeng at rice.edu (Bo Peng) Date: Fri, 24 Feb 2006 18:16:38 -0600 Subject: Module written in C does not repond to Ctrl-C interruption. In-Reply-To: References: <468qvoF9r91vU1@uni-berlin.de> Message-ID: Daniel Dittmar wrote: > > You could set up your own signal handler when entering the C extension. > This should abort the extension (tricky) and call the Python signal > handler. This can be done under linux using things in signal.h but I am not sure whether or not there is a portable way to do it (max, win32). Does anybody know a quick way under windows? Bo From heikki at osafoundation.org Tue Feb 21 14:10:01 2006 From: heikki at osafoundation.org (Heikki Toivonen) Date: Tue, 21 Feb 2006 11:10:01 -0800 Subject: RSA in python In-Reply-To: <4e4a257e0602172240p2f4000eif2e34984850313e4@mail.gmail.com> References: <4e4a257e0602172240p2f4000eif2e34984850313e4@mail.gmail.com> Message-ID: <43FB6589.9000907@osafoundation.org> Abhisek Datta wrote: > -----BEGIN RSA PUBLIC KEY----- > MIGJAoGBALxi3tGXlSwRgn7/Km6mTSge+5ijQgIn3GvnZOeYyOo1DkubVtTaFj26 > GWtJo43MEe1a5UlWKJEOpbKVCr4AASfFj8YmmRewH4SXdZ+w1Bad8amyzL2h8F7J > wJojOnocSs6xDE7o86CpZRUlojBefanMdCpu074QFktE63OD1zBBAgMBAAE= > -----END RSA PUBLIC KEY----- > > Traceback (most recent call last): [...] > M2Crypto.RSA.RSAError: no start line The files in M2Crypto tests directory don't have any files that have "BEGIN RSA PUBLIC KEY" in them - haven't checked if this is legal or not. However, plain OpenSSL does not like that file either: $ openssl rsa -in rsa_heikki.pem -pubin 3440:error:0906D06C:PEM routines:PEM_read_bio:no startline:pem_lib.c:644:Expecting: PUBLIC KEY $ openssl rsa -in rsa_heikki.pem -check 2140:error:0906D06C:PEM routines:PEM_read_bio:no startline:pem_lib.c:644:Expecting: ANY PRIVATE KEY If I take out the "RSA " part from the delimiter lines I get: $ openssl rsa -in rsa_heikki2.pem -pubin unable to load Public Key 3124:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c: 1282: 3124:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:ta sn_dec.c:374:Type=X509_ALGOR 3124:error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 e rror:tasn_dec.c:743:Field=algor, Type=X509_PUBKEY 3124:error:0906700D:PEM routines:PEM_ASN1_read_bio:ASN1 lib:pem_oth.c:83: $ openssl rsa -in rsa_heikki2.pem -check unable to load Private Key 2304:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:644:Expect ing: ANY PRIVATE KEY My suggestion would be to ask on the openssl-users list. -- Heikki Toivonen -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 257 bytes Desc: OpenPGP digital signature URL: From tjreedy at udel.edu Tue Feb 21 11:48:05 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 21 Feb 2006 11:48:05 -0500 Subject: Augmented assignment References: <1140506094.387829.60890@g14g2000cwa.googlegroups.com> Message-ID: wrote in message news:1140506094.387829.60890 at g14g2000cwa.googlegroups.com... > > Terry Reedy wrote: >> Program performance might be noticeable if 'x' is something like a.b.c.d >> that takes some lookup time. But again, I would use the += form for >> readability without testing run time. > > Would x=x + 1 be more readable, regardless of the background(whether > being introduced to the += form in some other language like C before) ? To *me*, able.baker.charles.delta += 1 is more easily read than able.baker.charles.delta = able.baker.charles.delta +1 because it is clear that there is one and only one attribute involved, being updated in place, whereas the latter might have been able.baker.charles.delta = able.baker.charley.delta +1 Therefore, as I said originally *I* would use the += form. Terry Jan Reedy From peter at engcorp.com Sun Feb 19 08:13:28 2006 From: peter at engcorp.com (Peter Hansen) Date: Sun, 19 Feb 2006 08:13:28 -0500 Subject: commenting out blocks of code In-Reply-To: References: <20060217231846.87613.qmail@web36708.mail.mud.yahoo.com> Message-ID: Steve Holden wrote: > Steven D'Aprano wrote: >>On Fri, 17 Feb 2006 19:12:01 -0500, Peter Hansen wrote: >>>Scite, for example, lets me selected a block and hit Ctrl-Q to either >>>comment or uncomment the block. >>>(It does this by prefixing each line >>>with #~ instead of just #, which allows it to detect when a line is >>>already so commented and reverse the operation.) >> >>It is *easy* to detect when a line is already commented. It starts with a >>#. The ~ is superfluous. >> >>Commenting and uncommenting should be two different commands: the whole >>point of nested comments is that it allows you to comment a block of text >>which may already contain comments. Having one command do both commenting >>and uncommenting according to the presence or absence of semantic clues in >>the text is a recipe for failure ("No you stupid computer, I want to >>COMMENT that block, not uncomment it!!!"). >> >>Imagine if your text editor used cntl-C for both copy and paste, somehow >>guessing whether you wanted to copy selected text or paste over it >>according to some subtle clue in the text itself. Wouldn't that be fun? > > I agree that's a less-than-sensible feature implementation. I submit that Steve and Steven (neither of whom has apparently even *used* this feature of Scite before criticizing it so strongly), should consider whether in actual practice something like this might not be much more effective than they can apparently imagine. I'm strongly critical of many features of most editors, and thus use very few of them, and I also happen to have a solid background in GUI design and ergonomics. I'm also a heavy user of Scite, and have found it readily accepted amongst the groups of programmers with whom I've worked. I and my team have found the Ctrl+Q feature of Scite to be very sensible, highly effective and useful, and in fact *better* than alternatives that we've used before in other editors. Kudos to Neil for having the (apparently) unusual design sense to think of it and implement it! So there. Harumph. :-) -Peter From k.suess at gmx.net Tue Feb 21 05:54:50 2006 From: k.suess at gmx.net (Katja Suess) Date: Tue, 21 Feb 2006 11:54:50 +0100 Subject: odt -> pdf Message-ID: <43FAF17A.70706@gmx.net> Hi Cause Google didn't find the Info I was trying to find her my post. Is PyUNO still _the_ Tool to create PDFs out of OpenOffice docs (odt, not swx) ? Do other tools exist? Do you prefer generatingp PDFs using the XML-Strukture of odt files? Regards, Katja From carsten at uniqsys.com Thu Feb 9 08:36:38 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 09 Feb 2006 08:36:38 -0500 Subject: email questions In-Reply-To: <12llu1ti1o7s7q477apo7idqod1e0qd4dr@4ax.com> References: <1139420846.28143.41.camel@dot.uniqsys.com> <12llu1ti1o7s7q477apo7idqod1e0qd4dr@4ax.com> Message-ID: <1139492198.31416.13.camel@dot.uniqsys.com> On Thu, 2006-02-09 at 00:50, Dennis Lee Bieber wrote: > On Wed, 8 Feb 2006 10:49:27 -0800, Scott Frankel > declaimed the following in comp.lang.python: > > > > > > mail..net > > Not sure why you feel you need to hide it -- I'm presuming it is the > same ISP in your email address... > > However, I'm currently finding a dead access to it... > > C:\Documents and Settings\Dennis Lee Bieber>tracert smtp.pacbell.net > Unable to resolve target system name smtp.pacbell.net. > > C:\Documents and Settings\Dennis Lee Bieber>tracert mail.pacbell.net > > Tracing route to mail.pacbell.net [207.115.57.20] > over a maximum of 30 hops: > > 1 1 ms <1 ms <1 ms 192.168.1.1 > 2 17 ms 13 ms 14 ms user-11fa401.dsl.mindspring.com > [66.245.16.1] > 3 13 ms 13 ms 15 ms cor02-vl-10.ca-sanfranc0.ne.earthlink.net > [209.165.103.65] > 4 16 ms 13 ms 16 ms > bor01-ge-6-1.ca-sanfranc0.ne.earthlink.net [209.165.103.17] > 5 22 ms 22 ms 22 ms > bor02-so-3-1.ca-pasadena0.ne.earthlink.net [209.165.109.154] > 6 23 ms 27 ms 31 ms > bor01-ge-1-1-0.ca-losangel4.ne.earthlink.net [209.165.107.182] > 7 28 ms 21 ms 22 ms ex1-g8-1s1.eqlaca.sbcglobal.net > [206.223.123.79] > 8 24 ms 22 ms 23 ms ex2-p3-0.eqlaca.sbcglobal.net > [151.164.191.226] > 9 25 ms 24 ms 24 ms bb1-p6-0.crrvca.sbcglobal.net > [151.164.41.34] > 10 23 ms 24 ms 27 ms core2-p4-0.crrvca.sbcglobal.net > [151.164.41.1] > 11 58 ms 61 ms 59 ms core2-p3-0.crhstx.sbcglobal.net > [151.164.241.125] > 12 88 ms 89 ms 81 ms core1-p9-0.cratga.sbcglobal.net > [151.164.191.192] > 13 83 ms 82 ms 84 ms core2-p1-0.cratga.sbcglobal.net > [151.164.241.82] > 14 82 ms 82 ms 83 ms core2-p6-0.crhnva.sbcglobal.net > [151.164.41.206] > 15 88 ms 89 ms 90 ms core2-p3-0.crnyny.sbcglobal.net > [151.164.188.197] > 16 91 ms 88 ms 89 ms bb2-p3-0.nycmny.sbcglobal.net > [151.164.240.221] > 17 88 ms 90 ms 87 ms ded2-g8-3-0.nycmny.sbcglobal.net > [151.164.41.181] > 18 93 ms 90 ms 98 ms 66.10.112.6 > 19 * * * Request timed out. > 20 * * * Request timed out. > 21 * * * Request timed out. > 22 * * * Request timed out. > 23 * * * Request timed out. This does not necessarily mean that the server is down. Routers can filter traceroute and ping. Telnet to mail.pacbell.net on port 25 works just fine. If the server had been down, the OP would not have gotten "connection refused", he would have gotten a connection timeout. The OP's problem is most likely that he's doing this: s = smtplib.SMTP("mail.pacbell.net") # This already connects s s.connect() # This reconnects s to localhost and is refused when he should do this: s = smtplib.SMTP() # make an unconnected SMTP instance s.connect("mail.pacbell.net") # and connect it. or simply this: s = smtplib.SMTP("mail.pacbell.net") -Carsten From steve at REMOVETHIScyber.com.au Sun Feb 19 03:00:51 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 19 Feb 2006 19:00:51 +1100 Subject: Python vs. Lisp -- please explain References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> Message-ID: On Sat, 18 Feb 2006 23:35:27 -0600, DH wrote: > > I'm wondering if someone can explain to me please what it is about > > Python that is so different from Lisp that it can't be compiled into > > something as fast as compiled Lisp? From this above website and > > others, I've learned that compiled Lisp can be nearly as fast as > > C/C++, so I don't understand why Python can't also eventually be as > > efficient? Is there some *specific* basic reason it's tough? Or is it > > that this type of problem in general is tough, and Lisp has 40+ years > > vs Python's ~15 years? > > It is by design. You make it sound like Guido sat down to design a language and deliberately put "Slow" first on his list of desired attributes. Why such a negative tone to your post? Python is not slow by design. Python is dynamically typed by design, and relative slowness is the trade-off that has to be made to give dynamic types. The Python developers have also done marvels at speeding up Python since the early days, with the ultimate aim of the PyPy project to make Python as fast as C, if not faster. In the meantime, the question people should be asking isn't "Is Python fast?" but "Is Python fast enough?". > Python is dynamically typed. It is essentially an > interpreted scripting language like javascript or ruby or perl, although > python fans will be quick to tell you python is compiled to byte code. You make it sound like Python fans are bending the truth. That Python compiles to byte-code is an objective fact which can be learnt by anyone, not just "Python fans". In that regard, Python is closer to Java than Perl or Javascript. Only without the slow startup time of the JRE. > They'll also be quick to tell you: > -python has true closures (although nothing like ruby's blocks) They're also nothing like Pascal's with statements either. Why make the comparison with Ruby's blocks when the original poster is comparing Python to Lisp? > -is beginner friendly (despite being case sensitive and 3/4==0, for > example) Case sensitivity isn't beginner unfriendly. It is sloppy thinker unfriendly. Whether you have been programming for thirty days or thirty years, if you don't know the difference between foo and FOO you have a serious problem. As they say, case is the difference between "I helped my Uncle Jack off a horse" and "I helped my uncle jack off a horse." As for the difference between integer division and true division, yes, that was an unfortunate design decision. Fortunately it is being rectified in the least painful way possible. > -is not, in fact, slow at all (despite benchmarks as you noted showing > otherwise). I've asked this question before, but obviously there is a particular mindset that just doesn't get it. Slow compared to what? Slow to do what? For those who don't understand the difference between "faster" and "fast enough", perhaps a simple analogy will bring enlightenment. For most people, under most circumstances, an ordinary car (top speed around 75 mph or so) is fast enough, more convenient, and much better value for money than the significantly faster F-15 fighter plane (top speed around 1850 mph). On modern hardware, for the vast majority of applications, the execution speed of the language is not the limiting factor. I/O or the algorithm is usually the limiting factor. "Change your algorithm" is often better advice than "change your language". That's not to say that Python isn't objectively SLOWER (note the relative term, not absolute) than some languages. But execution speed is rarely the most important factor in choice of a language. For those tasks that language speed is a limiting factor (say, writing devise drivers, operating systems, and similar), Python may not be fast enough. But they are the exception rather than the rule, and there are no shortage of ways around that: Psycho, C extensions, or even "choose another language". -- Steven. From lcrees at gmail.com Wed Feb 8 12:17:13 2006 From: lcrees at gmail.com (L.C. Rees) Date: 8 Feb 2006 09:17:13 -0800 Subject: Mixing custom __setattr__ method and properties in new style classes In-Reply-To: <1139418477.572639.154300@z14g2000cwz.googlegroups.com> References: <1139418477.572639.154300@z14g2000cwz.googlegroups.com> Message-ID: <1139419033.608688.147710@g14g2000cwa.googlegroups.com> I see the error: the get and set properties are inverted. Now it works. From gaz082 at gmail.com Thu Feb 16 10:36:18 2006 From: gaz082 at gmail.com (Gaz) Date: 16 Feb 2006 07:36:18 -0800 Subject: Sendmail "ok" signal? Message-ID: <1140104177.989381.292550@z14g2000cwz.googlegroups.com> Hey. I looked at the Sendmail help and did not find a property where i can get an "ok" signal when the email is finally sent. I need something like that to show a "Processing, please stand by" screen when the server is sending an email, and when the email is out, another screen appears with an "Email sent" message. Do you know an alternative to the "ok" from the sendmail to do this? From nibiery at hotmail.com Mon Feb 20 19:28:28 2006 From: nibiery at hotmail.com (Ingrid) Date: 20 Feb 2006 16:28:28 -0800 Subject: getting started, .py file In-Reply-To: <1140476484.581881.230170@o13g2000cwo.googlegroups.com> References: <1140471172.783876.80400@g14g2000cwa.googlegroups.com> <1140476484.581881.230170@o13g2000cwo.googlegroups.com> Message-ID: <1140481708.344495.198340@g43g2000cwa.googlegroups.com> I found it! I needed to set sys.path ("sys.path.append("c:\\documents and settings\\my documents\\ingrid")") Ingrid From bronger at physik.rwth-aachen.de Mon Feb 20 08:30:26 2006 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 20 Feb 2006 14:30:26 +0100 Subject: Python vs. Lisp -- please explain References: <1140324074.458446.227480@z14g2000cwz.googlegroups.com> <43f8ba1e$0$2895$626a54ce@news.free.fr> <43f8cb3f$0$4225$626a54ce@news.free.fr> <87bqx3glb1.fsf@wilson.homeunix.com> <43f984dc$0$27151$626a54ce@news.free.fr> <873bienwlx.fsf@wilson.homeunix.com> Message-ID: <878xs6b1jh.fsf@wilson.homeunix.com> Hall?chen! Carl Friedrich Bolz writes: > Torsten Bronger wrote: > >> [...] >> >> My definiton would be that an interpreted language has in its >> typical implementation an interpreting layer necessary for >> typical hardware. Of couse, now we could discuss what is >> "typical", however, in practice one would know it, I think. In >> case of Python: CPython and all important modern processors. > > Well, if we take any modern Intel/AMD chip (which could be > described as "typical), a C++ program would fit the "interpreted" > definition, since the processor does not execute the machine code > directly but rather breaks it down into smaller microcode > instruction -- a process that could be described as intepretation. This is an interpreting layer within the hardware, not necessary for it. > Another problem with the definition: what would you call a C++ > program that is running on top of an emulator? Compiled. I said "necessary for typical hardware". > [...] I think that the disctinction between "interpreted" and > "compiled" (whatever both means) is really just not sensible at > all. The question is whether such features have to be considered when choosing the right tool for a task. I think, yes. Whereas C is very close to the fastest code you can get because it works very closely to how the machine itself works, Python can well be one or one and a half orders of magnitude farther away. No problem since you can get the best of both worlds but: You must be aware of it. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus ICQ 264-296-646 From NethanO at SPdogdiniAM.com Fri Feb 17 13:25:22 2006 From: NethanO at SPdogdiniAM.com (EShames) Date: Fri, 17 Feb 2006 18:25:22 GMT Subject: Print a PDF transparently In-Reply-To: <1140184955.674138.275010@o13g2000cwo.googlegroups.com> References: <1140184955.674138.275010@o13g2000cwo.googlegroups.com> Message-ID: On 2/17/2006 9:02 AM, Daniel Crespo wrote: > Hi to all, > > I want to print a PDF right from my python app transparently. With > "transparently" I mean that no matter what program handles the print > petition, the user shouldn't be noticed about it. > > For example, when I want to print a PDF, Adobe Acrobat fires and keep > opened. This is what I don't want to happen (and I thing there are a > lot of people who want this too). So I just want to send the PDF to > the right handler and print it. That's all. > > I've seen some things like Adobe's Postscript driver that can read a > PDF, or Ghostscript, but I still don't know how to use it. > > Any help for printing a PDF transparently? > > Thank you > > Daniel > You may find that RedMonEE is a useful piece to your puzzle. I find it to be stable and quite invaluable. http://www.is-foehr.de/ > RedMon - Redirection Port Monitor EE > > Transparent PostScript printing from Windows NT, W2K and XP. Overview > > > The RedMon EE port monitor redirects a special printer port to a > program. RedMon EE is commonly used with Ghostscript and a > non-PostScript printer to emulate a PostScript printer. > > RedMon EE can be used with any program that accepts data on standard > input. > > Using RedMon EE you create a redirected printer port. If you connect > a Windows printer driver to the redirected printer port, all data > sent to the redirected port will be forwarded by RedMon to the > standard input of a program. The output of this program can be sent > to different printer port, or the program can generate whatever > output it desires. > > A PostScript Windows printer redirected to a RedMon port can shared > on a network. When this printer is configured to use Ghostscript and > a non-PostScript printer, it appears as a PostScript printer to other > network clients. From carsten at uniqsys.com Wed Feb 15 15:16:53 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 15 Feb 2006 15:16:53 -0500 Subject: Linux application in python In-Reply-To: <1140032096.691138.286750@z14g2000cwz.googlegroups.com> References: <1140032096.691138.286750@z14g2000cwz.googlegroups.com> Message-ID: <1140034613.22048.102.camel@dot.uniqsys.com> On Wed, 2006-02-15 at 15:02, sundarashiv at gmail.com wrote: > Hi all , > > I have a linux application that needs to run on a python interpreter Why does it "need to" run "on" a python interpreter? > .So what is the best way to have the same functionalities provided by > "C" to be implemented in python . 1) Rewrite the functionality in python. 2) Separate the functionality into a library and write a python extension to call into the library (or use ctypes to call into the library without writing an extension module) Better solutions may become apparent once you provide more details about your needs. -Carsten From bearophileHUGS at lycos.com Tue Feb 28 06:00:20 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 28 Feb 2006 03:00:20 -0800 Subject: sort one list using the values from another list In-Reply-To: <4403b3c3_2@newspeer2.tds.net> References: <4401d314_2@newspeer2.tds.net> <4403b3c3_2@newspeer2.tds.net> Message-ID: <1141124420.079243.41470@i39g2000cwa.googlegroups.com> >_ is just a plain variable name in Python. It is sometimes when a variable is needed to receive a value that won't be used.< Like in some other interactive systems (Mathematica, etc, but with a different syntax) _ has a use in the interactive shell, it contains the last unassigned result: >>> a = 2 * 5 >>> _ Traceback (most recent call last): File "", line 1, in ? NameError: name '_' is not defined >>> 2 * 5 10 >>> _ 10 Bye, bearophile From s323 at mail.ru Tue Feb 14 06:29:44 2006 From: s323 at mail.ru (Sergey) Date: Tue, 14 Feb 2006 14:29:44 +0300 Subject: file names longer than MAX_PATH under Windows 2003 Message-ID: Hello. I try to open file with pathname length 282 bytes: E:\files\..................\something.dat On MSDN (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/naming_a_file.asp) described method to access files with path length up to 32000 bytes: just add prefix \\?\ to file name. But when I try to pass prefixed name to file(), I get the same result as when I don't add the prefix: file not found. May be Python just doesn't support long unicode filenames? Is there way to open such files? From fredrik at pythonware.com Sun Feb 12 11:30:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Feb 2006 17:30:35 +0100 Subject: Can I get the 8bit-string representation of any unicode string References: <1139757073.364694.176200@g14g2000cwa.googlegroups.com> <1139760950.777963.245250@g47g2000cwa.googlegroups.com> Message-ID: wanghz at gmail.com wrote > I may misunderstood it. I will think about it carefully. > > By the way, does python has a interface, just like iconv in libc for > C/C++? Or, how can I convert a string from a encoding into another > one? if b is an 8-bit string containing an encoded unicode string, u = b.decode(encoding) or u = unicode(b, encoding) gives you a unicode string. to encode the unicode string back to another byte string, use the encode method. b = u.encode(encoding) From kay.schluehr at gmx.net Fri Feb 24 11:56:31 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 24 Feb 2006 08:56:31 -0800 Subject: Unintended inheritance In-Reply-To: <1hb23fp.icnshja9l7hhN%aleaxit@yahoo.com> References: <1140461082.972776.28090@g14g2000cwa.googlegroups.com> <1hb23fp.icnshja9l7hhN%aleaxit@yahoo.com> Message-ID: <1140800191.347266.296770@j33g2000cwa.googlegroups.com> Alex Martelli wrote: > Kay Schluehr wrote: > ... > > To prevent unintended inheritance C# introduced a relatively complex > > contract semantics using three modifiers virtual, override and new. Is > > this issue serious for Python programmers, in particular for those > > working in larger projects ( Twisted, Zope ... ) or is it not? If not, > > why not? > > I have not found it to be a particular problem (in C++ as well as in > Python or Java), because subclasses' coupling to superclasses is too > strong anyway to expect everything to just work smoothly when the > superclass's interface is changed, and even the most semidecent of > unittests easily catch this specific problem -- obviously all subclasses > must be recompiled and tested when a superclass's interface is changed > in any way. Other kinds of coupling are subtler and more problematic > (not so much in Python as in C++, I'd say, but it's arguable). > > Lakos' book on large-scale design for C++ has good advice on dependency > control, which boils down to (WAY oversimplifying): each component must > expose to all others only unchanging abstract interfaces; anything > depending on anything beyond an abstract interface (as a subclass must) > must be in the same component as what it depends on. Inheritance, while > way handy, introduces too-strong coupling (==dependencies) to be freely > used across independently developed and maintained components; and any > change in interface (I would argue, in fact, most any change in > PROTOCOL, which is a stronger constraint) must occur on new, separate > interfaces (which may well extend the existing ones, of course). > > Yes, frameworks (separately developed, large components which are > *supposed* to be used via inheritance by separately developed and > maintained components) are quite problematic in terms of Lakos' rules > and guidelines (if you're at all interested in these subjects you should > surely read Lakos' book, anyway: no summary can do it justice). But I > believe (with no real-world experience of C#, admittedly) that they will > remain essentially just as problematic with C#'s complex rules -- a new > release of a framework, which changes protocols, will still be able to > break uncountable independently developed and maintained smaller > components, and the fact that the compiler catches the breakage (if, of > course, the other components DO get recompiled) rather than relying on > semidecent unittests is scant consolation -- there's still no bound to > the amount of work that may be needed to repair the wreckage. > > > Alex Interesting statement, Alex, as always. I've found an interview with Anders Hejlsberg from 2003 on Artima where he defended his C# design decisions with regard to the problem of "unintended inheritance": http://www.artima.com/intv/nonvirtual.html A strange twist is Anders exemplification of "pragmatism" with which Bruce Eckel seems to agree emphatically. I would indeed assume the exact opposite: laisser faire by pragmatists and expressive control by academics. I'm also not sure what I should think about the confusing use of the word "versioning" that is placed concretely by Bruce Eckel ( "DLL hell" ) but more metaphorically by Anders. His remarks about the difference of ingoing and outgoing interfaces are interesting but remain a little underdeveloped. Kay From steve at holdenweb.com Tue Feb 7 07:16:28 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 07 Feb 2006 07:16:28 -0500 Subject: python In-Reply-To: <1139310431.908915.299400@g43g2000cwa.googlegroups.com> References: <20060206222757.3277.qmail@web25701.mail.ukl.yahoo.com> <1139310431.908915.299400@g43g2000cwa.googlegroups.com> Message-ID: Salvatore wrote: > A new OS in Python : > http://unununium.org/introduction :-) > That page includes: """ Is the project dead? Maybe. Very little code was written in 2005. 2006 so far does not look better. What code has been written isn't very useful. ... """ regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From felipe.lessa at gmail.com Sat Feb 11 15:14:02 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sat, 11 Feb 2006 18:14:02 -0200 Subject: Clearing the screen In-Reply-To: <1139688262.046667.296940@g14g2000cwa.googlegroups.com> References: <1139688262.046667.296940@g14g2000cwa.googlegroups.com> Message-ID: <1139688842.9328.13.camel@kenshin> Em S?b, 2006-02-11 ?s 12:04 -0800, mwt escreveu: > I'm doing some python programming for a linux terminal (just learning). > When I want to completely redraw the screen, I've been using > os.system("clear") > This command works when using python in terminal mode, and in IDLE. > However, when running a little .py file containing that command, the > screen doesn't clear. > > What to do? There's one escape sequence that does what you want. I am *not* sure if this solution is the correct one, but: $ clear | hd 00000000 1b 5b 48 1b 5b 32 4a |.[H.[2J| 00000007 $ python Python 2.3.5 (#2, Nov 20 2005, 16:40:39) [GCC 4.0.3 20051111 (prerelease) (Debian 4.0.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print chr(0x1b)+chr(0x5b)+chr(0x48)+chr(0x1b)+chr(0x5b)+chr(0x32)+chr(0x4a), >>> # Clears the screen! -- "Quem excele em empregar a for?a militar subjulga os ex?rcitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destr?i os estados dos outros povos sem lutas prolongadas. Deve lutar sob o C?u com o prop?sito primordial da 'preserva??o'. Desse modo suas armas n?o se embotar?o, e os ganhos poder?o ser preservados. Essa ? a estrat?gia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" From n.estner at gmx.de Thu Feb 2 19:32:21 2006 From: n.estner at gmx.de (n.estner at gmx.de) Date: 2 Feb 2006 16:32:21 -0800 Subject: Another try at Python's selfishness References: <1138918102.863033.298700@o13g2000cwo.googlegroups.com> Message-ID: <1138926741.052843.169270@z14g2000cwz.googlegroups.com> > write(sys.stdin, split(read(open(file, 'r')))[0]) So, if I got you right, the interpreter would have to interpret this line like this: 1. Evaluate the first parameter of the first function (sys.stdin) 2. Look up the attribute "write" in this object 3. evaluate the first parameter of the split function -> 4. evaluate the first parameter of the read function -> 5. evaluate file (I guess this is a local string variable?) 6. try attribute lookup "open" on the string 7. fail -> call the global "open" function 8. lookup "read" in that object, call it 9. attribute lookup "split" on the returned object 10. call __getitem__(0) 11. pass the parameters to the write function from (1) Is this correct? My main problems are that you have to "guess" at step 6/7, and that the order of evaluation makes me a little dizzy ;-) Also, member functions seem to "shadow" global ones, what if I wanted to use some global "split" function I've written myself instead of the string's one. If I was mean, I'd ask you what this one does: class A: def test(self, this): return 1 class B: def test(this, self): return 2 test(self=A(), this=B()) The current call syntax at least can be read from left-to-right, and you always know whether you call a member function or a global one. From tim.hochberg at ieee.org Sun Feb 19 18:28:12 2006 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Sun, 19 Feb 2006 16:28:12 -0700 Subject: number ranges (was Re: Matlab page on scipy wiki) In-Reply-To: References: <1139945386.3346.38.camel@pc1.cole.uklinux.net> <43F8D881.5030804@sympatico.ca> Message-ID: <43F8FF0C.50908@ieee.org> Colin J. Williams wrote: >> >>It would be good if the range and slice could be merged in some way, >>although the extended slice is rather complicated - I don't understand it. >> >> The semantics for an extended slicing are as follows. The primary >> must evaluate to a mapping object, and it is indexed with a key that >> is constructed from the slice list, as follows. If the slice list >> contains at least one comma, the key is a tuple containing the >> conversion of the slice items; otherwise, the conversion of the lone >> slice item is the key. The conversion of a slice item that is an >> expression is that expression. The conversion of an ellipsis slice >> item is the built-in |Ellipsis| object. The conversion of a proper >> slice is a slice object (see section section 4.2 The standard type >> hierarchy ) >> whose |start|, |stop| and |step| attributes are the values of the >> expressions given as lower bound, upper bound and stride, >> respectively, substituting |None| for missing expressions. >> >>[source: http://www.network-theory.co.uk/docs/pylang/ref_60.html] >> >>The seems to be a bit of a problem with slicing that needs sorting out. >> >>The syntax for a slice list appears to allow multiple slices in a list: >> >> extended_slicing ::= primary "[" >> slice_list "]" >> slice_list ::= slice_item ("," >> slice_item )* [","] >> >>but the current interpreter reports an error: >> >> >>> a= range(20) >> >>> a[slice(3, 9, 2)] >> [3, 5, 7] >> >>> a[slice(3, 9, 2), slice(5, 10)] >> Traceback (most recent call last): >> File "", line 1, in ? >> TypeError: list indices must be integers >> >>> >> Extended slicing has nothing to do with lists. All that gobbeldy gook is trying to tell you is what the interpreter does with O[1:2:3, 4:5:6] where O is some arbitrary object. What it does is: O[1:2:3, 4:5:6] == O[slice(1,2,3), slice(4,5,6)] == O.__getitem__((slice(1,2,3), slice(4,5,6))) In the case of python lists, __getitem__ doesn't support multiple slice arguments. However, you are free to define your own types which do support multiple slices. This type of slicing was added to support Numeric originally and as far as I know is still only really used in Numeric and its successors Numarray and Numpy. Since this was originally posted to the numpy list I assume you are familiar with multidimensional indexing of arrays -- that is extended slicing in action. If you really want to learn about it, and for most people it's unnecessary although perhaps entertaining, play with the following class: class ExtendedSlicingDemo(object): def __getitem__(self, key): return key esd = ExtendedSlicingDemo() print esd[1:2:3] print esd[1:2:3, 3:4:5] print esd[1:2:3, ..., 3:4:5] #.... => slice(1, 2, 3) (slice(1, 2, 3), slice(3, 4, 5)) (slice(1, 2, 3), Ellipsis, slice(3, 4, 5)) -tim From aleaxit at yahoo.com Mon Feb 20 12:12:39 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Feb 2006 09:12:39 -0800 Subject: Quesion about the proper use of __slots__ References: <1140424508.393412.79140@o13g2000cwo.googlegroups.com> <43f9825e$0$4777$636a55ce@news.free.fr> <1140426860.033363.237150@o13g2000cwo.googlegroups.com> Message-ID: <1hb1vq2.1ij7f8e1bx24u8N%aleaxit@yahoo.com> Zefria wrote: ... > this special case I'm expecting each "carrier" to have up to 150 > fighters, and 3 to 5 carriers for each of the two teams, which comes > out to be quite large. The problem with the spread of email is that it reduces the number of envelopes laying around, and thus makes it harder to do "back of the envelopes" calculations (the key skill in engineering...). With 10 carriers between the two teams, and 150 fighters/carrier, you're dealing with 1500 fighters. If you save 64 bytes per fighter (and I don't think __slots__ will save quite that much), we're still talking about less than 100,000 bytes -- peanuts. __slots__ is unwarranted. > Additionally, this program's purpose was to experiment with as many of > the special methods as possible, so I suppose I'm on track so far. __slots__ is not a method, so it falls outside that purpose as stated. Alex From tdelaney at avaya.com Tue Feb 21 18:05:00 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 22 Feb 2006 10:05:00 +1100 Subject: Python vs. Lisp -- please explain Message-ID: <2773CAC687FD5F4689F526998C7E4E5F4DB97A@au3010avexu1.global.avaya.com> Terry Reedy wrote: >>> The the compiler is built into the VM as opposed to a separate tool >>> (like Java) is just an implementation issue. That was me, not Paul - careful with the attributions. Otherwise Paul might think you were trying to ascribe some awful, inaccurate statement to him ;) > The presence of the exec statement and the eval function (which is > used by the input statement) requires the runtime presence of the > parser-compiler. Removing the latter disables the former features. > This is legitimite when not needed or when space is tight, but the > result is no longer a full implementation. True - but there's no reason that exec and eval couldn't hand off to a python compiler to do the work. Failure to distribute the compiler would mean then that exec and eval wouldn't work - but everything else would. It's similar to why some projects need the JDK rather than the JRE - they have to be able to compile things on the fly. Tim Delaney From feedme at foo.org Fri Feb 17 03:53:46 2006 From: feedme at foo.org (Wojciech Pawlikowski) Date: Fri, 17 Feb 2006 09:53:46 +0100 Subject: restricted mode (2.4.2) Message-ID: Hey, I work on some project where main part (core) is coded in C (for speed) and the rest is in Python. Python API is used to launch python modules without using any exec() system() calls (thread safe). During debugging I found that many of Python modules fails to work because restricted mode: Traceback (most recent call last): File "../modules/scan/dns_forward.py", line 167, in scan_element d = DNSForward(domainname) File "../modules/scan/dns_forward.py", line 20, in __init__ self.__r = dns.resolver.Resolver() File "/usr/lib/python2.4/site-packages/dns/resolver.py", line 270, in __init__ self.read_resolv_conf(filename) File "/usr/lib/python2.4/site-packages/dns/resolver.py", line 295, in read_resolv_conf f = open(f, 'r') IOError: file() constructor not accessible in restricted mode Is there any way to avoid this mode ? -- ___________________________________________________________________ * Wojciech Pawlikowski :: :: GG: 4155781 * * http://www.knockdownhc.com || http://www.kingofthehillhc.com * * "Loved by a few, Hated by many, But respected by ALL" * From max at alcyone.com Mon Feb 13 23:52:28 2006 From: max at alcyone.com (Erik Max Francis) Date: Mon, 13 Feb 2006 20:52:28 -0800 Subject: how do you pronounce 'tuple'? In-Reply-To: References: Message-ID: Roy Smith wrote: > Peter Maas wrote: >>Latin n-tuple >>--------------------------- >>... ... >>triplex triple >>duplex duple >>simplex simple > > Would a 9-tuple be a nipple? We don't talk about that anymore since the Incident. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Society attacks early when the individual is helpless. -- B.F. Skinner From iddw at hotmail.com Mon Feb 20 11:47:28 2006 From: iddw at hotmail.com (Dave Hansen) Date: Mon, 20 Feb 2006 10:47:28 -0600 Subject: Python 3000 deat !? Is true division ever coming ? References: <1139810036.943598.229030@g47g2000cwa.googlegroups.com> <1140213665.105188.103450@o13g2000cwo.googlegroups.com> Message-ID: Caution: bunny trail ahead. Feel free to skip this message, as it contains no useful content whatever... On Sat, 18 Feb 2006 12:09:02 +1100 in comp.lang.python, Steven D'Aprano wrote: [...] > >I've never even used Matlab. But I have a calculator. (Actually I have >about half a dozen calculators.) In every single one of them, 1/2 gives >0.5 instead of 0. I'm even capable of doing that calculation in my head. >So I don't think true division is only in Matlab. I have three calculators: an HP-48S, and HP-16C, and NeoCal on my Palm. On the HP-48S: 1 2 / -> 500.000000000E-3 On the HP-16C: 1 2 / -> 0 h (c) On NeoCal: 1 2 / -> 500.e-3 Note: the (c) on the 16C indicates the "carry" bit was set, which the 16C does whenever the remainder of a division is nonzero. Caveats: The result for each calculator depends on its "mode." In "programmer" mode, each calculator performs a truncating integer division. The 16C is in programmer mode by default. The 48S is almost never in programmer mode since I bought the 16C. NeoCal goes into programmer mode about 25% of the time I use it. It was in "Statistics" mode when I powered it up just now. > > >> As you pointed out: the "true division" part of "Python3000" might be >> one of the "scariest" and should therefore be pointed out already in >> the tutorial !! (It would look quite ugly to newcomers, though) If you want ugly, consider Pascal. The / operator could not perform an integer divide, and a compile-time error was generated if you attempted to use it with integer operands. The integer divide operator was 'div', e.g. "i = j div k" > >The tutorial shouldn't talk about Python3000 at all. What would be the >point of that? The tutorial is there to teach about the way Python works >now, not to make guesses and prediction about how it will work some time >in the indefinite future. > > >> Having said that: I would vote against EVER introducing true division >> as default - because it will just PISS too many (long time python) >> people OFF. ;-) > >Do you realise that the reason true division was introduced into Python >was because many long-time Python programmers requested it? So far from >annoying them, it is a feature that most Python programmers are waiting >for. I am a relatively long-time user (since about 1999) of Python, but I mainly program in C. "True" division probably wouldn't p*ss me off too bad, and I certainly wouldn't have a problem with new scripts I wrote. But if it broke old scripts, I wouldn't be extremely happy. FWIW, ISTM that "true" division would be better implemented by the new // operator, leaving the behavior of / unchanged. But that's probably just me. Regards, -=Dave -- Change is inevitable, progress is not. From xavier.morel at masklinn.net Fri Feb 3 08:29:53 2006 From: xavier.morel at masklinn.net (Xavier Morel) Date: Fri, 03 Feb 2006 14:29:53 +0100 Subject: classmethod and instance method In-Reply-To: <1138915844.118266.159770@g14g2000cwa.googlegroups.com> References: <1138910923.048674.264840@g49g2000cwa.googlegroups.com> <1138915844.118266.159770@g14g2000cwa.googlegroups.com> Message-ID: andychambers2002 at yahoo.co.uk wrote: > Yes that's better. Didn't know about the __class__ attribute. I > thought there must be a way to access this but couldn't find it in the > docs. > > Thanks, > > Andy > dir(), help() and the interactive interpreter (IDLE or CLI) are your best friends. Any time you wonder what an object does, or if you do something to an object, fire the interpreter, create your object, abuse it via dir/help/whatever, and then use dir/help/whatever on the results of dir'ing your object. Oh, and use new style classes too (explicitly inherit from `object` or a built-in type), they are much more flexible and interesting than old-style classes >>> class Test: # old style class pass >>> test = Test() >>> dir(test) # are completely uninteresting ['__doc__', '__module__'] >>> class Test(object): # new style classes on the other hand pass >>> test = Test() >>> dir(test) # have 2500% more sexyness ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] >>> From keith at nekotaku.com Tue Feb 28 22:03:32 2006 From: keith at nekotaku.com (Keith Burns) Date: Tue, 28 Feb 2006 20:03:32 -0700 Subject: MySQLdb compile error with AMD64 Message-ID: <20060301031016.868C31E4002@bag.python.org> >> Can anyone offer any assistance on this one? > >Look here: > >>> gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -fmessage-length=0 -Wall >>> -D_FORTIFY_SOURCE=2 -g -fPIC -I/usr/include/mysql >>> -I/usr/include/python2.4 -c _mysql.c -o >>> build/temp.linux-x86_64-2.4/_mysql.o -I/usr/include/mysql -g >>> -march=i586 -mcpu=i686 -fmessage-length=0 > >specifically at -march=i586. MySQLdb sets CFLAGS which aren't applicable to >your processor, and as such the compile barfs. You should probably just run >it with something like > >CFLAGS="-march=athlon-64" python setup.py build > >I am positive that MySQLdb works on AMD64, I have it running there. Anyway, >the CFLAGS fix should work. Hey there! Appreciate the help but the CFLAGS did not change the gcc -march (I tried it as above and with CFLAGS="-march=athlon64" which I found in a GCC flag FAQ). I realize that the -march is my problem but I can't work out how to change it. Any ideas? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Feb 9 17:09:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 9 Feb 2006 23:09:45 +0100 Subject: jump into the interpreter in a script References: <43EA7A62.2090904@bryant.edu> Message-ID: Carl Friedrich Bolz wrote: > Yes. The "code" module of the stdlib is what you want. put > > import code > code.interact(local=locals()) > > into a point where you would like to have an interpreter prompt. or, as a reusable function: http://effbot.org/librarybook/code.htm (see the third example on that page) From deets at nospam.web.de Tue Feb 21 13:04:35 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 21 Feb 2006 19:04:35 +0100 Subject: Video Capture modules in linux References: <1140536025.234765.309040@z14g2000cwz.googlegroups.com> <1140537926.084128.66160@g44g2000cwa.googlegroups.com> Message-ID: <46134sF8rjpdU1@uni-berlin.de> sudharsh at gmail.com wrote: > well wht can i say it simply refuses to compile...i m getting make > errors. i think the culprit is the gcc-4.0..secondly i havent had a > chance to really try it out..aneways does libfg manipulate inputs from > webcams..like VideoCapture modules ..also i think libfg is mainly for C > although a module for python exists..forgive me i m a real newbie.. So it's far from not being useful. And a pure python video capture lib is unlikely to happen - for various reasons, not the least being that there are plenty of data to shuffle around in video grabbing. So - that _is_ a C-domain. I suggest you try getting libfg to run, probably by using you distro's package management. Diez From albert at compuscan.co.za Thu Feb 9 03:15:06 2006 From: albert at compuscan.co.za (Albert Leibbrandt) Date: Thu, 09 Feb 2006 10:15:06 +0200 Subject: how to remove
using replace function? In-Reply-To: <1139472365.378523.141150@g44g2000cwa.googlegroups.com> References: <1139462640.951603.302830@g44g2000cwa.googlegroups.com> <1139464079.635612.289930@o13g2000cwo.googlegroups.com> <1139465695.997171.159150@g44g2000cwa.googlegroups.com> <1139469846.713121.219060@g47g2000cwa.googlegroups.com> <1139472365.378523.141150@g44g2000cwa.googlegroups.com> Message-ID: <43EAFA0A.7030405@compuscan.co.za> Rinzwind wrote: >Works for me. > > > >>>>txt = "an unfortunate
in the middle" >>>>print txt.replace("
", "") >>>> >>>> >an unfortunate in the middle > > > > >Though I don't like the 2 spaces it gives ;) > > > so use regex and replace both the double spaces and the
cheers albert From santafefrank at cybermesa.com Fri Feb 10 22:37:07 2006 From: santafefrank at cybermesa.com (Frank LaFond) Date: Fri, 10 Feb 2006 20:37:07 -0700 Subject: Jython inherit from Java class In-Reply-To: <43ecee24_2@newspeer2.tds.net> References: <1139344211.725580.263660@g47g2000cwa.googlegroups.com> <43eab05b_2@newspeer2.tds.net> <1139594138.216488.12730@g14g2000cwa.googlegroups.com> <1139600759.152551.138440@g14g2000cwa.googlegroups.com> <43ecee24_2@newspeer2.tds.net> Message-ID: Jython 2.2 Alpha 1 supports Java 1.5 Frank. Kent Johnson wrote: > Mark Fink wrote: > >> I observed something strange when I tried to compile the jython class: >> 'assert' is a keyword, and may not be used as an identifier >> (try -source 1.3 or lower to use 'assert' as an identifier) >> public static void assert(PyObject test, PyObject message) { > > >> Looks like something in the Jython core causes the problem >> (org\python\core\Py.java) any Ideas what I can do? > > > I think jythonc is not compatible with Java 1.5, try compiling with 1.4. > > Kent From russandheather at gmail.com Thu Feb 9 12:35:14 2006 From: russandheather at gmail.com (Russell Warren) Date: 9 Feb 2006 09:35:14 -0800 Subject: Finding the public callables of self In-Reply-To: <1139503421.181118.127580@o13g2000cwo.googlegroups.com> References: <1139501230.964886.190500@g43g2000cwa.googlegroups.com> <1139503421.181118.127580@o13g2000cwo.googlegroups.com> Message-ID: <1139506514.422801.248500@g14g2000cwa.googlegroups.com> > import inspect > myCallables = [name for name, value in inspect.getmembers(self) if not > name.startswith('_') and callable(value)] Thanks. I forgot about the inspect module. Interestingly, you've also answered my question more than I suspect you know! Check out the code for inspect.getmembers(): def getmembers(object, predicate=None): """Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.""" results = [] for key in dir(object): value = getattr(object, key) if not predicate or predicate(value): results.append((key, value)) results.sort() return results Seems familiar! The fact that this is using dir(), getattr(), and callable() seems to tell me there is no better way to do it. I guess my method wasn't as indirect as I thought! And thanks for the reminder about getattr() instead of __getattribute__() and other streamlining tips. Russ From gregory.petrosyan at gmail.com Mon Feb 13 14:26:50 2006 From: gregory.petrosyan at gmail.com (Gregory Petrosyan) Date: 13 Feb 2006 11:26:50 -0800 Subject: Pythonic gui format? Message-ID: <1139858810.606052.39130@z14g2000cwz.googlegroups.com> Buenos dias, amigos! I have to write _simple_ gui library, for embedding into game. My first attempt was to use XML: isn't it cute to describe ui in such a way: Hello World! (some text here) first element second one...