From econtreras.bantech at gmail.com Fri Aug 15 08:26:08 2008 From: econtreras.bantech at gmail.com (econtreras.bantech at gmail.com) Date: Fri, 15 Aug 2008 05:26:08 -0700 (PDT) Subject: =?ISO-8859-1?Q?Re=3A_Don=B4t_find_HTMLgen?= References: <121682ff-1bfe-44db-a038-e764f26f012f@d77g2000hsb.googlegroups.com> Message-ID: <7a3d43ca-458e-4b27-8e89-23218162e25f@k37g2000hsf.googlegroups.com> On 15 ago, 00:10, "Gabriel Genellina" wrote: > En Thu, 14 Aug 2008 17:10:26 -0300, ? > escribi : > > > I am looking for HTMLgen module but not to find this, the link > > referenced inwww.python.orgit does not exist. > > > I have need to develop in cgi and would want to do it of the possible > > traditional form but, i like any module for my help. > > I like HyperText a lot more than HTMLGen - but it's no more available. > Both pyWeb and XIST ? > have evolved from it. > But I prefer to use a templating system rather than building HTML by code ? > > > -- > Gabriel Genellina Thank a lote. From fredrik at pythonware.com Fri Aug 29 01:20:22 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 29 Aug 2008 07:20:22 +0200 Subject: Checking if the file is a symlink fails In-Reply-To: References: <803e077e-c0c9-43d3-b40a-99511c2e55f3@25g2000prz.googlegroups.com> Message-ID: saswat at gmail.com wrote: > Do you mean the following is deprecated ? > http://docs.python.org/lib/module-stat.html > >>From the documentation - > > S_ISLNK( mode) > Return non-zero if the mode is from a symbolic link. As that page states, that's a function used to interpret a mode flag returned by os.stat, os.fstat, or os.lstat. It obviously won't give you the result you're looking for if you use a stat function that *follows* symbolic links. From ricaraoz at gmail.com Tue Aug 26 09:56:39 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 26 Aug 2008 10:56:39 -0300 Subject: Read dbf file as read only In-Reply-To: <00e201c90698$7f063a40$1f01a8c0@RAZAK> References: <00e201c90698$7f063a40$1f01a8c0@RAZAK> Message-ID: <48B40B97.1020502@bigfoot.com> ajak_yahoo wrote: > Hi, > > How can I access a foxpro dbf file from my python program. > I just want to read it as a read only file. > Regards, > Check Paul McNett's article in FoxTalk "Exploring Python from a Visual Foxpro Perspective" and check the code in : http://www.paulmcnett.com/vfp/09MCNESC.zip HTH From deets at nospam.web.de Fri Aug 22 08:45:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 22 Aug 2008 14:45:53 +0200 Subject: Trouble importing modules in IDLE (Win32) In-Reply-To: <1738d364-4622-40d2-8862-452032ffedac@i76g2000hsf.googlegroups.com> References: <1738d364-4622-40d2-8862-452032ffedac@i76g2000hsf.googlegroups.com> Message-ID: <6h7qo1Fjip32U1@mid.uni-berlin.de> boblatest at googlemail.com schrieb: > Hello, > > I wrote aprogram that imports odbc and dbi. Originally I used PyWin, > but now I prefer IDLE for working in Windows. Anyway, when I start my > program from IDLE, it can't import the odbc and dbi modules. However, > when I restart the shell and type "import odbc" at the prompt by, I > don't get an error. When I try to run the program now, I get the error > again. When I now type "import odbc" at the prompt, I get the error as > well. > > In short: > In a freshly (re)started shell, I can use "import odbc" by hand. I > can't import odbc from within a script, or by hand after trying to > start such a script. Screen capture follows. > > robert > >>>> ================================ RESTART ================================ >>>> import odbc # <<-no error here! >>>> ================================ RESTART ================================ >>>> # script started here > > Traceback (most recent call last): > File "H:\PythonProjekte\ADBExpress.py", line 1, in > import odbc > ImportError: DLL load failed: Das angegebene Modul wurde nicht > gefunden. > > In both shell and idle, do >>> import sys >>> print sys.prefix Most probably these differ, and you need to install the odbc-module to the python idle uses. Diez From lists at cheimes.de Wed Aug 20 18:19:09 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 21 Aug 2008 00:19:09 +0200 Subject: Negative integers In-Reply-To: References: Message-ID: johnewing wrote: > but that fails when one of the numbers is 0. I'm sure that there is > an easy way to do this. Any suggestions? For the not-so-distant future: Python 2.6 and 3.0 have a new function "copysign" in the math module. I added it during the revamp of the math module. copysign(x, y) returns x as float with the sign of y. It works also works for ints, longs and floats as y. copysign() is the most reliable and fastest way to distinguish -0.0 from +0.0. >>> from math import copysign >>> copysign(1.0, 23) 1.0 >>> copysign(1.0, -42) -1.0 >>> copysign(1.0, -0.0) -1.0 >>> copysign(1.0, +0.0) 1.0 >>> -0.0 == +0.0 True Christian From siryuhan at gmail.com Fri Aug 8 14:16:12 2008 From: siryuhan at gmail.com (Max) Date: Fri, 8 Aug 2008 11:16:12 -0700 (PDT) Subject: HTTP basic authentication with form-based authentication References: <1bc73112-9ac9-4c6b-988e-806fd6808192@p25g2000hsf.googlegroups.com> Message-ID: On Aug 7, 3:54?pm, Wojtek Walczak wrote: > Dnia Thu, 7 Aug 2008 11:14:05 -0700 (PDT), Max napisa?(a): > Use ClientCookie or even better - mechanize:http://pypi.python.org/pypi/mechanize/ > The docs aren't perfect, but you should easily > find what you are searching for. Thank you; mechanize is perfect. The example at http://wwwsearch.sourceforge.net/mechanize/ provided enough information for my problem. From execrable at gmail.com Sun Aug 10 15:17:09 2008 From: execrable at gmail.com (B) Date: Sun, 10 Aug 2008 12:17:09 -0700 Subject: Second python program: classes, sorting In-Reply-To: <6g8q7cFescp6U1@mid.individual.net> References: <6g8q7cFescp6U1@mid.individual.net> Message-ID: WP wrote: > Hello, here are some new things I've problems with. I've made a program > that opens and reads a text file. Each line in the file contains a name > and a score. I'm assuming the file has the correct format. Each > name-score pair is used to instantiate a class Score I've written. This > works fine, but here's my problem: After reading the file I have list of > Score objects. Now I want to sort them in descending order. But no > matter how I write my __cmp__ the order remains unchanged. I've > determined that __cmp__ is called but it's only called twice for three > list elements, isn't that odd? > > Complete program: > class Score: > def __init__(self, name_, score_): > self.name = name_ > self.score = score_ > > def __str__(self): > return "Name = %s, score = %d" % (self.name, self.score) > > def __cmp__(self, other): > print "in __cmp__" > return self.score >= other.score > > name = "" > score = 0 > # End class Score > > filename = "../foo.txt"; > > try: > infile = open(filename, "r") > except IOError, (errno, strerror): > print "IOError caught when attempting to open file %s. errno = %d, > strerror = %s" % (filename, errno, strerror) > exit(1) > > lines = infile.readlines() > > infile.close() > > lines = [l.strip() for l in lines] # Strip away trailing newlines. > > scores = [] > > for a_line in lines: > splitstuff = a_line.split() > > scores.append(Score(splitstuff[0], int(splitstuff[1]))) > > scores.sort() > > for a_score in scores: > print a_score > > Test file contents: > Michael 11 > Hanna 1337 > Lena 99 > > Output: > in __cmp__ > in __cmp__ > Name = Michael, score = 11 > Name = Hanna, score = 1337 > Name = Lena, score = 99 > > What am I doing wrong here? > > - Eric (WP) From http://docs.python.org/ref/customization.html: __cmp__( self, other) Called by comparison operations if rich comparison (see above) is not defined. Should return a negative integer if self < other, zero if self == other, a positive integer if self > other. You're not handling all the comparison cases, just assumping __cmp__ is being called for >=, when it's not. You can fix your __cmp__ function, but it's probably easier to understand if you overload specific comparison functions: __lt__, __gt__, etc. From deets at nospam.web.de Tue Aug 12 05:56:01 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 12 Aug 2008 11:56:01 +0200 Subject: File reading across network (windows) References: <6gcq3qFehr5kU1@mid.uni-berlin.de> Message-ID: <6gd53jFf6n2dU1@mid.uni-berlin.de> >> You need to create network shares in windows first. Once these are >> established, *all* programs using file-IO - including python - can >> access files. >> > It isn't absolutely essential to create a network share first: most > windows apis, including those used by Python, will be very happy with a > UNC path: You still need to create a share on the serving machine. The UNC-path is just for accessing it without *mounting* it on a local machine under some drive-letter. I should have worded clearer what I meant, though. You are of course right that actually mounting the drives makes it much easier to deal with them regarding authentication. Diez From epastore at metagovernment.org Fri Aug 8 14:33:27 2008 From: epastore at metagovernment.org (Ed Pastore) Date: Fri, 08 Aug 2008 14:33:27 -0400 Subject: Programmers needed: open governance project Message-ID: The Metagovernment project is seeking Python programmers to help us build Metascore, an open source (Affero GPL) web application intended to act as the governing mechanism of any community of any size. http://www.metagovernment.org/wiki/Metascore Metascore could be used for something as simple as managing the administrative functions of a chess club to something as massive as being the legal government of a city (or larger). The primary objective is to enable everyone in a community to participate in the governance of that community, without having to rely on any individual leader/representative. In its simplest form, this system can simplify the administration of small communities, obviating the need for a cumbersome bureaucratic structure. In it's most sophisticated potential application, it can enable massively-participatory ("web 2.0") global direct democracy without suffering from the traditional flaws of "mob rule." We are attempting to build a mechanism where consensus can be built organically through the promotion of synthesis between conflicting points of view. We invite you to check us out and see if you could be of assistance. We are pre-Alpha, and currently have two radically different branches. One of those is being developed in Python 2.4 and Django, and the lead developer would love to have some help. See this page for a general description and a link to a code repository: http://www.metagovernment.org/wiki/PrototypeA A running copy of the code is on the developer's laptop (but will be moved to metascore.org soon), so I won't give out that link, but he would be happy to talk to / share with you. What's in it for you, other than some great programming experience? A chance to be an architect and builder of what just might be the new government of humanity. It is a long road we are following, but clearly the world is poised to mature beyond archaic, leader-follower forms of government. This is your chance to be one of the key players to make it happen. Feel free to contact me, contact the lead developer of this branch (he hangs out on #metascore on irc.freenode.net) or to join our startup committee (i.e., mailing list) detailed at: http://www.metagovernment.org/wiki/Startup Thank you for your consideration. Ed Pastore Metagovernment project http://www.metagovernment.org/wiki/User:Ed_Pastore From tjreedy at udel.edu Tue Aug 5 16:15:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 05 Aug 2008 16:15:43 -0400 Subject: very large dictionary In-Reply-To: <7ef44808-5f88-4860-8f3b-dcad586f6f53@i76g2000hsf.googlegroups.com> References: <5c5e6d6e-04ef-4340-963f-d3825875b32c@e39g2000hsf.googlegroups.com> <6fftjvFb7ktoU2@mid.uni-berlin.de> <60FCF960-D1CD-4885-9F46-B5D7B798A9FF@gmail.com> <20080803224254.GG11163@tuva.opensoft.se> <6b690d0c-d817-4582-9dd1-9309b2d5cda1@e39g2000hsf.googlegroups.com> <00a78388$0$20302$c3e8da3@news.astraweb.com> <7ef44808-5f88-4860-8f3b-dcad586f6f53@i76g2000hsf.googlegroups.com> Message-ID: Simon Strobl wrote: > > Well, as I was using Python, I did not expect to have to care about > the language's internal affairs that much. I thought I could simply do > always the same no matter how large my files get. In other words, I > thought Python was really scalable. Python the language is indefinitely scalable. Finite implementations are not. CPython is a C program compiled to a system executable. Most OSes run executables with a fairly limited call stack space. CPython programs are, when possible, cached as .pyc files. The existence and format of .pyc's is an internal affair of the CPython implementation. They are most definitely not a language requirement or language feature. Have you tried feeding multigigabytes source code files to other compilers? Most, if not all, could be broken by the 'right' big-enough code. tjr From __peter__ at web.de Sat Aug 16 02:22:36 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 16 Aug 2008 08:22:36 +0200 Subject: sqlite empty inserts References: <9c28ccd0-ba04-4e21-8cbb-ff8959c4801e@m44g2000hsc.googlegroups.com> Message-ID: sapsi wrote: > I created a table like: > > create table __saved_query__ (vdb_name text , query_table_name text > PRIMARY KEY, query text) > > and then I insert as follows > > self.cursor.execute( "insert into __saved_query__(vdb_name, > query_table_name, query) values (?,?,?)", (vdbname, > foldername,where_query)) > self.conn.commit() > Now for some reason, the first insert works, but thereafter all > inserts result in empty rows > e.g > sqlite> select * from __saved_query__; > TestVDB|test_b|title regexp 'boo' > || > || > > The last two rows are from the 2nd and 3rd inserts. The values i;m > inserting are non null. > > Any ideas? Change the query to ... query_table_name text PRIMARY KEY NOT NULL ... to verify that assertion before you look any further. Peter From timothy.grant at gmail.com Tue Aug 5 23:35:02 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Tue, 5 Aug 2008 20:35:02 -0700 Subject: Finding IP address of localhost via socket API (or other API) In-Reply-To: <00a8dffe$0$20317$c3e8da3@news.astraweb.com> References: <38c9cdb10808051450q3912f70evdae9fd61950e09d2@mail.gmail.com> <00a8dffe$0$20317$c3e8da3@news.astraweb.com> Message-ID: On Tue, Aug 5, 2008 at 4:39 PM, Steven D'Aprano wrote: > Sorry for replying to the replier (Timothy) instead of the OP (David), > but the original post seems to have been eaten by my ISP. > > On Tue, 05 Aug 2008 15:48:26 -0700, Timothy Grant wrote: > >> On Tue, Aug 5, 2008 at 2:50 PM, David York wrote: >>> Does anybody know how to find the real IP address (e.g.: address >>> visible to internet) of a machine via Python? In other words I have a >>> machine with an IP address something like 192.168.1.5, an address given >>> to me by a router. The router's address (and thus my machine's address) >>> to the outside world is something realistic, 123.156.123.156 or >>> whatever. How do I get that number? I've tried >>> socket.getaddrinfo('localhost', None) but all I get is 127.0.0.1 as >>> expected. >>> >>> How do I find out my machine's IP address as visible to the outside >>> world? Thanks a lot. >>> >>> David >> >> I'm not sure what you are trying to accomplish. The machine I'm typing >> this on has a 192.168.x.x number. The router that gave it to me also has >> a 192.168.x.x number. However, I know that that is not the IP that the >> world sees when my packets finally leave the building. > > That's the IP address the OP probably wants. At least, when I've asked > this exact same question, that's what I meant. > > The only way I know of is to query an external server that will tell you. > There's a few of them out there. Here's a few: > > http://checkip.dyndns.org/ > http://www.showmyip.com > http://www.showmyip.com/simple/ > http://whatismyip.org/ > > The basic algorithm is to connect to one of those sites and fetch the > data it returns, then parse it appropriately. Some of them return a > simple IP address, some a complicated bunch of text, some a nicely > formatted XML document. Some of them only allow you to query the server a > limited number of times. I don't remember which is which. > > To get you started, here's an untested piece of code: > > import urllib2 > import re > data = urllib2.urlopen(site).read() > matcher = re.compile(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}") > ip_address = matcher.search(data).group() > > > > -- > Steven Now that is a cool solution to the problem. It even works in my work environment where I have three routers between me and the front door. -- Stand Fast, tjg. [Timothy Grant] From fredrik at pythonware.com Wed Aug 13 18:27:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 00:27:11 +0200 Subject: Suggestion for improved ImportError message In-Reply-To: References: Message-ID: Kent Tenney wrote: > I was just bit by > > from image import annotate > > ImportError: cannot import name annotate > > I found the problem via > > import image > print image.__file__ > > which made it clear that the wrong image module had been found. that's what "python -v" is all about, of course. From kyosohma at gmail.com Tue Aug 19 12:09:54 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 19 Aug 2008 09:09:54 -0700 (PDT) Subject: datetime.datetime.now() in military time References: <4401a30e-0445-40d3-b23a-bec538ff148c@a70g2000hsh.googlegroups.com> Message-ID: <6d52b471-a587-4496-8e31-92b0ef763937@x41g2000hsb.googlegroups.com> On Aug 19, 10:42?am, korean_dave wrote: > import datetime > > def main(): > ? ? timenow = datetime.datetime.now() > ? ? print(str(timenow.hour)) > > if __name__ == "__main__": > ? ? main() > > If the time was, say, 2pm, how can I make output of timenow.hour "14" > instead of "2"? > > Thanks. > -Dave Use the strftime() method to convert the time. Something like this: print timenow.strftime('%H') See also: http://docs.python.org/lib/module-time.html Mike From http Wed Aug 6 00:24:24 2008 From: http (Paul Rubin) Date: 05 Aug 2008 21:24:24 -0700 Subject: URLs and ampersands References: <00a78f7e$0$20302$c3e8da3@news.astraweb.com> Message-ID: <7xabfqrcsn.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > I could just do a string replace, but is there a "right" way to escape > and unescape URLs? I've looked through the standard lib, but I can't find > anything helpful. xml.sax.utils.unescape() From cvrebert+clp at gmail.com Thu Aug 28 14:41:06 2008 From: cvrebert+clp at gmail.com (Chris Rebert) Date: Thu, 28 Aug 2008 11:41:06 -0700 Subject: Multiple values for one key In-Reply-To: <26c69b160808281002l262e4824y60b8d3cb3369ee91@mail.gmail.com> References: <26c69b160808271326w2f53b6b8s6e4aa7f91071ac71@mail.gmail.com> <48b6ca75$0$5088$426a74cc@news.free.fr> <26c69b160808281002l262e4824y60b8d3cb3369ee91@mail.gmail.com> Message-ID: <47c890dc0808281141n72b4af58uc78d9c7a2707880a@mail.gmail.com> On Thu, Aug 28, 2008 at 10:02 AM, Ron Brennan wrote: > I have another question. > > How would like to be able to add the contents on the values for one key. > > key['20001']:[978, 345] I'm assuming that by this you meant: assert the_dict['20001'] == [978, 345] > > How can I do this? sum(the_dict['20001']) #=> 1323 Regards, Chris ======== Follow the path of the Iguana... Rebertia: http://rebertia.com Blog: http://blog.rebertia.com > > Thanks, > Ron > > On Thu, Aug 28, 2008 at 11:56 AM, Bruno Desthuilliers > wrote: >> >> norseman a ?crit : >>> >>> Terry Reedy wrote: >>>> >>>> >>>> Ron Brennan wrote: >>>>> >>>>> Hello, >>>>> How would I create a dictionary that contains multiple values for one >>>>> key. >>>> >>>> Make the value a collection object (set or list if you plan to add and >>>> delete). >>>> >>>>> I'd also like the key to be able to have duplicate entries. >>>> >>>> Dict keys must be hashable and unique. >>>> >>>> tjr >>>> >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>>> >>> ================ >>> First part I understand, second is still giving me a problem. >>> >>> For some reason I still want keys to be dbf column headers. >>> like: >>> >>> name:address:zip so forth >>> ---- ------- --- ------------------ >>> guy: unknown:00000 >>> girl: 123 tiny street:12345 >>> boy:321 here:33333 >>> gal:999 over there: 55555 >>> so forth >>> >>> Thus one key has many values. And you can then index on whatever key(s) >>> you wish - name,zip... >> >> You can either use 1/ a list of dicts, or 2/ a dict mapping keys to lists. >> >> 1/ >> records = [ >> {"name":"guy", "address":"unknown","zip":"00000"}, >> {"name":"girl", "address":"123 tiny street","zip":"12345"}, >> {"name":"boy", "address":"321 here","zip":"33333"}, >> {"name":"gal", "address":"999 over there","zip":"55555"}, >> ] >> >> keys = ("name", "address", "zip") >> >> print ":".join(keys) >> print "-" * len(":".join(keys)) >> for record in records: >> data = [record[key] for key in keys] >> print ":".join(data) >> >> >> 2/ >> records = dict( >> name=["guy", "girl", "boy", "gal"], >> address=["unknown","123 tiny street","321 there","999 over there"], >> zip=["00000", "12345", "33333", "55555"] >> ) >> >> keys = ("name", "address", "zip") >> nb_records = len(records[keys[0]]) >> >> print ":".join(keys) >> print "-" * len(":".join(keys)) >> for i in xrange(nb_records): >> data = [data[key][i] for key in keys] >> print ":".join(data) >> >> >> You are of course entitled the right to prefer the second solution, but >> then I hope I'll never have to maintain your code, since it's obviously not >> an appropriate data structure. >> >>> With billions plus records, >> >> With billions plus records, it may be time to move to a serious RDBMS. >> Which btw will provide solution 1, or a lighter version of it using a list >> of tuples, ie: >> >> cursor = connection.cursor() >> cursor.execute("select name, address, zip from peoples") >> records = cursor.fetchall() >> >> # at this time, you have : >> #records = [ >> # ("guy", "unknown","00000",), >> # ("girl", "123 tiny street","12345",), >> # ("boy", "321 here","33333",), >> # ("gal", "999 over there", "55555",), >> #] >> >> >> (snip) >> >>> OK - I know I missed the whole concept of a Python Dictionary. >> >> Bad thing for you, since it's the central datastructure in Python. >> >>> I haven't read anything as yet that gives a clear picture of what it is >>> and what it is for. >> >> Then you failed to read the FineManual's tutorial, which is where you >> should have started: >> >> http://docs.python.org/tut/node7.html#SECTION007500000000000000000 >> >> Do yourself a favour : read the above first, then if you still have >> questions about dicts, we'll gladly try to help. >> >> And do yourself another favour : learn about SQL, relational model and >> RDBMS. >> >> (snip description of why the OP *really* wants a RDBMS) >> -- >> http://mail.python.org/mailman/listinfo/python-list > > > > -- > FYI, my email address is changing. My rogers account will be deactivated > shortly. From now on please use: > brennan.ron at gmail.com > > -- > http://mail.python.org/mailman/listinfo/python-list > From jack.sankey at gmail.com Sat Aug 9 17:20:38 2008 From: jack.sankey at gmail.com (Jack) Date: Sat, 9 Aug 2008 14:20:38 -0700 (PDT) Subject: swig and DWMAPI.dll Message-ID: <7668efcb-a077-410d-bd6a-45f54280821d@k30g2000hse.googlegroups.com> Hello, When I try and compile a C++ project into a _mystuff.pyd file using swig with wxDev-C++ it works. I can import, run and everything else in python. When I try to compile with g++ command line or code::blocks, compiles just fine but when I try to import it I get this error: File "", line 1, in File "D:\python\spinmobules\speedy.py", line 7, in import _speedy ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. Running "dependency walker" tells me that DWMAPI.dll is missing. This is a file that apparently is only on windows vista. Has anyone run into this problem? Is there an easy solution? Thanks, Jack From danb_83 at yahoo.com Wed Aug 20 23:58:45 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 20 Aug 2008 20:58:45 -0700 (PDT) Subject: How to make xss safe strings References: <919a78ae-8ed8-41ab-a283-6c642462b712@m45g2000hsb.googlegroups.com> Message-ID: <04f0974b-29e6-45b3-bf08-c2e59f7cf160@n33g2000pri.googlegroups.com> On Aug 20, 10:10?pm, Roopesh wrote: > Hi, > > How can I make a string XSS safe? Will > simply .replace('<','<').replace('>','>').... do the work? Or > are there some other issues to take into account?. Is there already a > function in python which will do this for me. For HTML, use the cgi.escape function. From tjreedy at udel.edu Fri Aug 1 21:36:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 01 Aug 2008 21:36:15 -0400 Subject: Agnostic fetching In-Reply-To: <5f7629e5-b290-46a9-a4d0-0662ed2cfec0@e39g2000hsf.googlegroups.com> References: <5f7629e5-b290-46a9-a4d0-0662ed2cfec0@e39g2000hsf.googlegroups.com> Message-ID: jorpheus wrote: > OK, that sounds stupid. Anyway, I've been learning Python for some > time now, and am currently having fun with the urllib and urllib2 > modules, but have run into a problem(?) - is there any way to fetch > (urllib.retrieve) files from a server without knowing the filenames? > For instance, there is smth like folder/spam.egg, folder/ > unpredictable.egg and so on. If not, perhaps some kind of glob to > create a list of existing files? I'd really appreciate some help, > since I'm really out of my (newb) depth here. If you are asking whether servers will let you go fishing around their file system, the answer is that http is not designed for that (whereas ftp is as long as you stay under the main ftp directory). You can try random file names, but the server may get unhappy and think you are trying to break in through a back door or something. You are *expected* to start at ..../index.html and proceed with the links given there. Or to use a valid filename that was retrieved by that method. From tjreedy at udel.edu Fri Aug 1 00:00:36 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 01 Aug 2008 00:00:36 -0400 Subject: How smart is the Python interpreter? In-Reply-To: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> References: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> Message-ID: ssecorp wrote: > def str_sort(string): > s = "" > for a in sorted(string): > s+=a > return s > > > if i instead do: > > def str_sort(string): > s = "" > so = sorted(string) > for a in so: > s+=a > return s > > > will that be faster or the interpreter can figure out that it only has > to do sorted(string) once? or that kind of cleverness is usually > reserved for compilers and not interpreters? The optimizations performed by a Python interpreter and where they are performed depend on the implementation and version. CPython is conservative about optimizations. Not only do the developers want to be sure they are 100% correct (unlike too many optimizing compilers), but Guido also rejects some that are too tricky and too fragile (easily broken by new maintainers). In Python 3.0, here are two compiler optimizations >>> from dis import dis >>> def f(): return 1+2 >>> dis(f) 1 0 LOAD_CONST 3 (3) 3 RETURN_VALUE # constant arithmetic (folding); done with floats also >>> def f(): a,b = 1,2 return a+b >>> dis(f) 2 0 LOAD_CONST 3 ((1, 2)) 3 UNPACK_SEQUENCE 2 6 STORE_FAST 0 (a) 9 STORE_FAST 1 (b) 3 12 LOAD_FAST 0 (a) 15 LOAD_FAST 1 (b) 18 BINARY_ADD 19 RETURN_VALUE # tuples with constant members are pre-built by the compiler and stored in the code object. What you don't see (if it is still there) is an optimization in the interpreter loop for BINARY_ADD that takes a shortcut if both operands are ints. tjr From twic at urchin.earth.li Wed Aug 13 13:18:21 2008 From: twic at urchin.earth.li (Tom Anderson) Date: Wed, 13 Aug 2008 18:18:21 +0100 Subject: strptime and timezones Message-ID: Hello! Possibly i'm missing something really obvious here. But ... If i have a date-time string of the kind specified in RFC 1123, like this: Tue, 12 Aug 2008 20:48:59 -0700 Can i turn that into a seconds-since-the-epoch time using the standard time module without jumping through substantial hoops? Apart from the timezone, this can be parsed using time.strptime with the format: %a, %d %b %Y %H:%M:%S You can stick a %Z on the end for the timezone, but that parses timezone names ('BST', 'EDT'), not numeric specifiers. Also, it doesn't actually parse anything, it just requires that the timezone that's in the string matches your local timezone. Okay, no problem, so you use a regexp to split off the timezone specifier, parse that yourself, then parse the raw time with strptime. Now you just need to adjust the parsed time for the timezone. Now, from strptime, you get a struct_time, and that doesn't have room for a timezone (although it does have room for a daylight saving time flag), so you can't add the timezone in before you convert to seconds-since-the-epoch. Okay, so convert the struct_time to seconds-since-the-epoch as if it were UTC, then apply the timezone correction. Converting a struct_time to seconds-since-the-epoch is done with mktime, right? Wrong! That does the conversion *in your local timezone*. There's no way to tell it to use any specific timezone, not even just UTC. So how do you do this? Can we convert from struct_time to seconds-since-the-epoch by hand? Well, the hours, minutes and seconds are pretty easy, but dealing with the date means doing some hairy calculations with leap years, which are doable but way more effort than i thought i'd be expending on parsing the date format found in every single email in the world. Can we pretend the struct_time is a local time, convert it to seconds-since-the-epoch, then adjust it by whatever our current timezone is to get true seconds-since-the-epoch, *then* apply the parsed timezone? I think so: def mktime_utc(tm): "Return what mktime would return if we were in the UTC timezone" return time.mktime(tm) - time.timezone Then: def mktime_zoned(tm, tz): "Return what mktime would return if we were in the timezone given by tz" return mktime_utc(tm) - tz The only problem there is that mktime_utc doesn't deal with DST: if tm is a date for which DST would be in effect for the local timezone, then we need to subtract time.altzone, not time.timezone. strptime doesn't fill in the dst flag, as far as i can see, so we have to round-trip via mktime/localtim: def isDST(tm): tm2 = time.localtime(time.mktime(tm)) assert (tm2.isdst != -1) return bool(tm2.isdst) def timezone(tm): if (isDST(tm)): return time.altzone else: return time.timezone mktime_utc then becomes: def mktime_utc(tm): return time.mktime(tm) - timezone(tm) And you can of course inline that and eliminate a redundant call to mktime: def mktime_utc(tm): t = time.mktime(tm) isdst = time.localtime(t).isdst assert (isdst != -1) if (isdst): tz = time.altzone else: tz = time.timezone return t - tz So, firstly, does that work? Answer: i've tested it a it, and yes. Secondly, do you really have to do this just to parse a date with a timezone? If so, that's ridiculous. tom -- 102 FX 6 (goblins) From phil at freehackers.org Sun Aug 24 04:48:46 2008 From: phil at freehackers.org (BlueBird) Date: Sun, 24 Aug 2008 01:48:46 -0700 (PDT) Subject: Interrupt python thread Message-ID: Hi, I have a program with a master thread and several slave threads. Whenever an exception occurs, in the master thread or in one of the slave threads, I would like to interrupt all the threads and the main program. Threading API does not seem to provide a way to stop a thread, is there anyway to achieve that ? The closest thing I found is thread.interrupt_main() but it's far from perfect : - it only allow to interrupt the main thread - if the main thread is sleeping, it does not interrupt it (at least on windows) cheers, Philippe From mistersulu at gmail.com Thu Aug 7 14:36:03 2008 From: mistersulu at gmail.com (mistersulu) Date: Thu, 7 Aug 2008 11:36:03 -0700 (PDT) Subject: wxPython pop--up ("could not retrieve information...") Message-ID: Hi all: I'm using a wx.ListView object with a multi-threaded wxPython app. The list is dynamically generated and accessed across two or more threads. In spite of the fact that I have checks to see if an item at a given index is in the list and the entire set of logic is contained within a try: except: block I periodically get pop-up windows stating "Could not retrieve information for list control item X" when I try to change or access the list items. I searched the web and groups for similar posts but can't find any solutions. My question is: Is there a setting somewhere in wxPython to either disable these pop- up messages or a semaphore or event locking method to enable cross- thread access to a listview object? Thanks in advance, sulu From andrew_reed at ymail.com Sat Aug 2 07:20:04 2008 From: andrew_reed at ymail.com (Andrew Reed) Date: Sat, 2 Aug 2008 04:20:04 -0700 (PDT) Subject: Histogram and \lambda parameter of the laplacian curve. Message-ID: <825289.28609.qm@web59505.mail.ac4.yahoo.com> even i am trying to generate this curve. are you able to generate this curve using matplotlib, because i was thinking to write a library for it. -- Andrew. >Thanks everyone for your earlier help. >I have to plot a histogram of values lets say [0.5,0.6,0.8,0.9].I guess the >histogram would show an exponential decay ie, the laplacian curve. >I need to find the \lambda parameter of this curve . >So please tell me if it be done through >http://matplotlib.sourceforge.net/and are there any other libraries >which can be used. >Thanks in advance. >Aditya -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From goldnery at gmail.com Fri Aug 22 09:04:44 2008 From: goldnery at gmail.com (Gandalf) Date: Fri, 22 Aug 2008 06:04:44 -0700 (PDT) Subject: Question about wx BoxSizer background References: <79ff96a2-b5dd-4f0a-8e56-cc3525aa1dd0@y38g2000hsy.googlegroups.com> <0372ff83-80bf-4d04-abe5-4065ef2093ac@b30g2000prf.googlegroups.com> Message-ID: <96394093-4ce9-4fd0-ae22-57a3e0a138fd@8g2000hse.googlegroups.com> thanks! From avinashvora at gmail.com Sun Aug 3 13:44:22 2008 From: avinashvora at gmail.com (Avinash Vora) Date: Sun, 3 Aug 2008 23:14:22 +0530 Subject: Teething troubles with Python on a Mac In-Reply-To: References: <6651edd6-d47f-4e10-bf0b-0875190b9bc2@a1g2000hsb.googlegroups.com> <489546F1.9050102@cosc.canterbury.ac.nz> <3dcf39de-3c3c-4e47-abb4-508d1601a9e2@z11g2000prl.googlegroups.com> Message-ID: > You will likely cause more problems updating the system python than > managing the two separate installations. That's sadly worrying. > OSX relies on the version of python they ship. I think that helps my point--there *are* bug fixes between major versions despite the new language changes, and that can really only be a good thing. > While there are likely cases where it could be > replaced completely safely the risks of having to re-install your OS > at some point because it has the wrong version of python are not worth > it. I haven't been a Mac user long enough to see a major version change (I was on Linux/XP/Vista for most of 2.4 and switched distributions right after 2.5 came out, and then XP before that), so I've never seen a version change, but is this the sort of thing that will be upgraded in Software Update? - Avinash From emile at fenx.com Fri Aug 22 17:39:11 2008 From: emile at fenx.com (Emile van Sebille) Date: Fri, 22 Aug 2008 14:39:11 -0700 Subject: Should Python raise a warning for mutable default arguments? In-Reply-To: References: <00becb2d$0$20312$c3e8da3@news.astraweb.com> <6h8hhhFk2gamU1@mid.uni-berlin.de> Message-ID: Dan wrote: > I'd suggest that at the > end of the tutorial, when people have a better general idea of how > Python works, there would be a Python Gotchas section. > Hmmm, OK -- mutable defaults, integer division, name mangling... I'd think decimal precision is more a general problem than a python problem, but still one that throws newbies... Any other ideas for gotcha's (as opposed to faqs)? Emile From none at this.time Tue Aug 12 09:17:30 2008 From: none at this.time (The Pythonista) Date: Tue, 12 Aug 2008 09:17:30 -0400 Subject: Building python-svn from source References: <403f9$48a0f24e$4963@news.teranews.com> <48a119e9$0$4513$9b622d9e@news.freenet.de> Message-ID: On Tue, 12 Aug 2008 07:04:41 +0200, Martin v. L?wis wrote: > For some reason, the getopt module in your host's python cannot process > the command line options to asdl_c.py correctly. > > What Python version do you have installed in PATH? Martin, Thank you so much! In fact, I did have a python executable on my PATH in ~/bin that was screwing things up. After I moved it (thus leaving the system default python as the only python executable on my PATH), the build process went smoothly (except for not being able to find a few libraries for some C extensions, but I think I can fix that). I now have working python2.6 and python3.0 executables to play with, thanks to you. :-) -- code.py: A blog about life, the universe, and Python http://pythonista.wordpress.com ** Posted from http://www.teranews.com ** From mad.vijay at gmail.com Thu Aug 7 02:58:08 2008 From: mad.vijay at gmail.com (SamG) Date: Wed, 6 Aug 2008 23:58:08 -0700 (PDT) Subject: os.system question References: <1c5bf$489a4add$4275d90a$15022@FUSE.NET> Message-ID: On Aug 7, 6:07?am, Kevin Walzer wrote: > ?>>> import os > ?>>> foo = os.system('whoami') > kevin > ?>>> print foo > 0 > ?>>> > > The standard output of the system command 'whoami' is my login name. Yet > the value of the 'foo' object is '0,' not 'kevin.' How can I get the > value of 'kevin' associated with foo? > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com Why dont you try commands module instead.... In [28]: import commands In [29]: dir(commands) Out[29]: ['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'getoutput', 'getstatus', 'getstatusoutput', 'mk2arg', 'mkarg'] In [30]: (a,b) = commands.getstatusoutput('whoami') In [31]: print a 0 In [32]: print b luma35 From Josef.Robert.Novak at gmail.com Wed Aug 13 04:28:35 2008 From: Josef.Robert.Novak at gmail.com (kettle) Date: Wed, 13 Aug 2008 01:28:35 -0700 (PDT) Subject: python tr equivalent (non-ascii) References: <552ee625-5d07-4f37-958f-abe046cdff3d@v1g2000pra.googlegroups.com> Message-ID: <9463c35a-fef9-48be-8840-8fd1c0d2fa37@a3g2000prm.googlegroups.com> On Aug 13, 5:18 pm, kettle wrote: > Hi, > I was wondering how I ought to be handling character range > translations in python. > > What I want to do is translate fullwidth numbers and roman alphabet > characters into their halfwidth ascii equivalents. > In perl I can do this pretty easily with tr: > > tr/\x{ff00}-\x{ff5e}/\x{0020}-\x{007e}/; > > and I think the string.translate method is what I need to use to > achieve the equivalent in python. Unfortunately the maktrans method > doesn't seem to accept character ranges and I'm also having trouble > with it's interpretation of length. What I came up with was to first > fudge the ranges: > > my_test_string = u"???????" > f_range = "".join([unichr(x) for x in > range(ord(u"\uff00"),ord(u"\uff5e"))]) > t_range = "".join([unichr(x) for x in > range(ord(u"\u0020"),ord(u"\u007e"))]) > > then use these as input to maketrans: > my_trans_string = > my_test_string.translate(string.maketrans(f_range,t_range)) > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode characters in position > 0-93: ordinal not in range(128) > > but it generates an encoding error... and if I encodethe ranges in > utf8 before passing them on I get a length error because maketrans is > counting bytes not characters and utf8 is variable width... > my_trans_string = > my_test_string.translate(string.maketrans(f_range.encode("utf8"),t_range.encode("utf8"))) > Traceback (most recent call last): > File "", line 1, in ? > ValueError: maketrans arguments must have same length Ok so I guess I was barking up the wrong tree. Searching for python ?? ??? quickly brought up a solution: >>>import unicodedata >>>my_test_string=u"????-%*@A????????3" >>>print unicodedata.normalize('NFKC', my_test_string.decode("utf8")) ????-%*@ABC-%*@123 >>> still, it would be nice if there was a more general solution, or if maketrans actually looked at chars instead of bytes methinks. From dancinguy at linkline.com Sat Aug 2 21:44:22 2008 From: dancinguy at linkline.com (Tyler Breisacher) Date: Sat, 02 Aug 2008 18:44:22 -0700 Subject: I =?ISO-8859-1?Q?don=E4=27t_get_while-loops?= In-Reply-To: <51261108-f7d1-43c0-83ba-3c3885d8545b@y38g2000hsy.googlegroups.com> References: <51261108-f7d1-43c0-83ba-3c3885d8545b@y38g2000hsy.googlegroups.com> Message-ID: <48950D76.7020200@linkline.com> You're actually calling the read2() function from within read2(). This is called recursion, and it is *not* what you want in this case, since it unnecessarily fills up your call stack. Remember that a while loop automatically goes back to the top without you having to re-call your function. I would just do this: def read3(): expr = raw_input("Lisp> ") while expr != "quit": print parse(expr) expr = raw_input("Lisp> ") print "Good session!" ssecorp wrote: > in read2 it never quits when I write quit, why? > > def read(): > expr = raw_input("Lisp> ") > if expr != "quit": > print parse(expr) > read() > else: > print "Good session!" > > def read2(): > expr = "" > while expr != "quit": > expr = raw_input("Lisp> ") > print parse(expr) > read2() > print "Good session!" > From larry.bates at vitalEsafe.com Sat Aug 30 09:00:08 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Sat, 30 Aug 2008 08:00:08 -0500 Subject: Fastest way to write huge files In-Reply-To: References: <538050a90808281735u51ce90d0o3db3945a6ed2b591@mail.gmail.com> <48B7A8DA.7050203@timgolden.me.uk> Message-ID: Mohamed Yousef wrote: >> If connection is over Internet via HTTP the connection speed is so slow in >> relation to the speed of your CPU that it doesn't really matter. > this is not always true , espicially when using a localhost or a local > netwtork server > the problem is the increase in cpu and memory usage make it a painful bug > such that downloading a big file (say 1 GB ) would introduce a big cpu > usage (already tested) > > Thanks , > > Regards, > Mohamed Yousef I disagree. There is very little overhead in file writing if you stream your writes to disk in small blocks as they arrive via HTTP. Don't wait for the entire 1Gb to arrive and then write it. Python can write small to a file blazingly fast with normal file writing I/O. Any extra CPU overhead you may see is probably due to reading the entire 1Gb into memory and seeing swapping to disk as you exhaust main memory. Interleaving your HTTP reading with file writing should be very fast. -Larry From python at rgbaz.eu Fri Aug 1 02:46:11 2008 From: python at rgbaz.eu (Python.Arno) Date: Fri, 1 Aug 2008 08:46:11 +0200 Subject: like py2exe, but on a mac In-Reply-To: References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> <341kk.407$aA5.312@trnddc05> <0I2kk.565$rb5.429@trnddc04> Message-ID: oops didn't send it to the list... On 31 jul 2008, at 23:28, Python.Arno wrote: > > On 30 jul 2008, at 20:48, William McBrine wrote: > >> On Wed, 30 Jul 2008 16:57:35 +0000, I wrote: >> >>> [bundlebuidler] does put in a version-specific #! line, but if I >>> change >>> that to #!/usr/bin/env python, the app still works, and it seems >>> to me >>> that it will work for any version of Python on OS 10.4, 10.5, and >>> maybe >>> 10.3. >> >> Then again, I see now that it has more hardwired paths in the >> "Python" >> binary. Bah. > > > Arno wrote: > oh just one i forgot, you can also compile python scripts into > executables > with apple's Xcode, in the developer's tools > gr Arno From wannymahoots at gmail.com Tue Aug 19 08:35:27 2008 From: wannymahoots at gmail.com (wannymahoots at gmail.com) Date: Tue, 19 Aug 2008 05:35:27 -0700 (PDT) Subject: optparse escaping control characters Message-ID: <4001fcc2-e595-4bd6-9baf-c71db3761d36@m3g2000hsc.googlegroups.com> optparse seems to be escaping control characters that I pass as arguments on the command line. Is this a bug? Am I missing something? Can this be prevented, or worked around? This behaviour doesn't occur with non-control characters. For example, if this program (called test.py): from optparse import OptionParser parser = OptionParser() parser.add_option("-d", dest="delimiter", action="store") (options, args) = parser.parse_args() print options is run as follows: python test.py -d '\t' it outputs: {'delimiter': '\\t'} i.e. the \t has had an escape character added to give \\t. From nick at craig-wood.com Tue Aug 12 19:33:42 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 12 Aug 2008 18:33:42 -0500 Subject: export sites/pages to PDF References: Message-ID: jvdb wrote: > My employer is asking for a solution that outputs the content of urls > to pdf. It must be the content as seen within the browser. > Can someone help me on this? It must be able to export several kind of > pages with all kind of content (javascript, etc.) Sounds like you'd be best off scripting a browser. Eg under KDE you can print to PDF from Konqueror using dcop to remote control it. Here is a demo... start Konqueror, select the PDF printer manually before you start. (You can automate this I expect!) Run dcop konq* to find the id of the running konqueror (in my case "konqueror-18286"), then open a URL dcop konqueror-18286 konqueror-mainwindow#1 openURL http://www.google.com To print to a PDF file dcop konqueror-18286 html-widget2 print 1 Web site converted to PDF in ~/print.pdf ;-) Easy enough to script that with python. See here for some more info on dcop :- http://www.ibm.com/developerworks/linux/library/l-dcop/ -- Nick Craig-Wood -- http://www.craig-wood.com/nick From adityashukla1983 at gmail.com Tue Aug 19 15:48:26 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Tue, 19 Aug 2008 14:48:26 -0500 Subject: Newbie question about sending and receiving data to the command prompt. Message-ID: <73045cca0808191248o47d315d5wb9780b92e17dc684@mail.gmail.com> Hello folks, I am using windows vista and i am trying to send data to the command prompt ,this is what is done. import subprocess proc =subprocess.Popen('cmd.exe',stdin=subprocess.PIPE) proc.communicate('abc') when i run this the command prompt just blinks and disappears , can anyone explain what's going on? Similarly when i am trying to receive data from the command prompt the same thing happens.This is what i have done. proc = subprocess.Popen('cmd.exe',stdout=subprocess.PIPE, ) stdout_value = proc.communicate()[0] print '\tstdout:', repr(stdout_value) -command prompt blinks and disappears.Please explain what's happening. Thanks in advance. Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From mbrkic at invalid_mail.adress Sat Aug 30 21:36:39 2008 From: mbrkic at invalid_mail.adress (Marin Brkic) Date: Sun, 31 Aug 2008 03:36:39 +0200 Subject: Writing to ms excel References: Message-ID: <09tjb4p32lfbk4nji4sqjg5mk0e99gub2v@4ax.com> On Sat, 30 Aug 2008 19:37:16 +0200, "Marco Bizzarri" wrote: > >Is it suitable for you to use a python program talking with a running >instance of openoffice? in that case, pyuno could help you. Hello Marco, thanks for answering, no, sorry. As much as I like OOffice, several other people will be using the program I'm working on, and I can't cound on them having the OOffice installed. MS, as much as I hate to admit it, is the industry standard (or, at least that's the one we're stuck with at the present time ;-) Best regards Marin From tjreedy at udel.edu Fri Aug 8 16:33:42 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 08 Aug 2008 16:33:42 -0400 Subject: Best practise implementation for equal by value objects In-Reply-To: <71daf8cf-024c-4ab1-b050-7f1f626e89c0@r66g2000hsg.googlegroups.com> References: <135eb396-6daa-4ff4-a722-253ba149889c@27g2000hsf.googlegroups.com> <573362d6-5356-4029-8ee4-f43248263976@p25g2000hsf.googlegroups.com> <71daf8cf-024c-4ab1-b050-7f1f626e89c0@r66g2000hsg.googlegroups.com> Message-ID: Slaunger wrote: > OK, i am encouraged to carry on my quest with the eval(repr)) for my > 'nice' classes. > I just revisited the documentation for eval and noticed that there are > optional globals > and locals name space variables, that one could specify: > > http://docs.python.org/lib/built-in-funcs.html > > Quite frankly I do not understand how to make use of these parameters, > but it is my feeling > that if I enforce a convention of always specifying the globals/locals > parameter in a specific > manner: > assert eval(repr(x), globals, locals) == x > would work independent of how I have imported the module under test. I have no opinion as to whether you should or should not use eval beyond testing. But I believe the following will work and teach a bit more too. In one module, define 'mynice = {'Age':Age, ...}' for your nice classes (that module could import from other modules and use dotted names as needed). Then eval(repr(x), mynice, mynice) should work anywhere (as long as mynice has been imported!). From gabriel.rossetti at arimaz.com Wed Aug 20 11:01:29 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 20 Aug 2008 17:01:29 +0200 Subject: getattr() on nested functions? In-Reply-To: References: <48ABD71E.8060907@arimaz.com> Message-ID: <48AC31C9.4000304@arimaz.com> Gabriel Genellina wrote: > En Wed, 20 Aug 2008 05:34:38 -0300, Gabriel Rossetti > escribi?: > >> I can't get getattr() to return nested functions, I tried this : >> >> >>> def toto(): >> ... def titi(): >> ... pass >> ... f = getattr(toto, "titi") >> ... print str(f) >> ... >> >>> toto() >> Traceback (most recent call last): >> File "", line 1, in >> File "", line 4, in toto >> AttributeError: 'function' object has no attribute 'titi' >> >>> >> >> I thought that since functions are objects, that I could obtain it's >> nested functions. How come it doesn't work and what can I do to >> fix/replace it? I'm using it in code that is like this : > > Yes, functions are objects, but inner functions aren't attributes of > the outer; they live in its local namespace instead (and inner > functions won't exist until the outer function executes) Ok, yes, I see > >> def __test(self, action, *args): >> def request(params): >> pass >> def submit(params, values): >> pass >> def update(params, values): >> pass >> def delete(params): >> pass >> result = getattr(__test, action)(*args) >> return resultToXml(result) >> >> where "action" is a string containing either "request", "submit", >> "update", or "delete". I was using an evel() with this form : >> >> result = eval(action + "(params, values)") >> >> but I didn't find that very clean. > > Try using locals()[action] Yes, that works, thanks, I keep on forgetting that locals() exists! From castironpi at gmail.com Thu Aug 28 14:51:31 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 28 Aug 2008 11:51:31 -0700 (PDT) Subject: Problem with list.insert References: Message-ID: On Aug 28, 11:13?am, SUBHABRATA wrote: > Dear Group, > I wrote one program, > There is a dictionary. > There is an input string. > Every word of input string the word is matched against the dictionary > If the word of input string is matched against the dictionary it gives > the word of the dictionary. > But if it does not find it gives the original word. > After searching the words are joined back. > But as I am joining I am finding the words which are not available in > dictionary are printed in the last even if the word is given in the > first/middle. > Now, I want to take them in order. > I am applying a thumb rule that the position of the word of the string > is exact with the resultant string. > So, I am determining the word which is not in the dictionary, and its > position in the input string. > Now I am inserting it in the target string, for this I am splitting > both the given string and the output/result string. > Till now it is working fine. > But a problem happening is that if I insert it it is inserting same > words multiple times and the program seems to be an unending process. > What is the error happening? > If any one can suggest. > The code is given below: Warning, -spoiler-. Instead split up your inputs first thing. trans= { 'a': 'A', 'at': 'AT', 'to': 'TO' } sample= 'a boy at the park walked to the tree' expected= 'A boy AT the park walked TO the tree' sample_list= sample.split( ) for i, x in enumerate( sample_list ): if x in trans: sample_list[ i ]= trans[ x ] result= ' '.join( sample_list ) print result assert result== expected Then replace them as you visit each one, and join them later. From steve at REMOVE-THIS-cybersource.com.au Fri Aug 22 21:54:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 23 Aug 2008 01:54:00 GMT Subject: Should Python raise a warning for mutable default arguments? References: <00becb2d$0$20312$c3e8da3@news.astraweb.com> <6h8hhhFk2gamU1@mid.uni-berlin.de> Message-ID: <00bf687f$0$20312$c3e8da3@news.astraweb.com> On Fri, 22 Aug 2008 14:39:11 -0700, Emile van Sebille wrote: > Dan wrote: >> I'd suggest that at the >> end of the tutorial, when people have a better general idea of how >> Python works, there would be a Python Gotchas section. >> >> > Hmmm, OK -- mutable defaults, integer division, name mangling... > > I'd think decimal precision is more a general problem than a python > problem, but still one that throws newbies... > > Any other ideas for gotcha's (as opposed to faqs)? Augmented assignment: x ?= y is not always the same as x = x ? y. Repeated string addition can be very slow. For that matter, so can list addition. Inserting at the beginning of lists is slow. Everything about unicode is a Gotcha! *wink* Raw strings are not designed for Windows paths, they're designed for regexes. Consequently, you can't write the following: r'C:\dir\' list.sort() and list.reverse() return None. sorted() returns a list, but reversed() returns an iterator. urllib2.urlopen() will automatically detect the proxy in your environment and use that. That's usually a feature, but sometimes it can be a gotcha. urllib2 doesn't work well with some HTTPS proxies. This is, I believe, a known bug, but until it is fixed, it can be a gotcha. -- Steven From josiah.carlson at gmail.com Tue Aug 5 12:18:52 2008 From: josiah.carlson at gmail.com (Josiah Carlson) Date: Tue, 5 Aug 2008 09:18:52 -0700 (PDT) Subject: Questions about asyncore References: <5d30aad5-cad7-4e47-aa83-277202c70ae2@z72g2000hsb.googlegroups.com> Message-ID: <85afa6f5-431b-42ee-bd31-de5321b0b0f9@l33g2000pri.googlegroups.com> On Jul 29, 4:09?am, Frank Millman wrote: > Hi all > > I have been using my own home-brewed client/server technique for a > while, using socket and select. It seems to work ok. The server can > handle multiple clients. It does this by creating a new thread for > each connection. Each thread runs its own select loop. > > I am making some fairly big changes, so I thought I would look atasyncore. I modified my program to useasyncorewithout much trouble, > and it feels nicer. It uses async I/O instead of threading, and it > relieves me of having to run my own select loop. > > I have two questions. They both relate to whether I am using the > module as intended. The documentation is rather sparse, and I know > from experience that just getting something working is no guarantee > that I am getting the full benefit. > > Firstly, having gotasyncoreworking, I had a look at asynchat. As far > as I can see I get very little benefit from using it. I have already > set up a 'messaging' protocol between server and client, where all > messages consist of 5 digits for the message length, followed by the > message. The message consists of a pickled tuple, where the first > element is a message identifier, and the rest is the message body. > > This is how it works inasyncore- > > ? ? def __init__(self,channel): > ? ? ? ? [...] > ? ? ? ? self.msgLength = 0 > ? ? ? ? self.recvData = '' ?# temporary buffer > > ? ? def handle_read(self): > ? ? ? ? self.recvData += self.recv(8192) > ? ? ? ? if not self.msgLength: > ? ? ? ? ? ? if len(self.recvData) < 5: ?# 1st 5 bytes = msg length > ? ? ? ? ? ? ? ? return > ? ? ? ? ? ? self.msgLength = int(self.recvData[:5]) > ? ? ? ? ? ? self.recvData = self.recvData[5:] > ? ? ? ? if len(self.recvData) < self.msgLength: > ? ? ? ? ? ? return > ? ? ? ? data = loads(self.recvData[:self.msgLength]) > ? ? ? ? self.recvData = self.recvData[self.msgLength:] > ? ? ? ? self.msgLength = 0 > ? ? ? ? [handle data] > > This is how I got it working in asynchat - > > ? ? def __init__(self,channel): > ? ? ? ? [...] > ? ? ? ? self.recvData = '' ?# temporary buffer > ? ? ? ? self.set_terminator(5) > ? ? ? ? self.gotMsgLength = False > > ? ? def collect_incoming_data(self, data): > ? ? ? ? self.recvData += data > > ? ? def found_terminator(self): > ? ? ? ? if self.gotMsgLength: ?# what follows is the message > ? ? ? ? ? ? data = loads(self.recvData) > ? ? ? ? ? ? self.set_terminator(5) > ? ? ? ? ? ? self.gotMsgLength = False > ? ? ? ? ? ? [handle data] > ? ? ? ? else: ?# what follows is the message length > ? ? ? ? ? ? self.set_terminator(int(self.recvData)) > ? ? ? ? ? ? self.gotMsgLength = True > ? ? ? ? self.recvData = '' > > It may be slightly neater, but it does not seem worth adding an extra > layer just for that. Does asynchat give me any other benefits I may > have overlooked? Giampaolo already offered up some information, but I will offer these two little tidbits: In your first client, your handle_read doesn't handle the case where you have received multiple packets at one time. That is, imagine that in your one .read(8192), you received exactly two messages (the prefix length and the pickle itself times two). The first pass will pick up the message and handle the data. But unless the socket becomes readable again, the second message will never be processed. And even if the socket becomes readable immediately in the next select() call, the message will be delayed depending on what other sockets are up to. The asynchat module handles that case just fine. As for push() vs. send(); send() returns the number of bytes sent. If it sends less than the total block of data (which can be the case with large blocks of data, small TCP/IP windows over a slow connection, or small TCP/IP buffers), you need to be aware of it and attempt to resend the remaining. Again, the asynchat module handles that case just fine with it's .push() method; when it returns, you know that the data to be transferred will be transferred as long as the connection stays alive. Without .push(), you need to implement that behavior yourself (less boilerplate for every subclass = easier maintenance). (I normally don't hop on this list to comment, so please cc me on any replies) - Josiah > My second question relates to writing a dummy client program to test > the server. I just want to send it some messages and print the > responses. Some messages incorporate data extracted from previous > responses, so I have to wait for the reply before continuing. > > I am usingasyncorefor this as well. However, the only way I can > think of to get it working is to runasyncore.dispatcher in a separate > thread. > > To send messages, I append them to a list of messages to be sent. The > dispatcher method writable() returns True if there is anything in the > list, else False. > > To receive messages, I run a 'while 1' loop in the main thread, with a > sleep of 0.1, until recvData has something in it. > > It works, but it seems odd to use a separate thread, as one of th > points ofasyncoreis to avoid multi-threading. Is there a better way > to write the client program? > > Thanks > > Frank Millman From wuwei23 at gmail.com Sun Aug 24 06:00:04 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 24 Aug 2008 03:00:04 -0700 (PDT) Subject: property() usage - is this as good as it gets? References: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> Message-ID: castironpi wrote: > and we'll write Python. I haven't seen anything you've contributed to this group that would so far be considered well-written Python. Confusing and border-line insane, yes. Pythonic? Not at all. Here's a tip: try actually developing some real-world application in Python for a while, rather than the god-knows-what-you're-doing attempts that you keep hijacking various threads with. Your code isn't anywhere near as clever as you seem to think. From Ross at no.thanks.spammers Tue Aug 26 14:51:52 2008 From: Ross at no.thanks.spammers (RgeeK) Date: Tue, 26 Aug 2008 14:51:52 -0400 Subject: Unexpected global variable behaviour In-Reply-To: References: <48b3121c@news.alcatel.com> Message-ID: <48b450c8$1@news.alcatel.com> Thanks a lot Fredrik, A big wave of deja vu came over me as I read your note. That bit me once before, and was my only previous run-in with the 'global' directive which clearly didn't stick with me. :( Thanks for the concise, helpful reply. The universe makes sense again. -Ross. Fredrik Lundh wrote: > http://docs.python.org/ref/naming.html > > "If a name binding operation occurs anywhere within a code block, all > uses of the name within the block are treated as references to the > current block. This can lead to errors when a name is used within a > block before it is bound." > > to fix this, use the global directive: > > http://docs.python.org/ref/global.html > > def OnOutfileButton(self,evt): > global outXMLfile # flag variable as global > fPath, fName = os.path.split(fullName) > print "Selected output file:", fName > outXMLfile = fName > ... > > > From bugtrack at roumenpetrov.info Mon Aug 18 20:53:17 2008 From: bugtrack at roumenpetrov.info (Roumen Petrov) Date: Tue, 19 Aug 2008 03:53:17 +0300 Subject: cross-compilation In-Reply-To: <489b0adb$0$9718$9b622d9e@news.freenet.de> References: <489b0adb$0$9718$9b622d9e@news.freenet.de> Message-ID: <48AA197D.5060504@roumenpetrov.info> Martin v. L?wis wrote: >> What about to start to resolve issues step by step ? > > The first step surely should be to get the autoconf issue resolved. > > I don't think distutils cross-compilation is going to work, instead, > people wishing to cross-compile should edit Modules/Setup. > > Regards, > Martin Please find attached file "python-2.5.2.patch-CROSS". Note that this is "proof of concept" unified diff only for configure.in to show only some changes required for cross-compilation: - added macro AC_CANONICAL_HOST: this require files config.guess and config.sub to be copied to top source directiory. The files can be obtained from GNU automake distribution. In my test I use files from automake 1.10.1. - makefile conditional: the idea is to use in makefiles. It seems to me that build for PGEN (Parser from Makefile.pre.in) has to be suppress in case of cross-compilation as example (without related changes): ========= # Parser @CROSS_OFF at PGEN= Parser/pgen$(EXE) ========= - search for python in build system: usually in the cross environment we cann't run just build python executable we may use existing interpreter as example in Makefile.pre.in: ========= @CROSS_ON at RUNPYTHON= HOST_OS=@HOST_OS@ @SYSPYTHON@ @CROSS_OFF at RUNPYTHON= $(RUNSHARED) ./$(BUILDPYTHON) ========= - $ac_sys_system vs $host: the attached diff show how to detect host system. The existing detection (variable $ac_sys_system) isn't suitable for cross-environment. - ar program : macro AC_CHECK_TOOLS replace AC_CHECK_PROGS. for more details see autoconf texinfo page. - detection of files: skip detection in cross-env. and by default assume that file don't exists. This is minimal change and I think that we has to use macro AC_CHECK_FILE and in cross-env. to warn user but this require more changes. - creation of files from configure script (note this is not related directly to cross compilation): the script is changed to use macros AC_CONFIG_COMMANDS{_PRE}, i.e. more autoconf friendly. I would like to know what is acceptable for above changes ? (note that changes for mingw are only to show idea how to get host system and i will exclude from final patch ). Also how to proceed ? Must I open new issue and to mark that as example 1597850 depend from new one ? What is preferred patch: against trunk, release2.5 or both ? Roumen -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: python-2.5.2.patch-CROSS URL: From pavlovevidence at gmail.com Fri Aug 1 00:19:21 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 31 Jul 2008 21:19:21 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> <5a0b303a-8324-4eeb-a975-397371bf2875@b1g2000hsg.googlegroups.com> Message-ID: <9f920209-3080-470a-817b-9afadbecc453@j22g2000hsf.googlegroups.com> On Jul 31, 11:44 pm, Carl Banks wrote: [snip excellent explanation of why it's hard to for "if x" to be extensively polymorphic] By the way, one thing I forgot to mention is Matt Fitzgibbons' filter example. As I said, it's hard to write code that works for both numeric and container types because they share so few methods. However, sometimes you don't know ahead of time what methods are used! When you're doing functional programming you might pass in a method that calls the appropriate method, like so: def apply_if_true(func,x): if x: func(x) The function f could use methods appropriate for ints when x is an int, and for lists when x is an int. I did downplay this, because frankly, not many programmers use functional methods this extensively. But one should also note that you could pass in the test as well: def apply_if_condition(func,cond,x): if cond(x): func(x) Thus this usage of "if x" arguably could be considered "replaceable with a simple explicit test". But in the interests of harmony I didn't push the point, and it really would have been stretching the spirit of what I was trying to prove. Carl Banks From claird at lairds.us Mon Aug 18 11:43:40 2008 From: claird at lairds.us (Cameron Laird) Date: Mon, 18 Aug 2008 15:43:40 +0000 Subject: AOP in Python References: Message-ID: In article , Kay Schluehr wrote: >On 18 Aug., 15:21, Hussein B wrote: >> Hey, >> AOP is build in Groovy language via many means, does Python support >> AOP out of the box without the need for such >tools:http://pythonsource.com/open-source/aspect-oriented-frameworks >> Thanks. > Kay, I couldn't find anything at that URL, but the closely-related works better in my experiments. also might interest the original poster. My personal bias is that AOP mostly compensates for defects in Java, and contributes little to Python. I retain this prejudice despite the respect I have for two people who are very good programmers and enthralled by AOP. From jasper at peak.org Mon Aug 18 05:59:46 2008 From: jasper at peak.org (Jasper) Date: Mon, 18 Aug 2008 02:59:46 -0700 (PDT) Subject: Bizarre method keyword-arg bug. References: Message-ID: <5c6de13e-2785-498e-9602-d156f15f1205@79g2000hsk.googlegroups.com> On Aug 18, 2:40 am, Fredrik Lundh wrote: > Jasper wrote: > > Uggg! /That's/ an intuitive side-effect/wart. :-/ > > it's done that way on purpose, of course, because evaluating a full > closure for each default argument at every call would greatly hurt > performance (and lead to another set of surprises, of course). > > please don't label things that you don't understand and haven't spent > any time reflecting over as bugs or warts; that's disrespectful to the > designers and probably not good for your blood pressure. > > I understand it's done that way on purpose, and that there are tradeoffs involved, but frankly your /guess/ that I don't understand is wrong. Having used Python for some 15 years, I'm hardly a neophyte -- it's pure serendipity that this hasn't bitten me before. I can see the elegance from a language design perspective, the speed advantage, etc. Nonetheless, it's an unintuitive wart, hurting Python's clarity -- as evidence I'll point out all the warnings that need to be sprinkled through the various docs. And no, the alternative /does not/ have an equivalent set of surprises -- it's not like Python is unique in having default arguments. Frankly, if I wanted speed, I wouldn't be using python, and if I wanted clever tricks, I'd use Perl. Surprise caching as a side-effect is /very/ Perl-like. -Jasper From pavlovevidence at gmail.com Fri Aug 1 13:54:53 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 1 Aug 2008 10:54:53 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> <5a0b303a-8324-4eeb-a975-397371bf2875@b1g2000hsg.googlegroups.com> <9f920209-3080-470a-817b-9afadbecc453@j22g2000hsf.googlegroups.com> Message-ID: <2a56bffc-6c11-474d-b2b1-ca344ff94f09@x41g2000hsb.googlegroups.com> On Aug 1, 8:49 am, Matthew Fitzgibbons wrote: > Carl Banks wrote: > > On Jul 31, 11:44 pm, Carl Banks wrote: > > [snip excellent explanation of why it's hard to for "if x" to be > > extensively polymorphic] > > > By the way, one thing I forgot to mention is Matt Fitzgibbons' filter > > example. > > > As I said, it's hard to write code that works for both numeric and > > container types because they share so few methods. However, sometimes > > you don't know ahead of time what methods are used! When you're doing > > functional programming you might pass in a method that calls the > > appropriate method, like so: > > > def apply_if_true(func,x): > > if x: > > func(x) > > I find myself doing things like this surprisingly often. All you've done > is move the decision as to what function is applied to x elsewhere. Like > a factory, for example. I could see using something like this where func > prepares object x to be inserted into a database, and you want to make > sure x is meaningful first. > > def add_to_db(prep_func, x): > if x: > entry = prep_func(x) > add_to_db(entry) > > 'if x' strikes me as better for this case because you might want to > accept a non-empty list (or some other objects) but reject non-empty > lists. 'if x is None' would not work. It still may be susceptible to the > empty iterator problem, depending on what prep_func does. What if what you consider to be "meaningful" doesn't happen to coincide with what Python considers to be "something". For instance, what if being non-negative is what makes an integer meaningful? You can't use "if x" for that. What if any list, including an empty one, is meaningful, but you want to indicate the possibility of an unmeaningful value by passing None? You can't use "if x" for that. So, you might address this issue by doing something like this: def add_to_db(prep_func, is_meaningful, x): if is_meaningful(x): entry = prep_func(x) add_to_db(entry But if you do that, what has the polymorphism of "if x" gained you? The thing it gained for you before is not having to pass in a condition: whether x was a sequence, number, or whatever, the same condition could be used, and thus you avoided considerable complexity. But if you have to perform tests for which the implicit boolean doesn't work, that complexity has to be added to the code anyway. That matters in the context of this discussion because it limits the usefulness of the polymorphism of "if x" for this functional idiom: "if x" only helps you if you have no need for tests that it can't handle. [snip] Carl Banks From dlenski at gmail.com Fri Aug 15 16:52:36 2008 From: dlenski at gmail.com (Dan Lenski) Date: Fri, 15 Aug 2008 20:52:36 GMT Subject: negative numbers are not equal... References: <48A4932F.4010302@gmail.com> Message-ID: On Fri, 15 Aug 2008 08:03:23 -0700, Carl Banks wrote: > On Aug 14, 4:42?pm, Christian Heimes wrote: >> Integers >> between -5 and +256 are singletons as are some other objects like >> strings with one element or empty tuples. > > Not quite. > > Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) [GCC 4.2.4 (Debian > 4.2.4-1)] on linux2 Type "help", "copyright", "credits" or "license" for > more information. >>>> a = 'A' >>>> b = "%c" % a >>>> a > 'A' >>>> b > 'A' >>>> a is b > False Wow... wow wow. How very odd. That is one exception I did not expect, especially considering that string-formatting with a *literal* rather than a variable gives the opposite result. >>>> a = 'A' >>>> b = "%c" % 'A' >>>> a > 'A' >>>> b > 'A' >>>> a is b > True >> You must not rely on the >> optimization. > > Good advice. Indeed! Corner cases like the above will bit you in the ass ;-) Simple rule of thumb: use "is" when you really truly want to check if two symbols refer to the same object in memory. If that's not what you *really* want to do, then don't use it! Dan From gminick at bzt.bzt Mon Aug 18 17:43:43 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Mon, 18 Aug 2008 21:43:43 +0000 (UTC) Subject: searching through a string and pulling characters References: Message-ID: On Mon, 18 Aug 2008 13:40:13 -0700 (PDT), Alexnb wrote: > Now, I am talking 1000's of these. I need to do something like this. I will > have a number, and what I want to do is go through this text file, just like > the example. The trick is this, those "()'s" are what I need to match, so if > the number is 245 I need to find the 245th () and then get the all the text > from after it until the next (). If you have an idea about the best way to > do this I would love your help. If you made it all the way through thanks! > ;) findall comes to mind: >>> a="""(string1) ... (string2) ... (string3) ... (string4) ... (string5) ... (string6)""" >>> import re >>> pat = re.compile("(\(.*?\))") and now let's say you want to get fourth element: >>> pat.findall(a)[3] '(string4)' To save some memory use finditer (as long as you don't have to search for too many of these): >>> for i in enumerate(pat.finditer(a)): ... if i[0] == 2: ... print i[1].group() ... (string3) >>> -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From hubaghdadi at gmail.com Sun Aug 24 06:07:47 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Sun, 24 Aug 2008 03:07:47 -0700 (PDT) Subject: Best way to set/get an object property Message-ID: Hey, I noted that Python encourage the usage of: -- obj.prop = data x = obj.prop -- to set/get an object's property value. What if I want to run some logic upon setting/getting a property? What is Python preferred method to do so (using the new feature 'property')? I don't think __getattr__ and __setattr__ are practical (I have to code the property name into them). Thanks. From michele.simionato at gmail.com Sat Aug 9 01:55:02 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 8 Aug 2008 22:55:02 -0700 (PDT) Subject: Class definition attribute order References: <5fb776ae-e3d7-49ec-9ebf-350b9bf9cac1@l42g2000hsc.googlegroups.com> Message-ID: <64ce3665-c76a-4ee1-b7cf-be5eef7e793f@z72g2000hsb.googlegroups.com> On Aug 5, 5:05?am, Michele Simionato > Yep. Seehttp://stacktrace.it/articoli/2008/01/metaclassi-python-3000 > (I am working on an English translation these days, > but for the moment you can use Google Translator). > > ?M. Simionato FWIW, I have just finished translating the first part of the article and I have posted it on my blog on Artima: http://www.artima.com/weblogs/viewpost.jsp?thread=236234 From theller at python.net Tue Aug 26 15:05:52 2008 From: theller at python.net (Thomas Heller) Date: Tue, 26 Aug 2008 21:05:52 +0200 Subject: logging - how to use in a library? Message-ID: <6hj2ggFmbgutU1@mid.individual.net> I'm using the logging module in my comtypes library to log 'interesting' things that happen. In other words, the idea is if the user of the library is interested in the details that happen in the package internally, he (she?) would configure a logging level and handlers that write the log messages where it is convenient. This works great, with one exception: If the script using the library does NOT configure logging, and somewhere the library calls logger.error(...) or logger.critical(...) then he gets a message on stderr saying: No handlers could be found for logger "foo" Of course this can be avoided by configuring a NULL-Handler, or raising the loglevel to a very high value - but why is this necessary? I would assume that if no handlers are configured than simply the logging package should not output anything... Why does logging insist on a default level of ERROR even if unconfigured, and why does it insist to output something even if no handler is defined? I assume it would not be a good idea to configure logging in the library itself, possibly overwriting explicit configuration that the user has done... I don't get it. Thomas From bdesth.quelquechose at free.quelquepart.fr Thu Aug 7 16:27:09 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 07 Aug 2008 22:27:09 +0200 Subject: Create a short way to save typing script over and over.... In-Reply-To: References: Message-ID: <489b5aa8$0$15495$426a34cc@news.free.fr> frankrentef a ?crit : > I have a statement "url = 'http://xyzserver/'" so in my code every > time I need to use xyzserver I state "url +...." > > What I' m now trying to do is create a call to a login process. The > script for the login process is below. I'd like to call "adminlogin" > and not have to keep entering the same several lines of script each > and everytime (I'm testing various login functions and rule changes.) > > I'm a newbie, can someone walk me through this? I guess there's a section about functions somewhere in the tutorial ? > > > > #Login to ISeDeposit Admin > > ie.navigate (url + 'isweb/admin/default.aspx') > ie.textBoxSet ('AdminLogin1:Username','Admin') > ie.textBoxSet ('AdminLogin1:inputPassword','Password') > ie.buttonClick ('AdminLogin1:btnLogin') From info at thegrantinstitute.com Fri Aug 29 01:38:33 2008 From: info at thegrantinstitute.com (Anthony Jones) Date: 28 Aug 2008 22:38:33 -0700 Subject: Professional Grant Proposal Writing Workshop (September 2008: British Columbia Institute of Technology - Vancouver Campus) Message-ID: <20080828223832.3C0E1B954C78B6E6@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From mtobis at gmail.com Thu Aug 14 18:46:28 2008 From: mtobis at gmail.com (Michael Tobis) Date: Thu, 14 Aug 2008 15:46:28 -0700 (PDT) Subject: precedence of [] vs . Message-ID: <48390979-4759-43de-967c-8d9b712b61f7@l42g2000hsc.googlegroups.com> I wrote some code to test the precedence of getitem vs getattr; it shows that getitem binds tighter. I have been handed some code that relies on the observed behavior. However, the Nutshell precedence list claims the opposite. Is the Nutshell wrong or am I missing something or is this a bug? class a(object): def __getitem__(self,item): return str(item)[:-1] class b(object): def __getattr__(self,item): return str(item)[::-1] Albert = a() print Albert['abcd'] # prints 'abc' Barney = b() print Barney.abc # print 'cba' print Barney.Albert['abcd'] # raises TypeError; tries to evaluate 'treblA'['abcd'] # I expected 'cba' based on Nutshell 2d Ed p 50 From exarkun at divmod.com Wed Aug 20 10:46:26 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 20 Aug 2008 10:46:26 -0400 Subject: simple Question about using BeautifulSoup In-Reply-To: <19069980.post@talk.nabble.com> Message-ID: <20080820144626.29191.661506875.divmod.quotient.16680@ohm> On Wed, 20 Aug 2008 07:33:32 -0700 (PDT), Alexnb wrote: > >Okay, I have used BeautifulSoup a lot lately, but I am wondering, how do you >open a local html file? > >Usually I do something like this for a url > >soup = BeautifulSoup(urllib.urlopen('http://www.website.com') > urllib.urlopen gives you a file-like object for a resource at an url. file gives you a file-like object for a file on the local filesystem. soup = BeautifulSoup(file('/the/name/of/the/file')) Jean-Paul From jimgardener at gmail.com Thu Aug 28 11:35:07 2008 From: jimgardener at gmail.com (jimgardener) Date: Thu, 28 Aug 2008 08:35:07 -0700 (PDT) Subject: cannot find object instance Message-ID: <6b8a855f-8ff4-41f8-87f1-1b832368dd83@v16g2000prc.googlegroups.com> hi, i am a python newbie..while trying out some message passing between two object instances i came across a problem moduleA.py -------------------- import moduleB class MyClassA: def __init__(self): self.age=0 self.address='' def createClassB(self): self.objB=moduleB.MyClassB() def validate(self,age,address): if(age >= 100 or address==''): self.age=20; self.address="Broadway,NewYork" self.objB.display(self.age,self.address) def callB(self): self.objB.execute() if __name__ == "__main__": objA=MyClassA() objA.createClassB() objA.callB() moduleB.py ------------------ import moduleA class MyClassB: def __init__(self): self.createA() def createA(self): self.objA=moduleA.MyClassA() def execute(self): self.objA.validate(111,'') def display(self,age,address): print 'displaying:',str(age),address when i run the code i get a message AttributeError: MyClassA instance has no attribute 'objB' Do i have to put a placeholder for objB in __init__ of MyClassA ? is that why i get this error?someone please tell me how i can solve this? I tried to put self.objB=None but it didn't work..(i was thinking of java style objB=NULL ) please help thanks jim From rschroev_nospam_ml at fastmail.fm Sun Aug 31 18:43:52 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 01 Sep 2008 00:43:52 +0200 Subject: (in memory) database In-Reply-To: References: Message-ID: Cameron Laird schreef: > I now suspect that my 2.5 packaging has something to do with 64-bit builds; > all my 32-bit Ubuntu servers have Python 2.5.2, while the 64-bit ones are at > Python 2.5. Strange: my 64-bit Ubuntu 8.04 has Python 2.5.2, with working sqlite: roel at shannon $ uname -a Linux shannon 2.6.24-19-generic #1 SMP Wed Aug 20 17:53:40 UTC 2008 x86_64 GNU/Linux roel at shannon $ cat /etc/issue Ubuntu 8.04.1 \n \l roel at shannon $ python Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From israelu at elbit.co.il Mon Aug 4 15:06:58 2008 From: israelu at elbit.co.il (iu2) Date: Mon, 4 Aug 2008 12:06:58 -0700 (PDT) Subject: What Python looks like Message-ID: Hi, This is a little bit strange post, but I'm curious... I learned Python from its tutorial step by step, and practicing writing small scripts. I haven't seen a Python program before knowing Python. I'm curious, what did Python code look like to those of you who have seen a bunch of Python code for the first time before knowing Python? (I can tell, for example, that seeing perl for the first time looked like C with many $$$, I could see "if" and "for" and "while" but they were meaningless. Or Lisp for the first time looked like many words, no operators, how could that make a program???) Thanks From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 18 03:27:33 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 18 Aug 2008 09:27:33 +0200 Subject: print "%s" In-Reply-To: References: Message-ID: <48a92465$0$847$426a74cc@news.free.fr> Cameron Simpson a ?crit : > On 18Aug2008 11:58, Beema Shafreen wrote: > | In my script i have to print a series of string , so > | > | print "%s\t%s\t%s\t%s\t%s\t%s\t" %("a","v","t","R","s","f") > | > | I need to know instead of typing so many %s can i write %6s in python, as > | we do in C progm. > > I hate to tell you this, but "%6s" in C does NOT print 6 strings. It > prints 1 string, right justified, in no less that 6 characters. > C is just like Python in this example. > > | What are the other options . > > Write a small loop to iterate over the strings. Print a tab before each > string except the first. Or use the str.join method: print "\t".join(list("avtRsf")) From tjreedy at udel.edu Fri Aug 15 15:00:39 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 15 Aug 2008 15:00:39 -0400 Subject: negative numbers are not equal... In-Reply-To: References: Message-ID: Mel wrote: > castironpi wrote: >> It would be nice to put together a really canonical case of the use of >> the 'is' comparison. FTSOA for the sake of argument, when do you use >> it? Why is it even in the language? > > My poster child use case is in a MUDD game. For instance, the player > represented by `this_player` has picked up the yoghurt. We notify the > other players using code that boils down to: > > for person in this_room.inhabitants: > if person is not this_player: > person.notify ('%s has picked up the %s.' > % (this_player.name, 'yoghurt')) > > The `is` test avoids telling this_player something he already knows. > Perhaps the code could be written to make an equality test work, but then > again, perhaps the game could have a much more interesting use for equality > between persons. Excellent example. There are three uses for 'is'. 1. Minor optimization of comparison with None, True, False. 2. Testing the implementation: 'a=1;b=1;a is b' *should* be True, while 'a=257;b=257;a is b' *should* be False. The CPython test suite has tests like this. 3. Comparision of user class objects where identify is important. Objects representing people is certainly such a case ;-). tjr From PaulAlexWilson at gmail.com Mon Aug 4 05:48:34 2008 From: PaulAlexWilson at gmail.com (Wilson) Date: Mon, 4 Aug 2008 02:48:34 -0700 (PDT) Subject: Limits of Metaprogramming Message-ID: <0c56829a-7ad2-4ff2-b225-7981538e7c7a@j22g2000hsf.googlegroups.com> Hi all, I have an interesting problem that I'm hoping can be solved with metaprogramming, but I don't know how far Python supports code generation (and I don't know if I'm taking the correct approach either... hence why I'm asking on this group): I'd like to write a program that writes/manipulates a statemachine. My idea was that I would define states in a .py file along with their transitions and other metadata. I could then write a suite of programs that would manipulate these states in interesting ways, such as generate diagrams and documentation, test suites, do verifications and also edit them. These programs would import the .py file and use introspection upon the module's classes (states would be modelled as classes). For example, a documentation tool could use graphviz to draw the statediagram with the transition table and docstring... My problem is that I don't know if it's possible to edit these states and then write them back to .py. Firstly, if my editing tool was to create a new state, I would want to create the class (using type) and attach it to the imported state module somehow. I can't find information on whether this is possible. Secondly, I'd like to manipulate the class and then use the inspect module to get the source and write it back to file. Now I'm pretty sure the inspect module will only write the source code as found in the original .py file. Is there a way to generate the code for a class or other python objects in a generic way? Or will I have to bite the bullet and write to custom file and generate code from that (like glade with XML)? Or is there another solution with templates that I'm over looking? Having the classes in memory, editing their attributes, adding methods and then serialising them to code has an elegance to it in my mind and would hopefully simplify things. The result would be directly executable by the interpreter itself and editable by python developers. But I fear that I may need an intermediary notation/format for storage. Any advice/hints would be very useful. Thanks, Paul From Scott.Daniels at Acm.Org Sat Aug 23 11:37:55 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 23 Aug 2008 08:37:55 -0700 Subject: __eq__ problem with subclasses In-Reply-To: References: Message-ID: Daniel Israel wrote: > I am very confused by the following behavior. > > I have a base class which defines __eq__. I then have a subclass > which does not. When I evaluate the expression a==b, where a and b > are elements of these classes, __eq__ is always called with the > subclass as the first argument, regardless of the order I write my > expression. I can't see why this would be desired behavior. This is the quickest way to make sure that an over-ridden __eq__ gets called (that is, before the __eq__ is looked up, it asks, in this comparison of a and b (where type(a) == A and type(b) == B), is A != B and (A a subclass of B or B a subclass of A)? If so, there is one object of a more general type (the superclass), and one object of a more specific type (the subclass). If you have this situation, the more specific class _may_ have over-ridden the comparison method (in this case __eq__) of the more general class. We want to use the more specific comparison in such cases (as the subclass may have a way of folding in extra data into the comparisons in a way the general could not). However, without looking up the comparison method in the more specific subclass, you don't know whether or not there _is_ an over-riding method. Once you have done the work of the method lookup for one of the objects (which you must do to determine whether you _need_ to evaluate in a "special" order), the decision becomes, "Do we then throw away the work we did looking up the comparison method on one arg and compute a comparison on the other arg?" The cost of allowing the expression order to determine the call made when no comparison override is provided would be more computation before finally dispatching on the method. Would you want to slow down the comparison to get the behavior you seem to want? --Scott David Daniels Scott.Daniels at Acm.Org From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 26 04:51:32 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 26 Aug 2008 10:51:32 +0200 Subject: Total No. of "Records" in a File? In-Reply-To: <2MZrk.11343$vn7.9349@flpi147.ffdc.sbc.com> References: <1JXrk.20070$89.12375@nlpi069.nbdc.sbc.com> <2MZrk.11343$vn7.9349@flpi147.ffdc.sbc.com> Message-ID: <48b3c3e4$0$30971$426a74cc@news.free.fr> W. eWatson a ?crit : > Fredrik Lundh wrote: >> W. eWatson wrote: >> >>> I have an ordinary text file with a CR at the end of a line, and two >>> numbers in each line. Is there some way to determine the number of >>> lines (records) in the file before I begin reading it? >> >> In the general case, no. A file is just a bunch of bytes. If you >> know that all lines have exactly the same length, you can of course >> fetch the file size and divide by the line size, but that doesn't work >> for arbitrary files. >> >> Why do you need to know the number of lines before reading it, btw? >> >> >> > Actually, it was a matter of curiosity, and maybe absent mindedness. I > was envisioning a program where I might want to run up and down a file a > lot, sometimes deleting a record interactively at the request of the > user. However, I wanted to keep him alert to the total number of records > remaining. However, in retrospect, I more likely do this with files in a > folder. I also want him to be able to skip around in the Win OS folder > by saying something like go forward 3 files. I'd like not to have to > read all the files between the two points. The whole idea needs some > more thinking. > The whole idea is that you should learn what a DBMS is good for, IMHO. From ironfroggy at gmail.com Wed Aug 13 11:38:49 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Wed, 13 Aug 2008 11:38:49 -0400 Subject: You advice please In-Reply-To: <48A2FBAC.3000103@wiggly.org> References: <20080813110444.7b48ddbc.darcy@druid.net> <76fd5acf0808130811y7d7d6584m721096295a72af98@mail.gmail.com> <48A2FBAC.3000103@wiggly.org> Message-ID: <76fd5acf0808130838r44590107t3297fb3f38d38f10@mail.gmail.com> God forbid I try to make a joke. On Wed, Aug 13, 2008 at 11:20 AM, Nigel Rantor wrote: > Calvin Spealman wrote: >> >> Ruby (on Rails) people love to talk about Ruby (on Rails). >> >> Python people are too busy getting things done to talk as loudly. > > Have you read this list? > > I would suggest your comment indicates not. > > Throwaway comments like yours that are pithy, emotional and devoid of any > factual content are just the kind of thing that makes lists such as this > less useful than they could be. > > You are acting as a source of noise, not signal. I'm sure you don't want to > be considered in that manner, so perhaps you should think about adding > something to the conversation instead. > > Before you reply please think about what you plan on saying, you'll be > helping not only me but yourself and anyone who reads your post. > > n > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy From gagsl-py2 at yahoo.com.ar Tue Aug 12 01:48:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Aug 2008 02:48:28 -0300 Subject: tkinter, askopenfilename, initial directory References: Message-ID: En Thu, 07 Aug 2008 19:08:56 -0300, Lisa Frauens escribi?: > I see there is an initial directory option in askopenfilename. However, > I want the initial directory to be the last directory used in a prior > execution of my script. Is there a way to force the askopenfilename to > the previous initial directory easily using information somewhere (I > know Windows applications natively do this so you don't have to navigate > all the way back to directory of interest)? It defaults to the current > working directory. or do I have to save this initial directory > somewhere, probably in a *.txt file, when running my script the first > time and then access this *.txt file, and use information as the initial > directory option in askopenfilename, when running the script a > subsequent time? Yes, you should save the last used directory somewhere. Try using ConfigParser. last_used_directory = ... # retrieve from saved options; default = "." filename = tkFileDialog.askopenfilename(initialdir=last_used_directory) if filename is not None: # save the directory: os.path.dirname(filename) ... -- Gabriel Genellina From renesd at gmail.com Tue Aug 5 20:38:53 2008 From: renesd at gmail.com (illume) Date: Tue, 5 Aug 2008 17:38:53 -0700 (PDT) Subject: pygame 1.8.1 released Message-ID: <269c7cc3-990c-4c3c-a735-a7cbaf71c8fe@v13g2000pro.googlegroups.com> Hello, Stick a fork in it, it's baked... nice and toasty. A new version of pygame is out. http://www.pygame.org/ Pygame is a set of Python modules designed for writing games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language. Pygame is highly portable and runs on nearly every platform and operating system. http://www.pygame.org/wiki/about Silliness built in. Does not require OpenGL. Multi core CPUs can be used easily. Uses optimized C, and Assembly code for core functions. Comes with many Operating systems. Truly portable. It's Simple, and easy to use. Many games have been published. You control your main loop. Does not require a GUI to use all functions. Fast response to reported bugs. Small amount of code. Modular. Over 1000 open source games have been released that use pygame, so there are lots of examples to learn from. http://pygame.org/whatsnew.shtml Many bug fixes and improvements, including: * BLEND_RGBA_* blitters and blenders to go with the BLEND_RGB_* blend modes. * documentation updates (mainly for new sprite classes released in 1.8.0) * sound fixes, and streaming some music from file like objects * image saving fixes * greatly expanded tests * Pixelarray, and surfarray updates and fixes. * Enhanced Color class, reimplemented in C for speed. * New Windows and Mac binary installers. See the what's new page for full details http://pygame.org/whatsnew.shtml Many thanks to Marcus, Lenard, Brian, Nicholas, Charlie Nolan, Nirav Patel, Forrest Voight, Charlie Nolan, Frankie Robertson, John Krukoff, Lorenz Quack, Nick Irvine, Zhang Fan and everyone else who helped out with this release. Next release will include the physics engine, Webcam support, enhanced easy and automatic multithread support amongst other goodies -- they have been in development for over 3 months full time so far. cheers, From steve at REMOVE-THIS-cybersource.com.au Sun Aug 3 07:08:07 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 03 Aug 2008 11:08:07 GMT Subject: How to redirect operation methods to some sepcific method easily? References: Message-ID: <00a58cef$0$20331$c3e8da3@news.astraweb.com> On Sun, 03 Aug 2008 02:44:34 -0700, Victor Lin wrote: > Now, here comes the problem : I have to override all the operation > methods, such as __add__ and __mul__. I know the most stupid way is just > to write all of them like this. > > def __add__(self, other): > self.leftOperation('add', other) > > def __mul__(self, other): > self.leftOperation('mul', other) > > But I don't want to do that in this stupid way. I want to use little > code to redirect these operation methods to some specific method with > it's name. > > What can I do? I usually dislike code that uses exec, but this is one place where I'm tempted to make an exception (mainly because I can't think of an alternative). Untested and at your own risk: def factory(name): """Return a method name and a function.""" def func(self, other): return self.LeftOperation(name, other) return "__%s__" % name, func class Parrot(object): for name in ["mul", "add", "sub", "pow"]: # and many more... name, f = factory(name) exec "%s = f" % name del name, f Urrggh. I feel dirty. *wink* -- Steve From fredrik at pythonware.com Mon Aug 18 13:33:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 18 Aug 2008 19:33:53 +0200 Subject: Weird expression result In-Reply-To: <5301eb9b-d282-4d3d-a17e-c3a5220c56fa@m45g2000hsb.googlegroups.com> References: <83803185-725e-45bb-b2fe-1add2868bd34@c58g2000hsc.googlegroups.com> <5301eb9b-d282-4d3d-a17e-c3a5220c56fa@m45g2000hsb.googlegroups.com> Message-ID: cokofreedom at gmail.com wrote: >>>>> 3 in [3] == True > > http://docs.python.org/ref[3/summary.html that page is broken, as recently mentioned; "in", "not in", "is", and "is not" are comparison operators too, chains in the same way as the others. for details, see: http://docs.python.org/ref/comparisons.html#comparisons From tjreedy at udel.edu Tue Aug 5 15:56:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 05 Aug 2008 15:56:02 -0400 Subject: robust optimisation In-Reply-To: References: Message-ID: sh.mojtahedzadeh at gmail.com wrote: > Dear all, > > I have a LP model here as follow: > >... > The constraints > .15*x1 + .2*x2 +.15*x3 >= 100; > .2*x1 + .05*x2 + .2*x3 >= 100; > .25*x1 + .15*x2+ .05*x3 >= 150; > > have uncertainties in x1, x2, and x3 coefficients. I want to know how > can I make a robust optimisation model for this LP model? This has nothing to do with Python. You might get an answer on the scipy mailing list, but you should look for a group of list on numerical optimization, or better one specifically on linear programming, which is a somewhat separate subfield. Or find a book on 'robust optimization', whatever that is. tjr From larry.bates at vitalEsafe.com Tue Aug 26 15:15:40 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Tue, 26 Aug 2008 14:15:40 -0500 Subject: JSON from Python mysqldb In-Reply-To: References: Message-ID: jpuopolo wrote: > All: > > I am using Python to read some records from the MySQL database. I am > using the mysqldb library, and things are working well. > > Now, I would like to pass back the results of the query to a Web-based > front end, and I would like to use JSON. Is there a library/example of > creating a JSON array from a mysqldb row or row set? > > Thanks, > jpuopolo Google turns up several high quality links, just look for 'python json'. -Larry From deets at nospam.web.de Tue Aug 12 11:11:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 12 Aug 2008 17:11:31 +0200 Subject: python interpreter References: <29e59f7a-af87-40b4-9c5e-58abe1a28721@t1g2000pra.googlegroups.com> Message-ID: <6gdnj5Ff5u2rU1@mid.uni-berlin.de> Alexandru Mosoi wrote: > I'm using python's interpreter's to run various commands (like a > normal shell). However if sources are modified changes are not > reflected so I have to restart interpreter. Is there any way to avoid > restarting this? Other gave you advice on how to - partially - achieve this. Let me add that IMHO the better approach is to create a small test-script and let that run. If you want/must have a interactive prompt, python -i test.py as well as import pdb; pdb.set_trace() at an interesting point in your script are your friends. Diez From afriere at yahoo.co.uk Wed Aug 13 02:38:56 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 12 Aug 2008 23:38:56 -0700 (PDT) Subject: os.system question References: <1c5bf$489a4add$4275d90a$15022@FUSE.NET> <80aab1c9-7545-4f9e-b52d-9f72a14b345f@z6g2000pre.googlegroups.com> <00b210a0$0$14351$c3e8da3@news.astraweb.com> Message-ID: <3b2f5c11-e3c9-4e9f-b07a-ae6a39d91b14@j1g2000prb.googlegroups.com> On Aug 13, 8:58 am, Steven D'Aprano wrote: > On Mon, 11 Aug 2008 19:28:13 -0700, Asun Friere wrote: > > > but if I was in a hurry to find out who I was I would be tempted still > > to use the deprecated "os.popen('whoami').read()". > > Is it really deprecated? Since when? I'm using Python 2.5 and it doesn't > raise any warnings or mention anything in the doc string. > I should perhaps have put 'deprecated' in quotation marks? Note the post I was responding to and my own stated preference. Though I admit, I have been trying out Popen just recently. > The current documentation does say: > > "The subprocess module provides more powerful facilities for spawning new > processes and retrieving their results; using that module is preferable > to using this function." > > http://docs.python.org/lib/os-newstreams.html#os-newstreams > > but that's not the same as deprecating os.popen. > Current documentation also states: "[The subprocess] module intends to replace several other, older modules and functions, such as: ... [inter alia] ... os.system, os.popen*, commands.*" http://docs.python.org/lib/module-subprocess.html Which is also not exactly the same thing as deprecating os.popen, but it does sound somehwat more ominous. One hopes the subprocess module is not successful in realising its intentions. I note 3.0 runs os.popen without complaint (and had thought to mention that in my previous). Right now I'm wondering whether I should install the beta 2.6 to see whether Wotjek is pulling our leg or not. :) From tshopshire at gmail.com Thu Aug 28 18:56:49 2008 From: tshopshire at gmail.com (Tyler Shopshire) Date: Thu, 28 Aug 2008 22:56:49 GMT Subject: PyDoc in Vista Message-ID: I can't seem to get Pydoc up and running in windows Vista. I can search for modules manually by using the "pydoc module_name" command but if i try to set up an http server, it says the server is up and running but I can't access it in FF or IE. Any help is appreciated. From alex at a13x.net Fri Aug 29 19:07:04 2008 From: alex at a13x.net (Aleksandar Radulovic) Date: Fri, 29 Aug 2008 23:07:04 +0000 Subject: Can I write a binary windows executable with Python? In-Reply-To: <2e599711-7090-4ce6-b90d-201d1dd627c4@1g2000pre.googlegroups.com> References: <2e599711-7090-4ce6-b90d-201d1dd627c4@1g2000pre.googlegroups.com> Message-ID: <845b10c50808291607x4d947bd4g38aa24a4f6196e5a@mail.gmail.com> Hi, What you're probably referring to is py2exe tool (http://www.py2exe.org/) which creates windows executable programs out of python scripts. Once created, such executable can be run on a Windows machine without Python installed. Psyco, on the other hand, is a tool that greatly optimizes and increases execution speed of python scripts. -alex. On Fri, Aug 29, 2008 at 10:46 PM, walterbyrd wrote: > I have heard about Pysco. But does create a single executable that can > run without Python being installed? Or does that just compile the > libraries? > -- > http://mail.python.org/mailman/listinfo/python-list > -- a lex 13 x From notvalid2 at sbcglobal.net Thu Aug 28 01:02:01 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Wed, 27 Aug 2008 22:02:01 -0700 Subject: Wild Card String Comparison In-Reply-To: References: Message-ID: Sean DiZazzo wrote: > On Aug 27, 8:49 pm, "W. eWatson" wrote: >> Is it possible to do a search for a wild card string in another string. For >> example, I'd like to find "v*.dat" in a string called bingo. v must be >> matched against only the first character in bingo, and not simply found >> somewhere in bingo, as might be the case for "*v*.dat". >> -- >> Wayne Watson (Watson Adventures, Prop., Nevada City, CA) >> >> (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) >> Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet >> >> Web Page: > > Check: > > http://docs.python.org/lib/string-methods.html > http://docs.python.org/lib/module-re.html > http://docs.python.org/lib/module-glob.html > http://docs.python.org/lib/module-fnmatch.html > > ~Sean I'll take a look. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From sjmachin at lexicon.net Mon Aug 4 06:23:45 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 4 Aug 2008 03:23:45 -0700 (PDT) Subject: Nlp, Python and period References: Message-ID: <72742497-f47d-47c3-b43c-8c6dd6a49deb@v39g2000pro.googlegroups.com> On Aug 4, 7:59 pm, Fred Mangusta wrote: > Hi, > > are you aware of any nlp packages or algorithms in Python to spot > whether a '.' represents an end of sentence or rather something else (eg > Mr., f... at home.co.uk, etc)? > google("python nltk") ... it may do what you want. From buzzard at urubu.freeserve.co.uk Sat Aug 30 20:05:41 2008 From: buzzard at urubu.freeserve.co.uk (duncan smith) Date: Sun, 31 Aug 2008 01:05:41 +0100 Subject: Most pythonic way of weighted random selection In-Reply-To: References: Message-ID: Manuel Ebert wrote: > Dear list, > > who's got aesthetic advice for the following problem? I've got some > joint probabilities of two distinct events Pr(X=x, Y=y), stored in a > list of lists of floats, where every row represents a possible outcome > of X and every float in a row a possible outcome of Y (which I will now > call my matrix, altough I can't use numpy or numeric for this), so e.g. > m = [[0.2, 0.4, 0.05], [0.1, 0.05, 0.2]]. All lists in the list are > equally long and the values of the flattened list add up to 1.0, i.e. > sum([sum(row) for row in m]) == 1. In practice, this 'matrix' is about > 20x40, i.e. a list with 20 lists ? 40 floats each. > > Now the task is to select one outcome for X and Y based on the joint > probabilites, and afterwards check that the outcomes fullfill certain > criteria. If it doesn't fulfill some criteria a new pair of outcomes has > to be selected, for other criteria it will still be selected with a > certain probability. My approach was to choose a random number, and then > walk through the list adding the values together until the accumulated > sum is greater than my random threshold: > [snip] For a list of cumulative probabilities you could use the bisect module to find the insertion point for a 0,1 uniform variate (which you could then map back to a cell index). Alternatively you could use an alias table, http://amath.colorado.edu/courses/7400/2004fall/002/Web/SS-10.ppt. You could produce a probability table that takes into account your criteria, so that you don't need to check them. i.e. Each cell that does not satisfy criterion a has probability 0 of being selected. Each other cell has a probability of being selected proportional to its original value if it satisfies criterion b, or its original value * p otherwise. Normalise the resulting values to sum to 1 and you're done with the need to check against criteria. So, preprocess your table, create a corresponding list of cumulative probabilities and use the bisect model (is one possibility). Duncan From gminick at bzt.bzt Fri Aug 22 18:07:24 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Fri, 22 Aug 2008 22:07:24 +0000 (UTC) Subject: Generate alphabet? References: Message-ID: On Fri, 22 Aug 2008 15:02:19 -0700 (PDT), ssecorp wrote: > In Haskell I can do [1..10] for range(1,11) and ['a'..'z'] for a list > of the alphabet. > > Is there a way in Python to generate chars? It's not actually about generating anything, but why should one generate something if it's accessible anyway: import string print string.letters -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From semanticist at gmail.com Tue Aug 5 20:59:03 2008 From: semanticist at gmail.com (Miles) Date: Tue, 5 Aug 2008 20:59:03 -0400 Subject: string to type object (C) In-Reply-To: <4477a269-f189-4ae1-9c97-e78633bb3d27@2g2000hsn.googlegroups.com> References: <4477a269-f189-4ae1-9c97-e78633bb3d27@2g2000hsn.googlegroups.com> Message-ID: On Tue, Aug 5, 2008 at 2:30 AM, castironpi wrote: > I'm looking for a one-to-one function from strings to the built-in > data types in C. I will be keeping the string in a file. I need the > PyTypeObject* back from it. If nothing else I'll just do a bunch of > strcmp( "tuple" ) { return &PyTuple_Type; } commands, provided > &PyTuple_Type; will be linking the right address. Something along the lines of this? b = PyImport_Import("__builtin__"); return PyObject_GetAttrString(b, typestring); -Miles From bj_666 at gmx.net Wed Aug 20 14:57:40 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Aug 2008 18:57:40 GMT Subject: exception handling in complex Python programs References: <48ac4820$0$13097$426a74cc@news.free.fr> Message-ID: <6h37p4Fi5ipbU2@mid.uni-berlin.de> On Wed, 20 Aug 2008 18:37:02 +0200, Bruno Desthuilliers wrote: >> I personally think this is sloppy because you have to couple the >> exception type with the function --- between file() and open() in >> Python 2 and 3, a NameError is thrown with open() in Python 3 > > ??? I suspect this has nothing to do with any error happening while > opening the file. NameError means the name doesn't exists in the current > namespace nor it's enclosing namespaces. Could it be possible that > open() has been removed from Py3k ? No it's moved/changed but there's still a name for it in the builtin namespace. `file` on the other hand is gone: Python 3.0b2 (r30b2:65080, Aug 20 2008, 20:41:17) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> open >>> file Traceback (most recent call last): File "", line 1, in NameError: name 'file' is not defined Ciao, Marc 'BlackJack' Rintsch From __peter__ at web.de Mon Aug 11 12:46:13 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 11 Aug 2008 18:46:13 +0200 Subject: benchmark References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> Message-ID: Kris Kennaway wrote: > Peter Otten wrote: >> M8R-n7vorv at mailinator.com wrote: >> >>> On Aug 10, 10:10 pm, Kris Kennaway wrote: >>>> jlist wrote: >>>>> I think what makes more sense is to compare the code one most >>>>> typically writes. In my case, I always use range() and never use >>>>> psyco. But I guess for most of my work with Python performance hasn't >>>>> been a issue. I haven't got to write any large systems with Python >>>>> yet, where performance starts to matter. >>>> Hopefully when you do you will improve your programming practices to >>>> not make poor choices - there are few excuses for not using xrange ;) >>>> >>>> Kris >>> And can you shed some light on how that relates with one of the zens >>> of python ? >>> >>> There should be one-- and preferably only one --obvious way to do it. >> >> For the record, the impact of range() versus xrange() is negligable -- on >> my machine the xrange() variant even runs a tad slower. So it's not clear >> whether Kris actually knows what he's doing. > > You are only thinking in terms of execution speed. Yes, because my remark was made in the context of the particular benchmark supposed to be the topic of this thread. > Now think about memory use. Now you are moving the goal posts, But still, try to increase the chain length. I guess you'll find that the impact of range() -- in Chain.__init__() at least -- on the memory footprint is also negligable because the Person objects consume much more memory than the tempory list. > Using iterators instead of constructing lists is something > that needs to permeate your thinking about python or you will forever be > writing code that wastes memory, sometimes to a large extent. I like and use an iterator/generator/itertools-based idiom myself, but for "small" sequences lists are quite competitive, and the notion of what a small list might be is constantly growing. In general I think that if you want to promote a particular coding style you should pick an example where you can demonstrate actual benefits. Peter From fredrik at pythonware.com Tue Aug 26 13:11:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 26 Aug 2008 19:11:50 +0200 Subject: Return a string result with out breaking loop In-Reply-To: References: <631fff4c-0332-427f-9a1f-9ce7f47788ff@k7g2000hsd.googlegroups.com> Message-ID: Andrew wrote: > Yield returns the result I am looking for... however it does not > continue looping. It does the same thing as return would the XML-RPC protocol doesn't really support your use case; for each call, the client issues a complete request package, and the server produces a complete response in return. From fredrik at pythonware.com Wed Aug 20 17:50:22 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 20 Aug 2008 23:50:22 +0200 Subject: python custom command interpreter? In-Reply-To: References: Message-ID: joey boggs wrote: > That's kinda what I'm looking for, but it can't be interactive > as there's no way to send input during the installation. > It should pass the DROP statements to the interpreter and the > interpreter takes the input and runs os.rmdir() > or something similar. This way the backend does all the > work and the frontend wouldn't it be easier to use a good old Unix shell for this? or just a stock Python with some boilerplate code? drop("/stuff") drop("/otherstuff") From hubaghdadi at gmail.com Mon Aug 25 08:02:27 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Mon, 25 Aug 2008 05:02:27 -0700 (PDT) Subject: Best way to set/get an object property References: <00c1f394$0$20312$c3e8da3@news.astraweb.com> <7e16a2a7-2712-426e-91c2-48f9b93f587d@34g2000hsh.googlegroups.com> Message-ID: <5c03b2ba-3912-4468-b97d-d521b8e3ec4b@26g2000hsk.googlegroups.com> On Aug 25, 4:31 am, Steven D'Aprano wrote: > On Sun, 24 Aug 2008 23:56:27 -0700, Hussein B wrote: > > On Aug 24, 7:12 pm, Steven D'Aprano > cybersource.com.au> wrote: > >> >> I noted that Python encourage the usage of: -- obj.prop = data > >> >> x = obj.prop > >> >> -- > >> >> to set/get an object's property value. What if I want to run some > >> >> logic upon setting/getting a property? What is Python preferred > >> >> method to do so (using the new feature 'property')? I don't think > >> >> __getattr__ and __setattr__ are practical (I have to code the > >> >> property name into them). > ... > >> I think the actual answer to his question is that properties are the > >> preferred way to "run some logic upon setting/getting" an attribute, > >> that is, to implement getters and setters. > > >> Hussein, the Java habit of writing setters and getters for everything > >> isn't considered good practice in Python, but if you need them, that's > >> exactly what the property() function is for. > > >> -- > >> Steven > > > Thank you Steven :) > > -- > > public class JClass { > > private int answer; // property > > } > > -- > > class PyClass(object): > > doc __init__(self): > > self.answer = None > > -- > > AFAIUY (understand you), what it is called a property in Java, it is > > called an attribute in Python? > > Why Python encourages direct access to object's attributes? aren't > > setters/getters considered vital in OOP (encapsulation)? > > Thank you all for your time and help. > > Hussein, first let me ask you to please stop using "--" as a separator > around code. Many News clients, including mine, expect -- on a line by > itself to mean "everything from here on is the writer's signature", and > consequently that makes it harder to reply correctly to your posts. I had > to manually copy and paste your text in order to quote it. Perhaps you > could use === or +++ or *** as a separator? > > Now, back to your actual question... > > I'm not a Java coder, so the following should be read as my opinion. > Python attributes are equivalent to Java _public_ properties, not > private. If you can write: > > public class JClass { > public int answer; > > } > > then that would be more or less equivalent to Python's > > class PyClass(object): > def __init__(self): > self.answer = None > > Yes, Python does encourage direct access to an object's attributes. The > Python philosophy is "we're all adults here". If coders wish to shoot > themselves in the foot by accessing clearly marked private attributes, > then the language can't stop them and shouldn't try. It's easy to bypass > such private/public protection in C++, and harder, but still possible, in > Java. > > The Python development team is certainly aware that such a tactic > introduces some costs, by reducing encapsulation, but it also has many > benefits (e.g. less boilerplate getter/setter methods, faster development > time). It is their belief that such costs are worth paying in order to > get the benefits. That's the philosophy of the language. Python is not > trying to be Java, and Java should not try to be Python. > > Python does not enforce private attributes. By convention attributes > starting with a single underscore are considered "private -- don't touch > unless you know what you're doing". Attributes starting with a double > underscore are "really private", and Python mangles the name to (almost) > enforce it. > > Example: > > def Parrot(object): > colour = 'red' # public, free to use > _windspan = 15 # semi-private, use it at your own risk > __species = 'Norwegian Blue' # mangled to _Parrot__species > > But it's quite rare to see double-underscore "really private" attributes > in Python code. It is considered to go against the spirit of the language. > > I'm told that in Java it is quite difficult to change a class from using > public attributes to getters/setters, and therefore many Java developers > prefer to use getters/setters right from the beginning. But in Python it > is very easy to change from a bare attribute to a computed property > without messing up calling code. So there's no advantage to writing > something like this: > > class Foo(object): > def __init__(self): > self.__x = None # private attribute > def setx(self, x): # setter > self.__x = x > def getx(self): # getter > return self.__x > x = property(getx, setx) > > That is considered a waste of time in Python circles and is strongly > discouraged. > > You should read "Python Is Not Java" and "Java Is Not Python Either": > > http://dirtsimple.org/2004/12/python-is-not-java.html > > http://dirtsimple.org/2004/12/java-is-not-python-either.html > > -- > Steven Thank you all guys and big thank you Steven, I owe you a beer. Sorry, I wasn't aware of the two dashes problem as I use Google Group/ Reader. comp.lang.python really rocks & much more friendly and useful than comp.lang.ruby From fayuca at gmail.com Thu Aug 14 17:23:21 2008 From: fayuca at gmail.com (ariel ledesma) Date: Thu, 14 Aug 2008 18:23:21 -0300 Subject: negative numbers are not equal... In-Reply-To: References: <48A4932F.4010302@gmail.com> Message-ID: <48A4A249.9060004@gmail.com> Christian Heimes wrote: > You are getting the result because Python optimized small integers. > See http://svn.python.org/projects/python/trunk/Objects/intobject.c > Integers between -5 and +256 are singletons as are some other objects > like strings with one element or empty tuples. You must not rely on > the optimization. > i see now, so i guess that's also why id() returns the same address for them as well... i'll dive into the implementation file, it may be a bit out of my league but i'll see what i can gather, and hey, that's how it works, right? :-) thanks ariel From deets at nospam.web.de Sat Aug 2 09:53:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 02 Aug 2008 15:53:54 +0200 Subject: Strong/weak typing In-Reply-To: <6727fa22-aee9-4a9b-b9c0-08534aab6b34@m45g2000hsb.googlegroups.com> References: <6727fa22-aee9-4a9b-b9c0-08534aab6b34@m45g2000hsb.googlegroups.com> Message-ID: <6fj77iFbpj0iU1@mid.uni-berlin.de> MartinRinehart at gmail.com schrieb: > I'm writing Python as if it were strongly typed, never recycling a > name to hold a type other than the original type. > > Is this good software engineering practice, or am I missing something > Pythonic? Others pointed out the wrong wording. As often, this is not a question to be answered with a simple yes or no. Duck-typing is very ptyhonic, and as such it is very common to write e.g. if content_as_string: inf = StringIO.String(content_as_string) else: inf = open(filename) inf has two totally different types now, depending on the path taken. And I personally tend to actually do things like this: if isinstance(foo, str): foo = unicode(str) Or such. But that is more a matter of taste - I personally don't like to many names lying around, but YMMV. Diez From ireborin at gmail.com Sat Aug 16 15:30:28 2008 From: ireborin at gmail.com (Ivan Reborin) Date: Sat, 16 Aug 2008 21:30:28 +0200 Subject: wxPython beginners problem References: Message-ID: <9eaea4lg5bcgv09evi185q765u5v6kalla@4ax.com> On Fri, 15 Aug 2008 17:48:39 +0000 (UTC), Brian Victor wrote: >Ivan Reborin wrote: >> win.Show > >This line isn't doing anything. It needs to be: >win.Show() # note the parentheses Yes, that was the problem. I must've been tired while writing it, for I haven't noticed it after several repetitions. Thank you (and everyone else on their useful comments and suggestions). Best regards Ivan From ewertman at gmail.com Sat Aug 30 11:07:28 2008 From: ewertman at gmail.com (Eric Wertman) Date: Sat, 30 Aug 2008 11:07:28 -0400 Subject: Process "Killed" In-Reply-To: <48a554c6-eeb3-4605-bdf2-a4b7de17bca3@b1g2000hsg.googlegroups.com> References: <48a554c6-eeb3-4605-bdf2-a4b7de17bca3@b1g2000hsg.googlegroups.com> Message-ID: <92da89760808300807p1af72cbcoec2b39f153fe073e@mail.gmail.com> > I'm doing some simple file manipulation work and the process gets > "Killed" everytime I run it. No traceback, no segfault... just the > word "Killed" in the bash shell and the process ends. The first few > batch runs would only succeed with one or two files being processed > (out of 60) before the process was "Killed". Now it makes no > successful progress at all. Just a little processing then "Killed". This is the behavior you'll see when your os has run out of some memory resource. The kernel sends a 9 signal. I'm pretty sure that if you exceed a soft limit your program will abort with out of memory error. Eric From larry.bates at websafe.com` Thu Aug 14 12:52:39 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 14 Aug 2008 11:52:39 -0500 Subject: Fixed-length text file to database script In-Reply-To: References: Message-ID: Michael Str?der wrote: > Larry Bates wrote: >> ssharpjr at gmail.com wrote: >>> I have a machine (PLC) that is dumping its test results into a fixed- >>> length text file. I need to pull this data into a database (MySQL >>> most likely) so that I can access it with Crystal Reports to create >>> daily reports for my engineers. >>> [..] >>> I need to know how to write a script that will DAILY pull this text >>> file into a MySQL database. >> >> Just use the built in import SQL statement to import the information. >> You don't really need a Python script. import can handle fixed field >> records (as well as CSV, etc.). > > If the input data has to be pre-processed before storing it into the > database a Python script would be needed. > > Just in case somebody needs a module for reading fixed-length files in > the spirit of module csv: > > http://www.stroeder.com/pylib/fixedlenfields.py > > For the MySQL part: > http://mysql-python.sourceforge.net/ > > Ciao, Michael. While you are correct, that is not what the OP asked. There is no reference to processing data prior to insertion into MySQL database. Also the OP said they had a 1 day deadline. -Larry From fredrik at pythonware.com Tue Aug 19 09:22:14 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Aug 2008 15:22:14 +0200 Subject: Question regarding the standard library? In-Reply-To: References: Message-ID: Hussein B wrote: > Is the standard library compiled? the portions are written in Python are compiled to PYC files, just like modules you write yourself are automatically compiled to PYC files when you import them. (why not just look in the Python installation tree? it's all there for you to tinker with.) From bdesth.quelquechose at free.quelquepart.fr Tue Aug 19 14:58:51 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 19 Aug 2008 20:58:51 +0200 Subject: You advice please In-Reply-To: <79fac159-fb59-4ad6-8c41-23636b875332@y38g2000hsy.googlegroups.com> References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> <2a611c23-16a9-4a9d-8c93-3b24d7b404af@e39g2000hsf.googlegroups.com> <48a5b718$0$10768$426a74cc@news.free.fr> <79fac159-fb59-4ad6-8c41-23636b875332@y38g2000hsy.googlegroups.com> Message-ID: <48ab33dd$0$28448$426a74cc@news.free.fr> Hussein B a ?crit : > On Aug 15, 10:05 am, Bruno Desthuilliers > wrote: >> Hussein B a ?crit : >> (snip) >> >>> But this critisim looks so serious: >>> http://en.wikipedia.org/wiki/Ruby_programming_language#Criticism >> Most of what's written here could apply to Python too - all the part >> which mostly reflects the usual parano?a from bondage&discipline >> langages addicts wrt/ dynamic languages. The remaining is about >> implementation issues in ruby 1.8. > > Ruby doesn't has the language specification, do you think this is an > issue or a weak point? Unless you are trying to roll your own Ruby implementation, I don't think this is really an issue... From dlenski at gmail.com Mon Aug 18 12:17:34 2008 From: dlenski at gmail.com (Dan Lenski) Date: Mon, 18 Aug 2008 16:17:34 GMT Subject: Weird expression result References: <83803185-725e-45bb-b2fe-1add2868bd34@c58g2000hsc.googlegroups.com> Message-ID: On Mon, 18 Aug 2008 18:04:32 +0200, Peter Otten wrote: > This works just like a < b < c: > >>>> 3 in [3] and [3] == True > False > > Peter Interesting. I agree with the OP that it is confusing! Does this expansion really get invoked every time there is an expression of the form?? expr1 binary_op1 expr2 binary_op2 expr3 ... Seemingly, the answer is yes: >>> 3 in [3] in [[3],[4]] in [[[3],[4]],5] == [[[3],[2+2]],5] True How does this play with standard precedence rules? Dan From rokkamraja at gmail.com Mon Aug 25 05:52:42 2008 From: rokkamraja at gmail.com (Raja) Date: Mon, 25 Aug 2008 02:52:42 -0700 (PDT) Subject: Python cx_Oracle and Apache References: <8eb11d5f-c72f-48b2-bfbd-debab013af60@p25g2000hsf.googlegroups.com> Message-ID: <360c1518-066e-4685-ba99-8ffa47748625@x41g2000hsb.googlegroups.com> On Aug 25, 1:53?pm, Cousin Stanley wrote: > > .... > > > def generate_output(): > > ? ? ? ? print '' > > > generate_output() > > ? Raja .... > > ? ? You might try adding a ?Content-type ?header followed by > ? ? a ?blank line ?to your ?generate_output() ?function .... > > ? ? def generate_output() : > ? ? ? ? print 'Content-type: ?text/html' > ? ? ? ? print ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? > ? ? ? ? print .... rest of your html .... > > -- > Stanley C. Kitching > Human Being > Phoenix, Arizona Hi, Thanks for the help. I actually got the solution. The problem was apache's timeout is set to 1second. I just changed that value and it worked. Thanks, Raja. From pcsanders at yahoo.com Fri Aug 15 17:47:14 2008 From: pcsanders at yahoo.com (Paxton Sanders) Date: 15 Aug 2008 21:47:14 GMT Subject: Code works in current dir only? Message-ID: Does anyone know why the following code successfully labels (with [f|d|?]) entries in the current directory, but not in any other directory? (All other directories' entries print [?].) I'm using Python 2.5.1 on Cygwin. Thanks! import os # collect all files and their paths def collectinfo(path): files = os.listdir(path) files.sort() for n in files: if os.path.isdir(n): print "[d]", n elif os.path.isfile(n): print "[f]", n else: print "[?]", n # this works if __name__ == "__main__": collectinfo(".") # this does not work, always labels with [?] #if __name__ == "__main__": # collectinfo("/") -- Paxton Sanders pcsanders at yahoo.com From gagsl-py2 at yahoo.com.ar Fri Aug 15 00:19:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 15 Aug 2008 01:19:38 -0300 Subject: dynamically getting loggers References: Message-ID: En Thu, 14 Aug 2008 18:29:41 -0300, belred escribi?: > is there a way to dynamically get all the active loggers? > > i currently have code like this in different areas of the program: > > import logging > log = logging.getLogger('foo') > > > i would like to write a function that dynamically get a list of all > the logger names such as 'foo'. or get a list of the loggers which i > could then get the names. is this even possible? i don't see a > logger function that returns loggers. Loggers are created when requested, and I don't see a documented way to get such list. If you don't mind using undocumented attributes: existing_logger_names = logging.getLogger().manager.loggerDict.keys() -- Gabriel Genellina From gminick at bzt.bzt Fri Aug 22 15:53:58 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Fri, 22 Aug 2008 19:53:58 +0000 (UTC) Subject: EOF References: Message-ID: On Fri, 22 Aug 2008 22:18:37 +0530, Anjanesh Lekshminarayanan wrote: > Im trying to download a file from a server. But how do I detect EOF ? Whenever read() method returns empty string/list. > while f1: # When to stop ? retval = f1.read() if not retval: break f2.write(retval) should do the job. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From gagsl-py2 at yahoo.com.ar Mon Aug 18 22:36:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 18 Aug 2008 23:36:03 -0300 Subject: help with parsing email References: Message-ID: En Mon, 18 Aug 2008 12:24:07 -0300, Ahmed, Shakir escribi?: > Thanks everyone who tried to help me to parse incoming email from an exchange server: > > Now, I am getting following error; I am not sure where I am doing wrong. I appreciate any help how to resolve this error and extract emails from an exchange server. > > > First I tried: >>>> mailserver = 'EXCHVS01.my.org' >>>> mailuser = 'myname' >>>> mailpasswd = 'mypass' >>>> mailserver = poplib.POP3(mailserver) > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\lib\poplib.py", line 96, in __init__ > raise socket.error, msg > error: (10061, 'Connection refused') The code looks right - this isn't a Python problem. Ask your administrator, or look into your Outlook configuration and try to reproduce exactly those settings, including server name and port. >>>> mailserver = 'pop.EXCHVS01.ad.my.org' >>>> mailuser = 'myname at my.org' >>>> mailpasswd = 'mypass' >>>> mailserver = poplib.POP3(mailserver) > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\lib\poplib.py", line 84, in __init__ > for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): > gaierror: (11001, 'getaddrinfo failed') Probably pop.EXCHVS01.ad.my.org doesn't exist. -- Gabriel Genellina From sjmachin at lexicon.net Thu Aug 14 21:40:43 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 14 Aug 2008 18:40:43 -0700 (PDT) Subject: updating dictionaries from/to dictionaries References: Message-ID: <1c76b781-de1b-4c0a-8d8f-61cfa56a2e11@v39g2000pro.googlegroups.com> On Aug 15, 11:23 am, Edwin.Mad... at VerizonWireless.com wrote: > if the values for any of the keys are None, both do not work as can be seen below!!. > If any of the values are None, nothing can work. The OP justifiably (given his problem domain (bigram frequencies)) expects that all values will be integers. If this is not the case, it means that the code that populates his dictionaries is majorly stuffed, an exception will be raised, and he can fix it. From mh at pixar.com Thu Aug 28 19:31:15 2008 From: mh at pixar.com (mh at pixar.com) Date: Thu, 28 Aug 2008 23:31:15 GMT Subject: [1,2,3] exactly same as [1,2,3,] ? References: Message-ID: <7zGtk.20626$89.14452@nlpi069.nbdc.sbc.com> Paul McNett

wrote: > When confronted with this type of question, I ask the interpreter: > >>> [1,2,3] == [1,2,3,] > True Well I guess that's a pretty authoritative answer... thanks! -- Mark Harrison Pixar Animation Studios From http Tue Aug 12 04:16:14 2008 From: http (Paul Rubin) Date: 12 Aug 2008 01:16:14 -0700 Subject: for x,y in word1, word2 ? References: Message-ID: <7xk5em7inl.fsf@ruckus.brouhaha.com> ssecorp writes: > for x in y and for a in b: for x,a in zip(y,b): ... or the iterator version: from itertools import izip for x,a in izip(y,b): ... avoids allocating a list to iterate through. From eliben at gmail.com Thu Aug 21 03:34:21 2008 From: eliben at gmail.com (eliben) Date: Thu, 21 Aug 2008 00:34:21 -0700 (PDT) Subject: exception handling in complex Python programs References: Message-ID: On Aug 19, 7:19?pm, eliben wrote: > Python provides a quite good and feature-complete exception handling Thanks for the interesting discussion. Armed by the new information and few online sources, I blogged a summary for myself on the topic of robust exception handling in Python: http://eli.thegreenplace.net/2008/08/21/robust-exception-handling/ From fredrik at pythonware.com Sun Aug 17 11:17:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 17 Aug 2008 17:17:06 +0200 Subject: how many nested for can we utilize? In-Reply-To: References: <27cbc0fa0808152200l4be2ca5gc24d8b01458b6e62@mail.gmail.com> Message-ID: Wojtek Walczak wrote: >> it'll take approx 40 billion years to run the program. > > I guess that's exactly why the OP asks the question. He just wants > to start as soon as possible ;-) required reading: "The Effects of Moore's Law and Slacking on Large Computations" http://arxiv.org/abs/astro-ph/9912202 From marek.rocki at wp.pl Sat Aug 23 19:43:34 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Sat, 23 Aug 2008 16:43:34 -0700 (PDT) Subject: ctypes initializer References: <80af338b-d2fc-4479-b4bf-6c3fc9af3e87@m73g2000hsh.googlegroups.com> Message-ID: <1225338a-786a-4445-8102-7ca81ac96cc1@d77g2000hsb.googlegroups.com> castironpi napisa?(a): > Is there a way to initialize a ctypes Structure to point to an offset > into a buffer? I don't know if the way I'm doing it is supported. There is a high probability you're abusing ctypes too much, but it's possible. The following seems to work: from ctypes import * class S(Structure): _fields_ = [('x', c_uint), ('y', c_int)] rawdata = create_string_buffer('\xEE\xFF\x78\x56\x34\x12\xFF\xFF\xFF \xFF\xAA') # Try to make a structure s of type S which takes its data from rawdata # buffer, starting at index 2 s = cast(c_void_p(addressof(rawdata)+2), POINTER(S)).contents print hex(s.x), s.y # Should be 12345678h and -1 From larry.bates at websafe.com` Thu Aug 14 11:05:59 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 14 Aug 2008 10:05:59 -0500 Subject: for y in range (0,iNumItems)--> not in order? In-Reply-To: <8514d915-95bf-4e57-a16a-68866e0ad789@l42g2000hsc.googlegroups.com> References: <8514d915-95bf-4e57-a16a-68866e0ad789@l42g2000hsc.googlegroups.com> Message-ID: korean_dave wrote: > for y in range(0,iNumItems): > print(str(y)) > > How do i make the output go IN ORDER > 0 > 1 > 2 > 3 > 4 > 5 > 6 > etc. > > instead of > 0 > 1 > 10 > 11 > 12 > 13 > 14 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > 9 That's not what it does on my system (Python 2.5.2 on Windows). Please post the code that you are "actually" running. >>> for y in range(15): ... print str(y) ... 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 You must have put them in a list and sorted them prior to printing them to get the output you show. If you sort the list, the output is correct. To make it different, you will need to pass sort a custom cmp function. -Larry From gagsl-py2 at yahoo.com.ar Mon Aug 4 22:16:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 04 Aug 2008 23:16:46 -0300 Subject: URLs and ampersands References: <00a78f7e$0$20302$c3e8da3@news.astraweb.com> Message-ID: En Mon, 04 Aug 2008 20:43:45 -0300, Steven D'Aprano escribi?: > I'm using urllib.urlretrieve() to download HTML pages, and I've hit a > snag with URLs containing ampersands: > > http://www.example.com/parrot.php?x=1&y=2 > > Somewhere in the process, urls like the above are escaped to: > > http://www.example.com/parrot.php?x=1&y=2 > > which naturally fails to exist. > > I could just do a string replace, but is there a "right" way to escape > and unescape URLs? I've looked through the standard lib, but I can't find > anything helpful. This works fine for me: py> import urllib py> fn = urllib.urlretrieve("http://c7.amazingcounters.com/counter.php?i=1516903 &c=4551022")[0] py> open(fn,"rb").read() '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00... So it's not urlretrieve escaping the url, but something else in your code... -- Gabriel Genellina From Caseyweb at gmail.com Mon Aug 11 07:57:51 2008 From: Caseyweb at gmail.com (Casey) Date: Mon, 11 Aug 2008 04:57:51 -0700 (PDT) Subject: paretovariate References: Message-ID: On Aug 11, 3:14?am, "zhjchen" wrote: > I want to realize a list of numbers. They follow pareto distribution. > For instance, the average value is 10 and alpha is 1.0 > I do not know how to use the function of paretovariate(alpha). It only provides > alpha parameter. How should I set the average value? I'm guessing that paretovalue(alpha) treats alpha as the shape parameter and assumes a mode of 1.0, in which case you would multiply by 10 for your example. Alternatively, you could define your own Pareto function: # pareto for mode, shape > 0.0 def pareto(mode, shape): return mode * pow(1.0 - random.random(), -1.0 / shape) From joseph.steffl at medtronic.com Mon Aug 18 08:33:56 2008 From: joseph.steffl at medtronic.com (Steffl, Joseph) Date: Mon, 18 Aug 2008 07:33:56 -0500 Subject: pysyncml 0.1 released In-Reply-To: <48a57bb2$0$12027$426a74cc@news.free.fr> References: <48a57bb2$0$12027$426a74cc@news.free.fr> Message-ID: <9A745764A58AD94D996A055D92D7012B3BEF6AE1@MSPM1BMSGM20.ent.core.medtronic.com> -----Original Message----- From: J?r?me Laheurte [mailto:fraca7 at free.fr] Sent: Friday, August 15, 2008 7:51 AM To: comp-lang-python-announce at moderators.isc.org Subject: pysyncml 0.1 released Hi, I'm happy to announce the first release of pysyncml, a Python wrapper for the Funambol C++ API. The project page, with example scripts and API reference, is here: https://pysyncml.forge.funambol.org/ You can download it from here: https://pysyncml.forge.funambol.org/servlets/ProjectDocumentList Tested platforms are: Linux i386 (Slackware 12), MacOS X 10.4 and Windows XP. Binaries are available for these platforms (for Python 2.5), as well as source code. * About pysyncml * pysyncml has two parts: * A Python extension module (_pysyncml) wrapping the Funambol C++ API (see http://www.funambol.com/) * A pure Python module (pysyncml) with higher-level classes to ease writing SyncML-aware applications in Python. pysyncml is licensed under the GPL, version 2.1. -- J?r?me Laheurte [CONFIDENTIALITY AND PRIVACY NOTICE] Information transmitted by this email is proprietary to Medtronic and is intended for use only by the individual or entity to which it is addressed, and may contain information that is private, privileged, confidential or exempt from disclosure under applicable law. If you are not the intended recipient or it appears that this mail has been forwarded to you without proper authority, you are notified that any use or dissemination of this information in any manner is strictly prohibited. In such cases, please delete this mail from your records. To view this notice in other languages you can either select the following link or manually copy and paste the link into the address bar of a web browser: http://emaildisclaimer.medtronic.com From paul at boddie.org.uk Wed Aug 27 04:44:15 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 27 Aug 2008 01:44:15 -0700 (PDT) Subject: libxml2dom - parsing maligned html References: Message-ID: <5ea94ad9-847b-459a-b204-28f0d2ce64a9@34g2000hsh.googlegroups.com> On 26 Aug, 23:22, "bruce" wrote: > > ok, i can somehow live with this, i can accommodate it. but tell me, when > the parse module/class for libxml2dom does its thing, why does it not go > forward on the tree when it comes to a , if there's more text in the > string to process??? I imagine that libxml2, which actually does the parsing, stops doing its work when it has successfully closed all open elements. Perhaps there's a way of making it go on and potentially complain about trailing input. > oh, also, regarding screen parsing/crawling, i've seen a number of sites > that have discussed using a web testing app, like selinium, and driving a > browser process, in order to really capture all the required data. any > thoughts on the pros/cons of this kind of approach to scraping data... Once upon a time I used the KPartPlugins to automate Konqueror, combining them with a DOM implementation, qtxmldom, which let me read the contents of Web pages from a real browser. Unfortunately, that technology doesn't work with recent versions of KDE (or PyKDE), and attempts to use Mozilla via PyXPCOM weren't successful. If you wanted to pursue this route, my advice would be to ask the Mozilla people, particularly those who work with PyXPCOM. An alternative might be to look into the state of bindings for the Webkit browser technologies. Paul From ggpolo at gmail.com Thu Aug 28 18:09:01 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 28 Aug 2008 19:09:01 -0300 Subject: eval() == evil? --- How to use it safely? In-Reply-To: References: Message-ID: On Thu, Aug 28, 2008 at 6:51 PM, Fett wrote: > I am creating a program that requires some data that must be kept up > to date. What I plan is to put this data up on a web-site then have > the program periodically pull the data off the web-site. > > My problem is that when I pull the data (currently stored as a > dictionary on the site) off the site, it is a string, I can use eval() > to make that string into a dictionary, and everything is great. > However, this means that I am using eval() on some string on a web- > site, which seems pretty un-safe. > > I read that by using eval(code,{"__builtins__":None},{}) I can prevent > them from using pretty much anything, and my nested dictionary of > strings is still allowable. What I want to know is: > > What are the dangers of eval? > - I originally was using exec() but switched to eval() because I > didn't want some hacker to be able to delete/steal files off my > clients computers. I assume this is not an issue with eval(), since > eval wont execute commands. > - What exactly can someone do by modifying my code string in a command > like: thing = eval(code{"__builtins__":None},{}), anything other than > assign their own values to the object thing? By "disabling" __builtins__ you indeed cut some obvious tricks, but someone still could send you a string like "10 ** 10 ** 10". > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From luismgz at gmail.com Fri Aug 1 17:42:06 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Fri, 1 Aug 2008 14:42:06 -0700 (PDT) Subject: Hobbyist - Python vs. other languages References: Message-ID: <4a04b7b2-caa0-46bb-b597-554ef2f00ea6@d1g2000hsg.googlegroups.com> On 31 jul, 15:32, fprintf wrote: > I have been playing with computers since I first learned to program > moving shapes on an Atari 800XL in BASIC. After many years of dabbling > in programming languages as a hobbyist (I am not a computer scientist > or other IT professional), I have never found a way to stick with a > language far enough to do anything useful. ?I learn all about loops > and data structures and functions/methods etc. but never get to create > a program that will do anything of value that I can't more easily do > via freeware. Well, except the slot car timing system I wrote in C++ > for Linux many moons ago. > > Honestly Python seems like a breath of fresh air and possibly a way to > get back to my BASIC roots, you know, programming just for the fun of > it. > > Since I don't have a specific problem to solve, besides > Pythonchallenge (which I found very cryptic), and Project Euler (which > I found beyond my mathematics skills), is there a place to go for > increasingly difficult problems to solve? I have followed a number of > the recommended online tutorials that contain a logical progression of > problems and yet they all end at the point where a person has enough > knowledge of the syntax, but not really enough to do anything. Are you interested in web development? This could be a very good way to use python for doing useful things, since any app you create for the web can be instantly available to thousands of people. And now you have Google App Engine, which is a new and free way to get your python app online. Actually, any problem you may want to solve should have some kind of graphical interface if you want your app to be used by other people. So why not giving your apps a web interface? It has many advantages, and it seems to be the way to go today. From bearophileHUGS at lycos.com Mon Aug 18 16:02:33 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 18 Aug 2008 13:02:33 -0700 (PDT) Subject: like a "for loop" for a string References: <6bc8134c-fd89-4a98-8a99-813f41b26813@k30g2000hse.googlegroups.com> Message-ID: <22fcda17-ac22-4ff6-bc7e-0a87b26b90c7@y21g2000hsf.googlegroups.com> Fredrik Lundh: > or you could use re.finditer, which can be used for a lot more than just > splitting. Having implemented some of them (and even invented algorithms like a new substring search, that I have appreciated) you know that string methods are simpler ways to efficiently perform specialized functions that are used often. Many string methods can be replaced by operations with REs, but they become less easy/clean to use, and maybe even slower. A specialized xsplit can be faster than re.finditer, and the syntax is better/handier. Bye, bearophile From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 26 05:00:14 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 26 Aug 2008 11:00:14 +0200 Subject: What is class method? In-Reply-To: References: Message-ID: <48b3c5ef$0$8908$426a74cc@news.free.fr> Maric Michaud a ?crit : (snip) > > It is a common advice that staticmethod should not exist in python, as they do > nothing compared to module level functions, They "do" nothing more, but are accessible thru a class object instead of being accessible thru a module object. It sometimes happens to be useful (for a very very low value of 'sometimes' as far as I'm concerned, but still...) From saptarshi.guha at gmail.com Sat Aug 16 09:47:17 2008 From: saptarshi.guha at gmail.com (sapsi) Date: Sat, 16 Aug 2008 06:47:17 -0700 (PDT) Subject: sqlite empty inserts References: <9c28ccd0-ba04-4e21-8cbb-ff8959c4801e@m44g2000hsc.googlegroups.com> <72373c22-33dc-45dd-aea7-b31e36ac6169@b1g2000hsg.googlegroups.com> Message-ID: I forgot to mention that i was creating a view just before this i.e sql="create view %s as %s" % (foldername, query) # self.cursor.execute(sql) self.cursor.execute(sql) Now if i remove this, the insert code works fine. Regards Saptarshi From moijes12 at gmail.com Fri Aug 29 08:17:16 2008 From: moijes12 at gmail.com (moijes12) Date: Fri, 29 Aug 2008 05:17:16 -0700 (PDT) Subject: importing from .pyd References: <3d66daeb-d45a-46be-bd4d-34a2225683d1@2g2000hsn.googlegroups.com> <3d0c2dbb-6835-44c8-b663-ecb8677a46dd@2g2000hsn.googlegroups.com> Message-ID: On Jul 14, 4:11?pm, Kay Schluehr wrote: > On 14 Jul., 06:03, moijes12 wrote: > > > hi > > > there is a .pyd file present in the same folder as the script abc.py > > by the name foo.pyd .I don't have foo.py .In the script abc.py I try > > > import foo > > > Error i get is > > ImportError: DLL load failed: The specified module could not be found. > > It looks like the module that was accessed is either corrupt > ( unavailable entry point ) or it contains dependencies to other > modules which are not available. > > At least the latter can be checked without access to the source using > the DependencyWalker: > > http://www.dependencywalker.com/ > > Notice that the message clearly indicates that Python found the module > but failed to load it i.e. performing a LoadLibrary() which yielded a > NULL pointer. thanks From Arton0306 at gmail.com Wed Aug 13 20:48:18 2008 From: Arton0306 at gmail.com (Johnny) Date: Wed, 13 Aug 2008 17:48:18 -0700 (PDT) Subject: any function to fill zeros to the right?? zfill?? Message-ID: if I want to fill zeros to the right, what function can help?? ex: '1.23'=>'1.2300' but '1.23'.zfill(6)=>'001.23' From gabriel.rossetti at arimaz.com Tue Aug 26 10:41:10 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Tue, 26 Aug 2008 16:41:10 +0200 Subject: dynamically adding some of one module's functions to another Message-ID: <48B41606.9090202@arimaz.com> Hello everyone, I'm trying to import some modules into another's namespace (network_utils) network_utils.py: import utils import constants as main_const from services import constants as srv_const from plugins import constants as plg_const # # Import all the message creation functions # f = dict([ (f, eval("utils." + f)) for f in dir(utils) if f.startswith("create") ]) __builtins__.update(f) del utils # # Create a virgin namespace # class constants: """ An aggragation of L{constants}, L{services.constants}, & L{plugins.constants} """ pass # # Import all the constants into the new namespace # f = dict([ (f, eval("main_const." + f)) for f in dir(main_const) if f.isupper() ]) constants.__dict__.update(f) del main_const f = dict([ (f, eval("srv_const." + f)) for f in dir(srv_const) if f.isupper() ]) constants.__dict__.update(f) del srv_const f = dict([ (f, eval("plg_const." + f)) for f in dir(plg_const) if f.isupper() ]) constants.__dict__.update(f) del plg_const now, if I import network_utils somewhere, and try to call network_utils.myFunction() I get : >>> import network_utils >>> network_utils.myFunction Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'myFunction' but if I try to access the constants class: >>> from network_utils import constants >>> constants.NO_DATA_TYPE 'none' it works, how come? Thank you, Gabriel From steve at REMOVE-THIS-cybersource.com.au Thu Aug 21 01:49:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Aug 2008 05:49:02 GMT Subject: Bizarre method keyword-arg bug. References: <73104fb9-3f05-445e-83e6-2b1939316f15@d77g2000hsb.googlegroups.com> <00b981ba$0$20315$c3e8da3@news.astraweb.com> <00bc578e$0$20315$c3e8da3@news.astraweb.com> Message-ID: <00bcfca3$0$20315$c3e8da3@news.astraweb.com> On Wed, 20 Aug 2008 15:58:44 -0400, Robert Brown wrote: > Steven D'Aprano writes: >> On Wed, 20 Aug 2008 13:09:21 -0400, Robert Brown wrote: >> >>> In any case, chances are high that Lisp's way of handling default >>> arguments would have been changed had it been shown to cause >>> performance problems. >> >> But nobody is suggesting that it would cause performance problems in >> *Lisp*. It might, or it might not. Who cares? We're not talking about >> Lisp, we're talking about *Python*, and evaluating default arguments >> every time the function is called would certainly cause a performance >> hit in Python. > > Please explain why it's a performance problem for Python but not for > other languages. Because other languages are implemented differently from Python, just as other languages are implemented differently from Lisp, C, Basic, Forth, Smalltalk, Whitespace, Ruby, PHP, Java, and quite a few others. If you mean, why is it a problem for Python but not Lisp, I'm afraid I'll have to defer to others who are more knowledgeable about the implementation than I am. All I know is that Fredrik Lundh, who has forgotten more about Python than I know, has stated: "it's done that way on purpose, of course, because evaluating a full closure for each default argument at every call would greatly hurt performance" But if you want a simple example, consider this function definition: def parrot(x=expr) Evaluating expr will take arbitrary time. If you don't believe me, consider the pathological case of x=time.sleep(10**6). The current semantics pays that cost once, when the def statement is executed, and from that point on retrieving the default value of x is almost free. Evaluating expr every time the function is called will pay that cost every time. Frankly, I can't see how any language, including Lisp, could possibly avoid that runtime cost. -- Steven From gagsl-py2 at yahoo.com.ar Wed Aug 20 03:42:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 20 Aug 2008 04:42:02 -0300 Subject: Subprocess module question. References: <73045cca0808191806r1277669fyba9299451e62a7a5@mail.gmail.com> Message-ID: En Tue, 19 Aug 2008 22:06:13 -0300, aditya shukla escribi?: > I am using windows vista and i am trying to communicate with various > processes. > so when i do > > import subprocess > proc=subprocess.Popen('cmd.exe') > --This opens the command prompt > But when i do > > proc=subprocess.Popen('netscan.exe') > it gives an error > > WindowsError: [Error 2] The system cannot find the file specified > > However "netscan.exe" is present on my system. Is it on your system PATH? Can you execute "netscan" from a console at the same directory as your script? -- Gabriel Genellina From maric at aristote.info Tue Aug 12 07:11:06 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 12 Aug 2008 13:11:06 +0200 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> Message-ID: <200808121311.06892.maric@aristote.info> Le Tuesday 12 August 2008 11:29:18 Cousson, Benoit, vous avez ?crit?: > Hi, > > I'd like to be able to use a nested class (C1) from another sibling nested > class (C3). This looks very similar to the nested scopes of functions > except that it does not work. > > class A(object): > pass > > class B(object): > > class C1(object): > pass > > class C2(C1): > foo = A > > class C3(object): > foo = C1 > > The funny thing is that C2 can inherit from C1 but C3 cannot reference C1. > B.C1 does not work either, but in that case it makes sense since B is still > being defined. Is this a language limitation or something that does not > make sense at all? > This is a language limitation. This is because nested scope is implemented for python function only since 2.3 allow late binding of free variables. the scope in class statment is not a closure, so there is only two possible scope in it : local and global. When "class C2(C1):" statment is interpreted, it is in the scope of class B for which a name C1 exists, but it doesn't within the new scope of class C2 (the future C2.__dict__). If you really need such a nested thing, this could help : >>>[39]: class A(object) : class B(object) : pass C = type('C', (B,), {'ref' : B}) ....: >>>[29]: >>>[30]: A ...[30]: >>>[31]: A.B ...[31]: >>>[32]: A.C ...[32]: >>>[33]: A.C.__bases__ ...[33]: (,) >>>[34]: A.C.ref ...[34]: > I'm wondering as well if the new nonlocal statement will fix that in py3k? > nonlocal doesn't adress this issue an I doubt python 3.0 fix it at all. You have the same problem with generator expressions, which bind lately outer loop variables : >>>[70]: def f() : l = list( a for a in range(5) ) return list( e + f for f in range(5) for e in l ) ....: >>>[73]: list(f()) ...[73]: [0, 1, 2, 3, 4, 1, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8] >>>[74]: class A(object) : l = list( a for a in range(5) ) m = [ e + f for f in range(5) for e in l ] ....: ....: >>>[77]: A.m ...[77]: [0, 1, 2, 3, 4, 1, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8] >>>[78]: class A(object) : l = list( a for a in range(5) ) m = list( e + f for f in range(5) for e in l ) ....: ....: --------------------------------------------------------------------------- NameError Traceback (most recent call last) /home/maric/ in () /home/maric/ in A() /home/maric/ in ((f,)) NameError: global name 'l' is not defined -- _____________ Maric Michaud From stef.mientki at gmail.com Mon Aug 11 17:53:15 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 11 Aug 2008 23:53:15 +0200 Subject: eval or execute, is this the (most) correct way ? In-Reply-To: <48a0adb8$0$24005$9b622d9e@news.freenet.de> References: <48a0adb8$0$24005$9b622d9e@news.freenet.de> Message-ID: <48A0B4CB.3050507@gmail.com> Martin v. L?wis wrote: >> So AFAIK, sometimes I've to use eval and sometimes I need exec, >> so I use the following code (global / local dictionary parameters are >> left out in this example): >> >> >> Is this the (most) correct / elegant way, or are there better solutions ? >> > > You should be using compile with the "single" start symbol, and then > use eval on the resulting code option. > > thanks Martin, but when I read the doc (of one of the many) "compile" functions, I see 2 problems: - I still have to provide "kind" as exec or eval - I can not specify the global and local namespace (which is essential for me) >> I read somewhere that exec is going to disappear, >> > > That's not true. exec stops being a statement, and becomes a function > (like print). > > That's good to hear, as I already didn't realize it could also be used as a statement ;-) cheers, Stef > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list > From paul.sijben at xs4all.nl Mon Aug 4 11:05:39 2008 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Mon, 04 Aug 2008 17:05:39 +0200 Subject: import * and py2exe Message-ID: <48971ac4$0$49839$e4fe514c@news.xs4all.nl> I am trying to turn my application into a WinXP exe. Py2exe has packaged all my files up into one humongous executable. When trying to run the app, it complains that it can not find modules I just saw it include. These invariably are modules that have been imported using from import * Apparently this confuses py2exe. Well I tried unconfusing it by giving those modules as imports in the first place! How can I convince the py2exe-generated app to look for those modules in its own .exe file??? Paul From lfrogerscobalt at gmail.com Tue Aug 26 20:07:10 2008 From: lfrogerscobalt at gmail.com (Albertos) Date: Tue, 26 Aug 2008 17:07:10 -0700 (PDT) Subject: 've collected huge source codes collection of any kinds Message-ID: Hello, I've collected huge source codes collection of any kinds : work with text files, database, GUI etc. You can download it here http://freactor.com/get.php?file=Python+source+code From michele.simionato at gmail.com Fri Aug 29 08:11:05 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 29 Aug 2008 05:11:05 -0700 (PDT) Subject: Python in a Nutshell -- Book vs Web References: <924lo5-9u7.ln1@lairds.us> Message-ID: On Aug 29, 1:44?pm, cla... at lairds.us (Cameron Laird) wrote: > Insightful. ?Well, I find it insightful; perhaps it's > a personal blindness on my part. ?I expect programmers > to understand, for example, that two lines of code can > be a good day's production, in some circumstances My best days are the ones were I have a negative count of lines, i.e. I am able to remove cruft ;) From gnewsg at gmail.com Sat Aug 2 07:12:03 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sat, 2 Aug 2008 04:12:03 -0700 (PDT) Subject: Searching for some kind of data type Message-ID: <33d13c77-e710-4951-a559-7ea8b6e15287@26g2000hsk.googlegroups.com> Hi, for an FTP server I wrote I'd need to group the FTP commands in one table that defines the command itself, the syntax string, required permission, whether it requires authorization, whether it takes argument and whether there's a need to validate the path from the argument. The more obvious way I found to do that is something like this: class CommandProperty: def __init__(self, perm, auth_needed, arg_needed, check_path, syntax): self.perm = perm self.auth_needed = auth_needed self.arg_needed = arg_needed self.check_path = check_path self.syntax = syntax ftp_cmds = { "ABOR" : CommandProperty(perm=None, auth_needed=True, arg_needed=False, check_path=False, syntax="ABOR (abort transfer)."), "APPE" : CommandProperty(perm='a', auth_needed=True, arg_needed=True, check_path=True, syntax="APPE file-name (append data to an existent file)."), "CDUP" : CommandProperty(perm='e', auth_needed=True,arg_needed=False, check_path=False, syntax="CDUP (go to parentdirectory)."), ... ... ... } ...but I find it somewhat redundant and... "ugly". I was wondering if there was some kind of data type which could better fit such purpose or if someone could suggest me some other approach to do this same thing. Maybe using a dictionary is not the better choice here. Thanks in advance --- Giampaolo http://code.google.com/p/pyftpdlib/ From sturlamolden at yahoo.no Fri Aug 8 00:40:20 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 7 Aug 2008 21:40:20 -0700 (PDT) Subject: random numbers according to user defined distribution ?? References: Message-ID: Alex wrote: > I wonder if it is possible in python to produce random numbers > according to a user defined distribution? > Unfortunately the random module does not contain the distribution I > need :-( There exist some very general algorithms to generate random numbers from arbitrary distributions. The most notable of these are "Markov Chain Monte Carlo", e.g. the Metropolis-Hastings algorithm. It is very easy to implement in any programming language. The nature MCMC algorithms makes it inefficient when implemented in pure Python. But you can get tremendous speedup by simulating multiple Markov chains in parallel, by means of vectorizing with NumPy. A relative of Metropolis-Hastings which may also be applicable to your problem is pure "rejection sampling". It is far less efficient, but produces no autocorrelation in the samples. If you can generate random deviates from the marginal distributions, but need to sample the joint distribution, look into using the Gibbs sampler. It is an efficient version of Metropolis-Hastings for this special case. http://en.wikipedia.org/wiki/Metropolis-Hastings_algorithm http://en.wikipedia.org/wiki/Rejection_sampling http://en.wikipedia.org/wiki/Gibbs_sampling From Simon.Strobl at gmail.com Fri Aug 1 03:46:09 2008 From: Simon.Strobl at gmail.com (Simon Strobl) Date: Fri, 1 Aug 2008 00:46:09 -0700 (PDT) Subject: very large dictionary Message-ID: <5c5e6d6e-04ef-4340-963f-d3825875b32c@e39g2000hsf.googlegroups.com> Hello, I tried to load a 6.8G large dictionary on a server that has 128G of memory. I got a memory error. I used Python 2.5.2. How can I load my data? SImon From simon at brunningonline.net Wed Aug 27 07:29:20 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 27 Aug 2008 12:29:20 +0100 Subject: finding out the number of rows in a CSV file In-Reply-To: References: Message-ID: <8c7f10c60808270429r2f3f8337p2c836b3b59fdc46f@mail.gmail.com> 2008/8/27 SimonPalmer : > anyone know how I would find out how many rows are in a csv file? > > I can't find a method which does this on csv.reader. len(list(csv.reader(open('my.csv')))) -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From straton at lampsacos.demon.co.uk Thu Aug 28 05:53:37 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Thu, 28 Aug 2008 10:53:37 +0100 Subject: [Q] How to ignore the first line of the text read from a file In-Reply-To: References: Message-ID: youngjin.michael at gmail.com wrote: > Hello, > > I am new to Python and have one simple question to which I cannot find > a satisfactory solution. > I want to read text line-by-line from a text file, but want to ignore > only the first line. I know how to do it in Java (Java has been my > primary language for the last couple of years) and following is what I > have in Python, but I don't like it and want to learn the better way > of doing it. > > file = open(fileName, 'r') > lineNumber = 0 > for line in file: > if lineNumber == 0: > lineNumber = lineNumber + 1 > else: > lineNumber = lineNumber + 1 > print line > > Can anyone show me the better of doing this kind of task? > > Thanks in advance. > LineList=open(filename,'r').readlines()[1,] for line in Linelist: blah blah From jorgen.maillist at gmail.com Tue Aug 5 04:25:30 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Tue, 5 Aug 2008 10:25:30 +0200 Subject: UnicodeDecodeError, how to elegantly deal with this? In-Reply-To: <20080804184851.C15FC1E4004@bag.python.org> References: <20080804184851.C15FC1E4004@bag.python.org> Message-ID: <11e49df10808050125r3578641ayb6e576bb0f7e9c04@mail.gmail.com> Hi Edwin, Filemask is obvious as it is assigned in the python code itself. It is "%file%". The idea is that the file clicked is substituted for the "%file%" by the replace action. The file that needs to be substituted is a simple file on disk. Here is a dump of the file and it's characters. I do understand that it is not in the range of ASCII but how can I make it so that it will work? >>>E:\Series\Series\American Dad\American Dad - S03E15 - Stanny Slickers II, The Legend of Ollie??s Gold.avi E (69): (58)\ (92)S (83)e (101)r (114)i (105)e (101)s (115)\ (92)S (83)e (101)r (114)i (105)e (101)s (115)\ (92)A (65)m (109)e (101)r (114)i (105)c (99)a (97)n (110) (32)D (68)a (97)d (100)\ (92)A (65)m (109)e (101)r (114)i (105)c (99)a (97)n (110) (32)D (68)a (97)d (100) (32)- (45) (32)S (83)0 (48)3 (51)E (69)1 (49)5 (53) (32)- (45) (32)S (83)t (116)a (97)n (110)n (110)y (121) (32)S (83)l (108)i (105)c (99)k (107)e (101)r (114)s (115) (32)I (73)I (73), (44) (32)T (84)h (104)e (101) (32)L (76)e (101)g (103)e (101)n (110)d (100) (32)o (111)f (102) (32)O (79)l (108)l (108)i (105)e (101)? (194)? (180)s (115) (32)G (71)o (111)l (108)d (100). (46)a (97)v (118)i (105)Traceback (most recent call last): File "D:\backup\important\src\airs\gui\AirsFrame.py", line 575, in _onWebRequest webdispatch.execute(cmd, id, args) File "D:\backup\important\src\airs\webserver\webdispatch.py", line 167, in execute _cmd_dispatcher[cmd](cb, args) File "D:\backup\important\src\airs\webserver\webdispatch.py", line 122, in playFile therep = arg.replace(filemask, thefile) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 93: ordinal not in range(128) ---- I assume it is about this part: Ollie??s Gold.avi But what can I do to decode that properly? With regards, - Jorgen On Mon, Aug 4, 2008 at 8:46 PM, wrote: > if you can print out values of 'filemask', and 'thefile' variables, when it crashes, I can help. > > thx. Edwin > > -----Original Message----- > From: python-list-bounces+edwin.madari=verizonwireless.com at python.org > [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] > On Behalf Of Jorgen Bodde > Sent: Monday, August 04, 2008 2:24 PM > To: python-list at python.org > Subject: UnicodeDecodeError, how to elegantly deal with this? > > > Hi All, > > I am relatively new to python unicode pains and I would like to have > some advice. I have this snippet of code: > > def playFile(cmd, args): > argstr = list() > for arg in appcfg.options[appcfg.CFG_PLAYER_ARGS].split(): > thefile = args["file"] > filemask = u"%file%" > therep = arg.replace(filemask, thefile) ##### error here > argstr.append(therep) > argstr.insert(0, appcfg.options[appcfg.CFG_PLAYER_PATH]) > > try: > subprocess.Popen( argstr ) > except OSError: > cmd.html = "

Can't play file


" + args["file"] > return > > cmd.redirect = _getBaseURL("series?cmd_get_series=%i" % args["id"]) > cmd.html = "" > > ------------------- > > It crashes on this: > > 20:03:49: File > "D:\backup\important\src\airs\webserver\webdispatch.py", line 117, in > playFile therep = arg.replace(filemask, thefile) > > 20:03:49: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in > position 93: ordinal not in range(128) > > 20:03:49: Unhandled Error: : > 'ascii' codec can't decode byte 0xc2 in position 93: ordinal not in > range(128) > > It chokes on a ` character in a file name. I read this file from disk, > and I would like to play it. However in the replace action it cannot > translate this character. How can I transparently deal with this issue > because in my eyes it is simply replacing a string with a string, and > I do not want to be bothered with unicode problems. I am not sure in > which encoding it is in, but I am not experienced enough to see how I > can solve this > > Can anybody guide me to an elegant solution? > > Thanks in advance! > - Jorgen > -- > http://mail.python.org/mailman/listinfo/python-list > > > > The information contained in this message and any attachment may be > proprietary, confidential, and privileged or subject to the work > product doctrine and thus protected from disclosure. If the reader > of this message is not the intended recipient, or an employee or > agent responsible for delivering this message to the intended > recipient, you are hereby notified that any dissemination, > distribution or copying of this communication is strictly prohibited. > If you have received this communication in error, please notify me > immediately by replying to this message and deleting it and all > copies and backups thereof. Thank you. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From w.richert at gmx.net Fri Aug 29 02:14:12 2008 From: w.richert at gmx.net (Willi Richert) Date: Fri, 29 Aug 2008 08:14:12 +0200 Subject: Multiple values for one key In-Reply-To: <26c69b160808281002l262e4824y60b8d3cb3369ee91@mail.gmail.com> References: <26c69b160808271326w2f53b6b8s6e4aa7f91071ac71@mail.gmail.com> <48b6ca75$0$5088$426a74cc@news.free.fr> <26c69b160808281002l262e4824y60b8d3cb3369ee91@mail.gmail.com> Message-ID: <200808290814.12472.w.richert@gmx.net> Hi, try defaultdict: In [1]: from collections import defaultdict In [2]: d=defaultdict(list) In [3]: d[1].append(7) In [4]: d[1].append(8) In [5]: d Out[5]: defaultdict(, {1: [7, 8]}) In [6]: d[1] Out[6]: [7, 8] Regards, wr Am Donnerstag 28 August 2008 19:02:55 schrieb Ron Brennan: > I have another question. > > How would like to be able to add the contents on the values for one key. > > key['20001']:[978, 345] > > How can I do this? > > Thanks, > Ron > > On Thu, Aug 28, 2008 at 11:56 AM, Bruno Desthuilliers > > wrote: > > norseman a ?crit : > >> Terry Reedy wrote: > >>> Ron Brennan wrote: > >>>> Hello, > >>>> How would I create a dictionary that contains multiple values for > >>>> one key. > >>> > >>> Make the value a collection object (set or list if you plan to add and > >>> delete). > >>> > >>> I'd also like the key to be able to have duplicate entries. > >>> > >>> > >>> Dict keys must be hashable and unique. > >>> > >>> tjr > >>> > >>> -- > >>> http://mail.python.org/mailman/listinfo/python-list > >>> > >>> ================ > >> > >> First part I understand, second is still giving me a problem. > >> > >> For some reason I still want keys to be dbf column headers. > >> like: > >> > >> name:address:zip so forth > >> ---- ------- --- ------------------ > >> guy: unknown:00000 > >> girl: 123 tiny street:12345 > >> boy:321 here:33333 > >> gal:999 over there: 55555 > >> so forth > >> > >> Thus one key has many values. And you can then index on whatever key(s) > >> you wish - name,zip... > > > > You can either use 1/ a list of dicts, or 2/ a dict mapping keys to > > lists. > > > > 1/ > > records = [ > > {"name":"guy", "address":"unknown","zip":"00000"}, > > {"name":"girl", "address":"123 tiny street","zip":"12345"}, > > {"name":"boy", "address":"321 here","zip":"33333"}, > > {"name":"gal", "address":"999 over there","zip":"55555"}, > > ] > > > > keys = ("name", "address", "zip") > > > > print ":".join(keys) > > print "-" * len(":".join(keys)) > > for record in records: > > data = [record[key] for key in keys] > > print ":".join(data) > > > > > > 2/ > > records = dict( > > name=["guy", "girl", "boy", "gal"], > > address=["unknown","123 tiny street","321 there","999 over there"], > > zip=["00000", "12345", "33333", "55555"] > > ) > > > > keys = ("name", "address", "zip") > > nb_records = len(records[keys[0]]) > > > > print ":".join(keys) > > print "-" * len(":".join(keys)) > > for i in xrange(nb_records): > > data = [data[key][i] for key in keys] > > print ":".join(data) > > > > > > You are of course entitled the right to prefer the second solution, but > > then I hope I'll never have to maintain your code, since it's obviously > > not an appropriate data structure. > > > > With billions plus records, > > > > > > With billions plus records, it may be time to move to a serious RDBMS. > > Which btw will provide solution 1, or a lighter version of it using a > > list of tuples, ie: > > > > cursor = connection.cursor() > > cursor.execute("select name, address, zip from peoples") > > records = cursor.fetchall() > > > > # at this time, you have : > > #records = [ > > # ("guy", "unknown","00000",), > > # ("girl", "123 tiny street","12345",), > > # ("boy", "321 here","33333",), > > # ("gal", "999 over there", "55555",), > > #] > > > > > > (snip) > > > > OK - I know I missed the whole concept of a Python Dictionary. > > > > > > Bad thing for you, since it's the central datastructure in Python. > > > > I haven't read anything as yet that gives a clear picture of what it is > > and > > > >> what it is for. > > > > Then you failed to read the FineManual's tutorial, which is where you > > should have started: > > > > http://docs.python.org/tut/node7.html#SECTION007500000000000000000 > > > > Do yourself a favour : read the above first, then if you still have > > questions about dicts, we'll gladly try to help. > > > > And do yourself another favour : learn about SQL, relational model and > > RDBMS. > > > > (snip description of why the OP *really* wants a RDBMS) > > > > -- > > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From Stephen.Cattaneo at u4eatech.com Tue Aug 12 13:30:47 2008 From: Stephen.Cattaneo at u4eatech.com (Stephen Cattaneo) Date: Tue, 12 Aug 2008 10:30:47 -0700 Subject: xcompile patch for python 2.5.2? Message-ID: Hi all, Personally I know nothing of cross compiling so please excuse my ignorance, if this question is silly. A friend of mine is attempting to cross compile python 2.5.2 onto a MIPS64 box. He is asking if there is a cross compile patch for 2.5.2. Do any of you know where He might find such a thing? Thanks, Steve From kw at codebykevin.com Thu Aug 7 17:20:03 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 07 Aug 2008 17:20:03 -0400 Subject: Tkinter fullscreen with Mac OS X In-Reply-To: <5c309fb1-3b44-4d12-9b92-6ce763457335@2g2000hsn.googlegroups.com> References: <5c309fb1-3b44-4d12-9b92-6ce763457335@2g2000hsn.googlegroups.com> Message-ID: <489B6703.1040601@codebykevin.com> C Martin wrote: > On Jul 28, 6:43 pm, "Guilherme Polo" wrote: >> You could try this, supposing tl is a toplevel: >> >> tl.tk.call("::tk::unsupported::MacWindowStyle", "style", tl._w, "plain", "none") >> > > I tried this (although, my tl is actually a tk instance): > > self.tk.call("::tk::unsupported::MacWindowStyle", "style", self.tk._w, > "plain", "none") > > and get this message: > > Traceback (most recent call last): > File "./ProgramCountdown.py", line 120, in > control = Controller(tk) > File "./ProgramCountdown.py", line 37, in __init__ > self.tk.call("::tk::unsupported::MacWindowStyle", "style", > self.tk._w, "plain", "none") > _tkinter.TclError: bad class: should be alert, moveableAlert, modal, > moveableModal, floating, help, or document > > Any thoughts? Can you do something similar on the tk instance itself? > Try something like this (assuming self.tk._w is the name of your window): self.tk._w.wm_attributes(fullscreen='true') -- Kevin Walzer Code by Kevin http://www.codebykevin.com From gerald.kaszuba at gmail.com Mon Aug 25 05:22:12 2008 From: gerald.kaszuba at gmail.com (Gerald Kaszuba) Date: Mon, 25 Aug 2008 02:22:12 -0700 (PDT) Subject: Python Google Chart 0.2.1 released Message-ID: <1f6b72b7-d57e-4848-8ea5-85a3e8c72e25@d1g2000hsg.googlegroups.com> pygooglechart 0.2.1 has been released. http://pygooglechart.slowchop.com/ Here are the changes: * Added support for QR Code chart (#8) * Added legend positioning (chdlp) (Steve Brandt) * Added line styles (chm=D) (Steve Brandt) * Added "colours within series" option to chart (chco=xxx|xxx) (Steve Brandt) * Added QR codes and more line examples * Axis labels are now casted to strings automatically * Bug fixed where pie charts stopped working due to automatic scaling * Bug fixed where the module would download twice (#7) (Evan Lezar) * Bug fixed when automatic scaling is on and None values are in a data set (#5) (Alec Thomas) * Bug fixed with auto-scaling, where the minimum y range was always 0. (#6) (Rohit Jenveja) * Bug fixed, replaced "1" with "0" in add_horizontal_range and add_vertical_range (incorrect syntax for Google) (Steve Brandt) * Better clipping checks I've also updated the home page with more examples. Gerald -- Gerald Kaszuba http://geraldkaszuba.com/ From deets at nospam.web.de Thu Aug 21 18:43:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 22 Aug 2008 00:43:50 +0200 Subject: Having trouble with tail -f standard input In-Reply-To: <735cf3a7-ca9d-4ce6-a501-beb5281c28b4@y38g2000hsy.googlegroups.com> References: <735cf3a7-ca9d-4ce6-a501-beb5281c28b4@y38g2000hsy.googlegroups.com> Message-ID: <6h69d6FjgeaoU1@mid.uni-berlin.de> sab schrieb: > Hello, > > I have been working on a python script to parse a continuously growing > log file on a UNIX server. The input is the standard in, piped in > from the log file. The application works well for the most part, but > the problem is when attempting to continuously pipe information into > the application via the tail -f command. The command line looks > something like this: > > tail -f | grep | python parse.py > > If I don't pipe the standard in to the python script, it displays any > new entries immediately on the screen. However, if I pipe the > information into the script, the sys.stdin.readline() doesn't get any > new data until a buffer fills, after which it parses a block of new > information all at once (output is fine). I need it to read the data > in real-time instead of waiting for the buffer to fill. I have tried > running the script with the -u parameter but that doesn't seem to be > doing anything. Also, if I run the program against a text file and > add a line to the text file (via cat >> ) it picks it up > right away. I'm sure that it's just a simple parameter that needs to > be passed or something along those lines but have been unable to find > the answer. Any ideas would be appreciated. Get rid of tail, it's useless here anyway and most probably causing the problem. If for whatever reason you can't get rid of it, try and see if there is any other way of skipping most of the input file - maybe creating *one* python script to seek to the end, grep & parse. You can't do anything in python though - the buffering and potential flushing is courtesy of the upper end of the pipe - not python. Diez From magloca at mailinater.com Thu Aug 21 13:48:45 2008 From: magloca at mailinater.com (magloca) Date: Thu, 21 Aug 2008 19:48:45 +0200 Subject: exception handling in complex Python programs References: <48ad8a47$0$30999$426a34cc@news.free.fr> Message-ID: <48adaa7e$0$4245$6e1ede2f@read.cnntp.org> Bruno Desthuilliers @ Thursday 21 August 2008 17:31: >>> If you mean "the exceptions *explicitely raised* by your code", then >>> I agree. But with any generic enough code, documenting any possible >>> exception that could be raised by lower layers, objects passed in as >>> arguments etc is just plain impossible. Like, if you have a function >>> that takes a file-like object as arg, you just cannot know in >>> advance what exceptions this object might raise. >>> >> >> This is one of the main concerns with which I started this c.l.py >> thread ! I think it's a pity that we have no way of anticipating and >> constraining the exceptions thrown by our code, > > Java's "checked exception" system has proven to be a total disaster. Could you elaborate on that? I'm not disagreeing with you (or agreeing, for that matter); I'd just really like to know what you mean by a "total disaster." m. From maric at aristote.info Sun Aug 24 10:02:30 2008 From: maric at aristote.info (Maric Michaud) Date: Sun, 24 Aug 2008 16:02:30 +0200 Subject: A variables variables In-Reply-To: References: <625fce19-df89-4a6c-890a-22008a4fe92f@c58g2000hsc.googlegroups.com> Message-ID: <200808241602.31380.maric@aristote.info> Le Sunday 24 August 2008 03:24:29 Terry Reedy, vous avez ?crit?: > Gandalf wrote: > > how can I declare a variable with another variable ?name? > > > > for example ?I will use PHP: > > > > $a= "hello"; > > > > $a_hello="baybay"; > > > > print ${'a_'.$a) ?//output: baybay > > > > > > how can i do it with no Arrays using ?python > > Others have given you the direct answer. Well using locals() is the right answer, it is a very bad use case for eval. > But using lists or dicts is > almost always a better solution in Python than synthesizing global/local > namespace names. > > a={'hello':'baybay'} > print a['hello'] But locals() *is* an already made dict, very convenient for use locally and read-only. >>>[155]: var1 = "easy" >>>[156]: var2 = "proper" >>>[157]: var3 = "locals" >>>[158]: print "a %(var2)s and %(var1)s use of %(var3)s with %(var3)s()" % locals() a proper and easy use of locals with locals() -- _____________ Maric Michaud From deets at nospam.web.de Mon Aug 4 11:55:51 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 04 Aug 2008 17:55:51 +0200 Subject: Agnostic fetching References: Message-ID: <6fon6gFcj7ecU1@mid.uni-berlin.de> Ivan Ven Osdel wrote: >>----- Original Message ----- >>From: "Diez B. Roggisch" >>To: python-list at python.org >>Sent: Saturday, August 2, 2008 11:05:07 AM GMT -06:00 US/Canada Central >>Subject: Re: Agnostic fetching > >>Bruce Frederiksen schrieb: >> On Fri, 01 Aug 2008 17:05:00 -0700, jorpheus wrote: >> >>> OK, that sounds stupid. Anyway, I've been learning Python for some >>> time now, and am currently having fun with the urllib and urllib2 >>> modules, but have run into a problem(?) - is there any way to fetch >>> (urllib.retrieve) files from a server without knowing the filenames? >>> For instance, there is smth like folder/spam.egg, folder/ >>> unpredictable.egg and so on. If not, perhaps some kind of glob to >>> create a list of existing files? I'd really appreciate some help, >>> since I'm really out of my (newb) depth here. >> >> You might try the os.path module and/or the glob module in the standard >> python library. > >>Not on remote locations. The only work on your local filesystem. > >>Diez > > Here's a function I wrote for checking remote or local file existence. It > works for me but admittedly I haven't tested many cases with it. Also its > currently specific to an http URI scheme. The idea was to *not* know the filenames beforehand, but instead get a directory-listing. Which is impossible to get. Diez From lists at cheimes.de Tue Aug 5 21:29:15 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 06 Aug 2008 03:29:15 +0200 Subject: pyprocessing/multiprocessing for x64? In-Reply-To: References: <5cqdnSE547L0QgXVnZ2dnUVZ_sLinZ2d@comcast.com> Message-ID: <4898FE6B.7080007@cheimes.de> Benjamin Kaplan wrote: > I don't have a 64-bit machine, so I can only go off of what I read. This is > from the AMD64 FAQ Welcome to the world of marketing. The FAQ just explains that AMD64 compatible processors can still run 32bit programs. It doesn't say that you can recompile your code for 64bit w/o trouble. It's possible to write software that compiles and works on all sorts of platforms and CPU architectures like X86, AMD64, IA64, PPC etc. The Python interpreter is a good example. However one can easily write C code that runs on 32bit X86 CPUs but crashes on 64bit systems. The same code may run on a 64bit Linux/BSD system but crashes on a Win32 X64 because 64bit Windows defines a long as a 32bit datatype, while a long on 64bit Unix systems has 64bits. Christian From fetchinson at googlemail.com Mon Aug 4 16:13:12 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 4 Aug 2008 13:13:12 -0700 Subject: Keg - A python web framework In-Reply-To: <3e371780808031457l75a10f51h883e1d96cca2943a@mail.gmail.com> References: <3e371780808031457l75a10f51h883e1d96cca2943a@mail.gmail.com> Message-ID: > I've been working on a python web framework which I think might be of > interest to you. > Details may be found at http://code.google.com/p/keg/wiki/Concept. > > > All suggestions or comments will be greatly appreciated. I fail to see what the advantages of your framework are over django or turbogears. The description you give on the above url doesn't really help as all the goals you state for your project are solved by both django and turbogears. I wouldn't want to be too discouraging but it seems you are led by the NIH principle which is not a really useful one in the open source world. You can expect exactly 0 users and no appreciation for your efforts which will/can lead to frustration and bad health. Contributing to an already existing and mature framework like django and turbogears can/will be on the other hand rewarding. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From kem1723 at yahoo.com Fri Aug 29 15:09:33 2008 From: kem1723 at yahoo.com (Kevin McKinley) Date: Fri, 29 Aug 2008 12:09:33 -0700 (PDT) Subject: Memory Leek, critique me. Thanks!!! Message-ID: <345943.80055.qm@web83909.mail.sp1.yahoo.com> cnb, That is on of the things i want to fix with this code. I meant to mention in my original post that i've only been programming with Python for a little over two weeks. The only other experience with programming i've had is with Basic on my TI-83 calculator in high school. This isn't my excuse to sloppy code, its just my explanation of why i've done the coding the way i have. I hope to keep getting better. Thanks, Kevin From zen167520_AT_zen_co_uk Tue Aug 5 04:48:24 2008 From: zen167520_AT_zen_co_uk (Tim Greening-Jackson) Date: Tue, 05 Aug 2008 09:48:24 +0100 Subject: Hobbyist - Python vs. other languages In-Reply-To: References: Message-ID: <489813d8$0$2509$da0feed9@news.zen.co.uk> Tobiah wrote: > You may enjoy: > > http://www.pythonchallenge.com/ > > It's a blast and a half. To solve the > puzzles you have to write python programs > that do various things. Thanks for that. I can see that will keep me amused for quote some time. From adtpowell at hotmail.com Wed Aug 6 10:57:31 2008 From: adtpowell at hotmail.com (Adam Powell) Date: Wed, 6 Aug 2008 07:57:31 -0700 (PDT) Subject: Dictionary to tree format (hopefully simple) References: <6fs2pbFd43utU1@mid.uni-berlin.de> Message-ID: Thanks very much for this, very concise! From max at alcyone.com Wed Aug 6 16:59:50 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 06 Aug 2008 13:59:50 -0700 Subject: Psycho question In-Reply-To: References: <8f0dc2a7-d3bd-4632-a282-9428c910088d@e53g2000hsa.googlegroups.com> Message-ID: <68SdnU6uHqxNjQfVnZ2dnUVZ_j6dnZ2d@speakeasy.net> David C. Ullrich wrote: > Thanks. I would have guessed that I'd want low-level style code; > that's the sort of thing I have in mind. In fact the only thing > that seems likely to come up right now is looping through an > array of bytes, modifying them. The plan is to use the array > module first to convert a string or a list to an array, outside > the accelerated part, then maybe do something like > > for j in range(len(bytes)/3): > g = (bytes[3*j] + bytes[3*j+1] + bytes[3*j+2])/3 > bytes[3*j] = bytes[3*j+1] = bytes[3*j+2] = g If len(bytes) is large, you might want to use `xrange`, too. `range` creates a list which is not really what you need. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis You and I / We've seen it all / Chasing our hearts' desire -- The Russian and Florence, _Chess_ From mattheww at chiark.greenend.org.uk Tue Aug 5 15:29:08 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 05 Aug 2008 20:29:08 +0100 (BST) Subject: Redirecting stderr and stdout to syslog References: Message-ID: In article , > How do I redirect ALL stderr stuff to syslog, even stderr from > external programs that don't explicitly change their own stderr? Sending messages to syslog involves more than writing to a file descriptor, so there's no way to make this happen without having some process read the external programs' output and send it to syslog (which is basically the 'logger' method that you said you didn't like). > Since in _theory_ nothing should be "leaking" out, if stuff does leak > out in practice, something is not quite right. > So I want all such "leaks" be redirected to syslog (or my logging > routines), so that I can see the bugs/warnings - whether in my > program or other programs/modules I call/use. One reasonable way to do this is to have a separate 'breakage log' file for this kind of message, and point standard error there. This will catch output from external programs, and any output to standard error which libraries in your main program (or the Python interpreter) decide to produce. You'd do that with something like this (untested): STDERR = 2 se = os.open("breakage.log", os.O_WRONLY|os.O_APPEND) os.dup2(se, STDERR) os.close(se) You can also use this breakage log for errors from your own program, if there are any cases where you think things might be too messed up for you to want to rely on your normal logging routines. Then since the breakage log should normally be empty, you can write a cronjob or something to keep an eye on it and notify you if anything appears there. -M- From adam2new at gmail.com Fri Aug 22 16:56:19 2008 From: adam2new at gmail.com (Adam E) Date: Fri, 22 Aug 2008 13:56:19 -0700 (PDT) Subject: Tkinter, toplevel and images References: Message-ID: On Aug 22, 9:17 am, Pedro wrote: > Hi > > I'm trying to build a small application that can display some images > in a toplevel window. I have this code: > > def Results(master): > from Tkinter import Toplevel, Button, Label > from PIL import ImageTk > > figures = ['first.png', 'second.png'] > > ResultsWindow = Toplevel(master) > ResultsWindow.title('Results') > > picts = [ImageTk.PhotoImage(file = x) for x in figures] > > butRW = Button(ResultsWindow, text = 'CLOSE', command = > ResultsWindow.destroy) > butRW.pack() > > height = sum([x.height() for x in picts]) > width = picts[0].width() > > y = 0 > for pict in picts: > label = Label(ResultsWindow,image=pict).pack() > y += pict.height() > > from Tkinter import Tk > root = Tk() > Results(root) > root.mainloop() > > and I just can see a grey window with a "close" button... However, > when I try the same code with the root I can see both images... Can > anyone give me a tip? > > Thanks! :) You can try making a class for the Tkinter.Toplevel window. I don't have PIL, but I know if you query for a widget's value when the window is not yet displayed, it will give a nearly 0-by-0 size result. You can also try to set a size for the Toplevel window and see if the images display. I have not encountered this before, but I only know what I have read from books (like Programming Python by O'Reilly) and have assumed. Good luck. From dear.jay.logan at gmail.com Sat Aug 30 20:59:18 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Sat, 30 Aug 2008 17:59:18 -0700 (PDT) Subject: SAXReaderNotAvailble: No parsers found Message-ID: <507a08c2-7291-481f-b7ab-edbcfb5ad765@s50g2000hsb.googlegroups.com> > Vincent Yau writes: > > I am trying to use Python SAX API to parse XML files. I do see expat.py > > somewhere underneath my Python 2.1.1 installation (on Solaris). > > But I got this error when invoking the xml.sax.make_parser() call. Any > > tip/help much appreciated. > > You should install Expat before building Python. Best, you edit > Modules/Setup to build pyexpat explicitly. > > Regards, > Martin Fast-forward to 2008 I installed Python 3.0b2 on a Windows Vista laptop (after having previously installed Python 2.5), and I am getting this same error: Traceback (most recent call last): File "Programming\Python\monkeys.py", line 24, in test_parse(sys.argv[1]) File "Programming\Python\monkeys.py", line 21, in test_parse xml.sax.parse(f, handler) File "C:\Python30\lib\xml\sax\__init__.py", line 30, in parse parser = make_parser() File "C:\Python30\lib\xml\sax\__init__.py", line 90, in make_parser raise SAXReaderNotAvailable("No parsers found", None) xml.sax._exceptions.SAXReaderNotAvailable: No parsers found I see a pyexpat.lib in the C:\Python30\libs folder. I also see a pyexpat.pyd in the C:\Python30\DLLs folder. It works in Python 2.5. I installed Python 3.0b2 as admin. Does anyone know what is wrong and how to fix it? From circularfunc at gmail.com Sat Aug 2 09:02:02 2008 From: circularfunc at gmail.com (ssecorp) Date: Sat, 2 Aug 2008 06:02:02 -0700 (PDT) Subject: Profiling weirdness: Timer.timeit(), fibonacci and memoization Message-ID: <59994541-2fb7-450c-ac14-9922d87b6aa1@m45g2000hsb.googlegroups.com> I am not clear about the results here. from timeit import Timer import Decorators def fib(n): a, b = 1, 0 while n: a, b, n = b, a+b, n-1 return b @Decorators.memoize def fibmem(nbr): if nbr > 1: return fibmem(nbr-1) + fibmem(nbr-2) if nbr == 1: return 1 if nbr == 0: return 0 s = 100 t1 = Timer('fib(s)', 'from __main__ import fib, s') t2 = Timer('fibmem(s)', 'from __main__ import fibmem, s') t1.repeat(number=1) t2.repeat(number=1) print t1.timeit() print t2.timeit() >>> 35.3092010297 1.6516613145 >>> So memoization is 20+ times faster than the idiomatic way? Or am I missing something here? Ok for fun I added memoization to the idiomatic one: from timeit import Timer import Decorators @Decorators.memoize def fib(n): a, b = 1, 0 while n: a, b, n = b, a+b, n-1 return b @Decorators.memoize def fibmem(nbr): if nbr > 1: return fibmem(nbr-1) + fibmem(nbr-2) if nbr == 1: return 1 if nbr == 0: return 0 s = 100 t1 = Timer('fib(s)', 'from __main__ import fib, s') t2 = Timer('fibmem(s)', 'from __main__ import fibmem, s') t1.repeat(number=1) t2.repeat(number=1) print t1.timeit() print t2.timeit() didn't think it would make a difference there but it certainly did. >>> 1.59592657726 1.60179436213 >>> ================================ RESTART ================================ >>> 2.66468922726 3.0870236301 >>> ================================ RESTART ================================ >>> 1.62921684181 1.51585159566 >>> ================================ RESTART ================================ >>> 1.49457319296 1.60948472501 >>> ================================ RESTART ================================ >>> 1.48718203012 1.6645559701 >>> From oekss461 at googlemail.com Sun Aug 24 15:13:40 2008 From: oekss461 at googlemail.com (oekss461 at googlemail.com) Date: Sun, 24 Aug 2008 12:13:40 -0700 (PDT) Subject: fremdgehen wie in Burg kontaktanzeigen karlsruhe www internet kontaktanzeigen kontaktanzeigen bremen www singletreff ch sex kontaktanzeigen chemnitz kontaktanzeigen mannheim kontakt anzeigen sex kontaktanzeigen karlsruhe christliche kontaktanzeigen kontaktanzeigen kiel kontaktanzeigen abenteuer erotik kontaktanzeigen duisburg nicht fremd gehen Message-ID: <0c4d1384-8569-4467-9971-b17254d6f460@e39g2000hsf.googlegroups.com> fremdgehen wie in Burg kontaktanzeigen karlsruhe www internet kontaktanzeigen kontaktanzeigen bremen www singletreff ch sex kontaktanzeigen chemnitz kontaktanzeigen mannheim kontakt anzeigen sex kontaktanzeigen karlsruhe christliche kontaktanzeigen kontaktanzeigen kiel kontaktanzeigen abenteuer erotik kontaktanzeigen duisburg nicht fremd gehen + + EROTIK KONTAKTE - EROTISCHE KONTAKTANZEIGEN http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ + + + + + + + + + + + http://kontaktanzeigen-saarbruecken.adult-kontakt.de http://nrw-kontaktanzeigen.adult-kontakt.de http://single-treff-st.adult-kontakt.de http://hamburg-kontaktanzeigen.adult-kontakt.de http://cheaters-fremdgehen.adult-kontakt.de erotische kontaktanzeigen nuernberg free kontaktanzeigen in Jever erotische kontaktanzeigen saarland sex kontaktanzeigen magdeburg in Cloppenburg www fremdgehen tut kontaktanzeigen cottbus in Coesfeld lustige kontaktanzeigen mehr fremdgehen in Pinneberg singletreff christlich kontaktanzeigen singels in Donauwoerth fremdgehen um russlanddeutsche erotische kontaktanzeigen in Ha?furt singles kontaktanzeigen singletreff st in Aschersleben man fremdgehen kontaktanzeigen finden in Germersheim * fremdgehen richtig fremdgehen in Schwandorf erotik kontaktanzeigen deutschland kontaktanzeigen kostenlos in Westerstede kontaktanzeigen mannheim singletreff mannheim in Schrobenhausen free kontaktanzeigen russlanddeutsche kontaktanzeigen in Ravensburg Dine.com kontaktanzeigen saarland in Marktoberdorf singletreff ?sterreich kontaktanzeigen er sucht ihn in Helmstedt single treff ?sterreich erotik kontaktanzeigen trier in Eutin christliche erotische kontaktanzeigen fremdgehen um in L?neburg christliche erotische kontaktanzeigen private erotische kontaktanzeigen in Bad http://www.meinews.net/buy-t244237.html - Cams.com kontaktanzeigen cottbus in Ploen http://www.bloglines.com/forums/read.php?21,71690 - fremdgehen geschichten kontaktanzeigen nrw in Wittgenstein http://www.bebin.tv/forum/showthread.php?t=31389 - kontaktanzeigen flirt www internet kontaktanzeigen com in Harburg http://www.rwdmag.com/forum/member.php?u=52279 - fremdgegangen de kontaktanzeigen test in Lindau http://www.meinews.net/hdmi-t226255.html - kontaktanzeigen baden kontaktanzeigen erfurt in Aalen http://forum.tag-board.com/showthread.php?t=23719 - suche frau zum fremdgehen Grad Finder com in Bad http://www.bebin.tv/forum/showthread.php?t=31409 - www kontaktanzeigen net fremdgehen gut in Dillingen http://www.bloglines.com/forums/read.php?10,71560 - Share Rent com single kontaktanzeigen org in Aschaffenburg http://www.meinews.net/asking-t244239.html - singletreff flensburg www kontaktanzeigen in Koblenz http://www.bloglines.com/forums/read.php?17,98766 - seri?se kontaktanzeigen kontaktanzeigen ingolstadt in Grevenbroich http://www.gamesforum.ca/showthread.php?t=317056 - single treff duisburg kontaktanzeigen software in Goeppingen http://draconian.com/dragon-forum/showthread.php?t=17712 - sex kontaktanzeigen berlins sex kontaktanzeigen nuernberg in Lauf a.d. Pegnitz http://www.meinews.net/hdmi-t226272.html - erotische kontaktanzeigen moenchengladbach single treff ohne in Freyung http://draconian.com/dragon-forum/showthread.php?t=20415 - kontaktanzeigen m?nchengladbach kontaktanzeigen freiburg in Perleberg From stef.mientki at gmail.com Tue Aug 12 15:06:35 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 12 Aug 2008 21:06:35 +0200 Subject: export sites/pages to PDF In-Reply-To: References: Message-ID: <48A1DF3B.50200@gmail.com> jvdb wrote: > Hi all, > > My employer is asking for a solution that outputs the content of urls > to pdf. It must be the content as seen within the browser. > Can someone help me on this? It must be able to export several kind of > pages with all kind of content (javascript, etc.) > -- > http://mail.python.org/mailman/listinfo/python-list > pdfCreator does the job. cheers, Stef From magloca at mailinater.com Thu Aug 7 17:08:10 2008 From: magloca at mailinater.com (magloca) Date: Thu, 07 Aug 2008 23:08:10 +0200 Subject: Testing for the first few letters of a string References: <3b45ec2e-d79a-4c88-945e-5376189bedfb@l33g2000pri.googlegroups.com> Message-ID: <489b643a$0$4242$6e1ede2f@read.cnntp.org> John Machin wrote: >> import re >> template = '^My name is alex' > > The ^ is redundant. Didn't the OP want to match only at the beginning of the string? m. From george.sakkis at gmail.com Sat Aug 9 09:28:23 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 9 Aug 2008 06:28:23 -0700 (PDT) Subject: list question... unique values in all possible unique spots References: Message-ID: On Aug 9, 9:05?am, ToshiBoy wrote: > I'm wondering how to do this the most elegant way: I found this quiz > in some magazine. I've already solved it on paper, but want to write a > python program to solve it. It comes down to being able to represent > range(1,27) through a number of formulas. How do I write a loop that > will loop through this list, so that: 1. every number only occurs > once, and 2. I get every possibility of order within the list? I guess > it'd be somewhat similar to Sudoku, where you have the numbers from > 1-9 in any possible order. Here it's 1-26. Search for a permutation generator function. George From maric at aristote.info Mon Aug 18 07:52:11 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 18 Aug 2008 13:52:11 +0200 Subject: help with parsing email In-Reply-To: References: Message-ID: <200808181352.11545.maric@aristote.info> Le Monday 18 August 2008 12:43:02 Gabriel Genellina, vous avez ?crit?: > En Thu, 14 Aug 2008 12:50:57 -0300, Ahmed, Shakir escribi?: > > I need to grab/parse numeric numbers such as app number from incoming > > emails stored in Microsoft Outlook (Microsoft Exchange server) with > > specified subject line. > > > > The email body is like this > > > > myregion ; tst ; 11-Aug-2008 > > > > http://my.xyz.com/dddd/content/ifs/apps/myDocFolder/NoticeOfapplication/0 > >80612-21_test_337683.pdf > > > > I need to extract 080612-21_ number from above line from incoming > > emails. > > I can't help with the part dealing with Outlook - but once you retrieved > the email body, it's easy: Three options here : - dealing directly with outlook mailboxes files, I used some open source code to parse .pst files in past, but you'll need some googling to match your requirements. Doesn't help if there is an instance of outlook running on the box. - use the outlook COM or even some windows MAPI interface via WIN32 API (pywin32), can't help with this one. - access emails directly on the Exchange server via standard python modules poplib or imaplib, my preferred choice if one of these protocols are supported by your environment. You won't need no extensions, just a standard python installation, and your code will work with most mail delivery agent and will run on all python supported platform. -- _____________ Maric Michaud From boblatest at yahoo.com Sat Aug 9 08:02:33 2008 From: boblatest at yahoo.com (Robert Latest) Date: 9 Aug 2008 12:02:33 GMT Subject: mktime overflow in March 2008? References: <6g0tsaFdrcrhU1@mid.uni-berlin.de> Message-ID: <6g5faoFecb7hU1@mid.uni-berlin.de> Tim Roberts wrote: > What time zone are you in? March 30, 2008, was a Sunday. If that happened > to be the date your country transitioned to summer time, then the hour > between 2 AM and 3 AM would not exist. > > Does it work if you use 3:43 AM? Actually you're right; I'm in Middle Europe, and DST was started on March 30, 2am. I need to check this. robert From simon at brunningonline.net Tue Aug 26 04:29:27 2008 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 26 Aug 2008 09:29:27 +0100 Subject: How to manipulate list of dictionary In-Reply-To: <012b01c9074a$c3489ce0$1f01a8c0@RAZAK> References: <012b01c9074a$c3489ce0$1f01a8c0@RAZAK> Message-ID: <8c7f10c60808260129u70f85f46ie0ce86156296d8b3@mail.gmail.com> 2008/8/26 ajak_yahoo : > Need some help, I have a list of dictionary as below, > > table = [{"Part #":"Washer","Po #":"AE00128","qty":100}, > {"Part #":"Brake Pad","Po #":"AE00154","qty":150}, > {"Part #":"Mesh","Po #":"AE00025","qty":320}, > {"Part #":"Mouse","Po #":"AE00207","qty":120}, > {"Part #":"Insulator","Po #":"AE0013","qty":190}] > > How to manipulate the table? > > I need to search for the Po #, and display the result as below. > > > Part # : Mouse > Po # : AE00207 > Qty : 120 pcs Well, that's a really bad data structure for what you want to do, but you can do it with something like (untested): wanted = 'AE00207' for part in table: if part['Po #'] == wanted: print "Part #:\t%(Part #)s\nPo #:\t%(Po #)s\nQty #:\t%(qty)s" % part -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From vat.vjay10 at gmail.com Sun Aug 24 08:54:00 2008 From: vat.vjay10 at gmail.com (vat.vjay10 at gmail.com) Date: Sun, 24 Aug 2008 05:54:00 -0700 (PDT) Subject: get more info for your bright future Message-ID: <2342099b-c2b1-43b9-ad73-dad1159cd165@r15g2000prd.googlegroups.com> http://www.moneymaking4.blogspot.com/ From vrshah at gmail.com Mon Aug 25 02:26:19 2008 From: vrshah at gmail.com (Vishal) Date: Sun, 24 Aug 2008 23:26:19 -0700 (PDT) Subject: How to check in CGI if client disconnected References: <75a68632-1f47-48d7-a890-fe1b92484c2a@w24g2000prd.googlegroups.com> Message-ID: <57942430-2040-4a42-8d3b-f9248aee21be@r35g2000prm.googlegroups.com> Hi, Thanks for the replies. In my case, the cgi is sending a large file to the client. In case the the stop button is pressed on the browser to cancel the download, i want to do some cleanup action. It's all one- way transfer in this case, so i can't expect the client to send anything to me. I read somewhere that apache sends the SIGTERM signal to a cgi when the client disconnects. However, my cgi is not getting the signal - is there a way to have the cgi catch and handle the SIGTERM? I tried using the signal module --- def sigtermHandler(signum, frame): # do some cleanup signal.signal(signal.SIGTERM, sigtermHandler) --- But even this doesn't work. Regards, -vishal. On Aug 25, 2:58?am, "Gabriel Genellina" wrote: > En Sun, 24 Aug 2008 17:51:36 -0300, Wojtek Walczak escribi?: > > > On Sun, 24 Aug 2008 17:21:52 -0300, Gabriel Genellina wrote: > >>> ? ?I am writing a CGI to serve files to the caller. I was wondering if > >>> there is any way to tell in my CGI if the client browser is still > >>> connected. If it is not, i want to execute some special code before > >>> exiting. > > >>> ? ?Is there any way to do this? Any help on this is appreciated :) > > >> I don't think so. A CGI script runs once per request, and exits. The server may find that client disconnected, but that may happen after the script finished. > > > I am not a web developer, but I think that the only way is to > > set a timeout on server side. You can't be sure that the client > > disconnected, but you can stop CGI script if there's no > > action on client side for too long. > > Which kind of client action? Every link clicked or form submitted generates a different request that triggers a CGI script; the script starts, reads its parameters, do its task, and exits. There is no "long running process" in CGI - the whole "world" must be recreated on each request (a total waste of resources, sure). > > If processing takes so much time, it's better to assign it a "ticket" - the user may come back later and see if its "ticket" has been finished, or the system may send an email telling him. > > -- > Gabriel Genellina From code at pizzashack.org Wed Aug 27 19:27:47 2008 From: code at pizzashack.org (Derek Martin) Date: Wed, 27 Aug 2008 19:27:47 -0400 Subject: Setting my Locale In-Reply-To: References: <9611.72753382034$1219748098@news.gmane.org> Message-ID: <20080827232747.GC29228@dragontoe.org> On Wed, Aug 27, 2008 at 01:25:49AM -0300, Gabriel Genellina wrote: > En Tue, 26 Aug 2008 07:52:21 -0300, Robert Rawlins > >How can I get a list of available locales? > > I'd like to know how to retrieve that too... On a Linux system (and likely most modern Unix systems): locale -a -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From demarcheb at gmail.com Wed Aug 13 04:59:14 2008 From: demarcheb at gmail.com (Palindrom) Date: Wed, 13 Aug 2008 01:59:14 -0700 (PDT) Subject: How to best explain a "subtle" difference between Python and Perl ? References: <4290ea3f-43b9-455d-bd60-587369842c5b@s50g2000hsb.googlegroups.com> <662b41c4-cd67-4bd9-b95d-2e4b9770e75b@v13g2000pro.googlegroups.com> Message-ID: <50ca6394-0309-4dfb-9603-80c4585c52ea@e39g2000hsf.googlegroups.com> On Aug 13, 2:12?am, Jonathan Gardner wrote: > On Aug 12, 9:17?am, Palindrom wrote: > > > > > Hi everyone ! > > > I'd like to apologize in advance for my bad english, it's not my > > mother tongue... > > > My girlfriend (who is a newbie in Python, but knows Perl quite well) > > asked me this morning why the following code snippets didn't give the > > same result : > > > ### Python ### > > > liste = [1,2,3] > > > def foo( my_list ): > > ? ? my_list = [] > > > foo(liste) > > > print liste# she expected liste to be an empty list > > > ### Perl ### > > > @lst =(1,2,3); > > $liste =\@lst; > > foo($liste); > > print "@lst\n"; > > > sub foo { > > ?my($my_list)=@_; > > ?@{$my_list}=() > > > } > > > I have to admit that I don't know how to clearlyexplainto her the > > differences between these results. > > Could someone please help us understand these difference between > > Python and Perl ? > > David Ullrich gives a great and complete answer. I want to focus on > some of the subtleties. > > Perl and C share a lot in common. There are "direct" variables, things > like numbers and arrays. These aren't references to object, but the > object is itself stored in the variable. That is, you can't talk about > the thing that is '@lst' without creating a reference to it. > > Python, on the other hand, doesn't have direct variables. Well, it > does, it is just that all of the direct variables are really pointers > or references to the values they reference. > > Imagine a perl where you are only allowed to use scalars, and > specifically, scalars that are references to object but not references > to references. That is the Python variable system. > > To be more concrete... > > This statement cannot be expressed in Python: > > ?@lst = (1, 2, 3); ? ?# perl > > However, you can create an arrayref (perl) / list (Python) and assign > a scalar (perl) / variable (Python) to reference it: > > ?$liste = [1, 2, 3]; ?# perl > ?liste = [1, 2, 3] ? ?# Python > > Likewise, this statement cannot be expressed in Python: > > ?$refref = \$ref; ? ? # perl > > Although you can cheat in both perl and Python to get a similar > result: > > ?$refref = [$ref] ? ? # perl > ?refref = [ref] ? ? ? # python > > As far as the functions, the Python version and the perl version are > doing two completely different things. David explains how to write a > Python version that does what the perl version is doing. If you wanted > a perl version that did what your python version did, it would look > like this: > > ?sub foo { > ? ?my ($my_list) = ?@_; > ? ?$my_list = []; > ? ?return undef; > ?} > > Is Python's variable system better than perl's? It depends on which > way you prefer. As for me, being a long-time veteran of perl and > Python, I don't think having a complicated variable system such as > perl's adds anything to the language. Python's simplicity in this > regard is not only sufficient, but preferable. Thank you Jonathan for your extensive and clear response ! I agree with you, Python's variable system is eazier to understand. Regards. From norseman at hughes.net Fri Aug 22 13:31:27 2008 From: norseman at hughes.net (norseman) Date: Fri, 22 Aug 2008 10:31:27 -0700 Subject: Overwriting property-> can't set attribute In-Reply-To: References: Message-ID: <48AEF7EF.9040401@hughes.net> Gregor Horvath wrote: > Hi, > > why is this code failing? > > class B(object): > pass > > B.testattr = property(lambda s:"hallo") > b = B() > b.testattr = "test" > > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > > /tmp/python-14202ViU.py in () > 14 B.testattr = property(lambda s:"hallo") > 15 b = B() > ---> 16 b.testattr = "test" > 17 > 18 > > : can't set attribute > > -- > Greg > -- > http://mail.python.org/mailman/listinfo/python-list > ==================================== b = B() # synonyms When B.testattr = "hallo" so does b.testattr So if in subsequent code: B.testattr = property(lambda s:"test") Then: b.testattr yields "test" unless b was essentially destroyed/reused in between times this is how/why things like: gc = damn-lot-of-typing-due-to-long-names gc.something works as if it was: damn-lot-of-typing-due-to-long-names.something Steve norseman at hughes.net From brtzsnr at gmail.com Tue Aug 26 11:18:00 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Tue, 26 Aug 2008 08:18:00 -0700 (PDT) Subject: atomic increment Message-ID: <6297cf93-5eec-4bf3-9104-0605a82f7186@p10g2000prf.googlegroups.com> how can i do an atomic read+increment? something like with lock: old = atomic_int atomic_int += 1 but in one operation From simon at brunningonline.net Wed Aug 13 12:56:43 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 13 Aug 2008 17:56:43 +0100 Subject: gasp In-Reply-To: <65dba773-6441-424e-a019-dc1e493dddb7@v57g2000hse.googlegroups.com> References: <65dba773-6441-424e-a019-dc1e493dddb7@v57g2000hse.googlegroups.com> Message-ID: <8c7f10c60808130956l19553772u62d8f993f610a0bc@mail.gmail.com> 2008/8/13 kumwaka : > I am a beginner in Python. Please tell me how to go about in > downloading and installing the module gasp.I am using Python 2.5.2. Does this work? easy_install gasp -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From kay.schluehr at gmx.net Sat Aug 16 08:08:16 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 16 Aug 2008 05:08:16 -0700 (PDT) Subject: Confused: looking for a simple XML parser References: <04f57893-3f08-41a6-b2a7-defb069c4978@x16g2000prn.googlegroups.com> Message-ID: <5c4d3a73-cf4d-4e91-b6bd-45bb1980d832@w7g2000hsa.googlegroups.com> On 16 Aug., 02:21, Rex wrote: > Hello, > > I am a Python programmer facing my first small XML project. I am > looking to find a simple tool to take an XSD file and convert the XSD > tree structure to another text format (e.g. an adjacency matrix for > the tree's graph), or convert one xml file format definition into > another, non-xml one. I don't need to validate XML documents created > by this schema or do anything else fancy. I just need to be able to > traverse this tree programmatically and find which child attributes > belong to which parent attributes, etc. > > There seem to be so many Python libraries and programs out there that > I don't know what to use. > > What tool should I use? > > Thanks, > Rex Many people seem to be happy with elementree and it might be the most adequate parser for your purposes. Personally I'm sticking with expat and define handlers to build custom data structures. Both expat and elementree are available in the standard library. http://docs.python.org/lib/module-xml.parsers.expat.html http://docs.python.org/lib/module-xml.etree.ElementTree.html From keith.hughitt at gmail.com Wed Aug 13 10:30:10 2008 From: keith.hughitt at gmail.com (Keith Hughitt) Date: Wed, 13 Aug 2008 07:30:10 -0700 (PDT) Subject: Corrupted images after attempting to store PNG images as BLOBs in MySQL? Message-ID: <73674d9f-891b-4acb-8a01-a20232ecf8ce@34g2000hsh.googlegroups.com> Hi all, I've run into a strange error while trying to store some PNG images in a MySQL database using MySQLdb. When I try to insert smaller images (< 64kb or so) everything seems to work fine. When I start trying to insert larger images (~150kb), however, the images get corrupted along the way. The result is that only part of the image, e.g. the top 30% of the image, is stored in the database, and the rest is simply transparent. Furthermore, if I attempt to view the image in mysql-query-browser, it does not display and simply states "Cannot display as image data," which seems to further suggest the idea that the data is being corrupted somewhere along the way. To store the image I'm using: blob = open(img, 'rb').read() sql = "INSERT INTO table VALUES('%s')" % (MySQLdb.escape_string(blob)) Anyone have any ideas? Thanks, Keith From tjreedy at udel.edu Tue Aug 5 01:47:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 05 Aug 2008 01:47:40 -0400 Subject: Class definition attribute order In-Reply-To: References: <5fb776ae-e3d7-49ec-9ebf-350b9bf9cac1@l42g2000hsc.googlegroups.com> Message-ID: Michele Simionato wrote: > On Aug 5, 4:38 am, "Gabriel Genellina": >> So the namespace that the metaclass receives when the class is created, >> will be some kind of ordered dictionary? >> Metaclasses are available for a long time ago, but the definition order is >> lost right at the start, when the class body is executed. Will this step >> be improved in Python 3.0 then? >> > > Yep. See http://stacktrace.it/articoli/2008/01/metaclassi-python-3000 > (I am working on an English translation these days, > but for the moment you can use Google Translator). Bfiefly, as I understood the discussion some months ago: In 2.x, the class body is executed in a local namespace implemented as a normal dict and *then* passed to the metaclass. In 3.0, the metaclass gets brief control *before* execution so, among other possibilities, it can substitute an (insertion) ordered dict for the local namespace. I will leave the details to Michele's article and its eventual translation. tjr From digetl.try at gmail.com Tue Aug 12 05:28:08 2008 From: digetl.try at gmail.com (raja) Date: Tue, 12 Aug 2008 02:28:08 -0700 (PDT) Subject: Creating a Site? Message-ID: Don't Forget Your Own Toolbar Keep The User a Step Away. Act Now http://finance4u.synthasite.com/ From marco.bizzarri at gmail.com Sat Aug 30 08:45:05 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 30 Aug 2008 14:45:05 +0200 Subject: __stack_chk_fail_local In-Reply-To: <1217e9d2-b81f-471d-854e-4f39ad9b40f5@x35g2000hsb.googlegroups.com> References: <40a21602-a613-484b-aae4-4643dab9e146@8g2000hse.googlegroups.com> <1217e9d2-b81f-471d-854e-4f39ad9b40f5@x35g2000hsb.googlegroups.com> Message-ID: <3f0d61c40808300545h372ffbfcg7d51d955da034a63@mail.gmail.com> The ldd should point you to the library which is not loaded. Maybe the library you need is not in one of the normal locations in your Linux/Unix path. Normally, the linker looks for library under /lib and /usr/lib, and maybe other paths specified in /etc/ld.so.conf If you know the library is installed in your system, you can force the linker to look for it, either modifying your /etc/ld.so.conf (better if you know what you're doing, however) or, just setting the LD_LIBRARY_PATH variable: export LD_LIBRARY_PATH=/some/non/standard/lib/dir/ python -c "import foo" Another possibility, which you can check googling a little, is that you've two different versions of the libarary around your system, and that you're loading the wrong one (i.e., python is looking at the wrong one) again, setting the LD_LIBRARY_PATH should help Regards Marco On Sat, Aug 30, 2008 at 2:33 PM, gianluca wrote: > On 30 Ago, 12:05, "Marco Bizzarri" wrote: >> On Fri, Aug 29, 2008 at 7:53 PM, gianluca wrote: >> > hy list, >> > I've built _libfoo.so and libfoo.py library with swig and I've copied >> > in /usr/lib/python2.5/lib-dynload/ but when import the module >> >> >>>import libfoo >> >> > I've that message >> >> > Traceback (most recent call last): >> > File "", line 1, in >> > ImportError: /usr/lib/python2.5/lib-dynload/_libfoo.so: undefined >> > symbol: __stack_chk_fail_local >> >> > Could anybody help me? >> >> > gianluca >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> Have you tried to use ldd against the _libfoo.so to check if it is >> able to get all the libraries it needs? >> >> Regards >> Marco >> >> -- >> Marco Bizzarrihttp://iliveinpisa.blogspot.com/ > > I've tried with ldd and the library aren't loaded. I don't use my *.i > interface so is quite difficult modify it (realy, the libraru is > supplied with make). > > Any suggests? > gianluca > -- > http://mail.python.org/mailman/listinfo/python-list > -- Marco Bizzarri http://iliveinpisa.blogspot.com/ From maoxw at tradeinfo.cn Tue Aug 12 04:09:28 2008 From: maoxw at tradeinfo.cn (maoxw at tradeinfo.cn) Date: Tue, 12 Aug 2008 01:09:28 -0700 (PDT) Subject: internet searching program References: <304d52cb-a8a8-46d5-81be-4eb01c73d479@26g2000hsk.googlegroups.com> <00ad1698$0$20318$c3e8da3@news.astraweb.com> <05d0cd73-f2cf-457d-abbd-c569f7720010@p10g2000prf.googlegroups.com> Message-ID: On 8?12?, ??1?44?, alex23 wrote: > On Aug 12, 12:03 am, "Support Desk" wrote: > > > Google does'nt allow use of their API's anymore, I belive Yahoo has one > > Are you sure? > > "Google Custom Search enables you to search over a website or a > collection of websites. You can harness the power of Google to create > a search engine tailored to your needs and interests, and you can > present the results in your website. Your custom search engine can > prioritize or restrict search results based on websites you specify." > > http://code.google.com/apis/customsearch/ http://www.muffler-silencer.com [url=http://www.muffler-silencer.com]V-4 type Series Muffler[/url] [url=http://www.muffler-silencer.com]B type Series Muffler[/url] From bedouglas at earthlink.net Mon Aug 25 14:20:18 2008 From: bedouglas at earthlink.net (bruce) Date: Mon, 25 Aug 2008 11:20:18 -0700 Subject: python/xpath issue.. In-Reply-To: <0de501c906a8$99a7e780$0301a8c0@tmesa.com> Message-ID: <0ef601c906df$3c1b3720$0301a8c0@tmesa.com> never mind... it was an issue with the targeted site... it's sending screwed up html the times when i get an err... thanks though! -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of bruce Sent: Monday, August 25, 2008 4:49 AM To: python-list at python.org Subject: python/xpath issue.. hey guys... got a weird, hopefully simple issue. the following sample bit of script is stripped down, and simply gets the "form" node from the specified site "schedule.psu.edu". the problem i run into is that the dom/xpath from the libxml2dom works, and i get the dom object everytime i run the app, but that the xpath is intermittent!!! in other words, i can run the script 10 times.. and it might work 7 or 8 times.. the other times, the xpath doesn't give the nodes back... when it works, name1_ in the app should be a list of nodes (for the 2 forms in the page). and len_ should be 2. is there anything you might suggest that i try in order to get a better handle on exactly what might be going on here... keep in mind, i'm not a python guy, just trying to get this to consistently work... my suspicion is that the culprit might be memory related... i'm running linux, on a x86 dual core with 4G ram. the python is 2.5.1. thoughts/comments/etc would be appreciated... -thanks!!! #!/usr/bin/python # # test.py # # scrapes/extracts the basic data for the college # # # the app gets/stores # name # url # address (street/city/state # phone # ###################################################################### #test python script import re import libxml2dom import urllib import urllib2 import sys, string from mechanize import Browser import mechanize #import tidy import os.path import cookielib from libxml2dom import Node from libxml2dom import NodeList import subprocess import time ######################## # # Parse pricegrabber.com ######################## ##cj = "p" ##COOKIEFILE = 'cookies.lwp' #cookielib = 1 urlopen = urllib2.urlopen #cj = urllib2.cookielib.LWPCookieJar() ##cj = cookielib.LWPCookieJar() Request = urllib2.Request br = Browser() br2 = Browser() ##if cj != None: ## print "sss" ###install the CookieJar for the default CookieProcessor ## if os.path.isfile(COOKIEFILE): ## cj.load(COOKIEFILE) ## print "foo\n" ## if cookielib: ## opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) ## urllib2.install_opener(opener) ## print "foo2\n" user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values1 = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } url="http://schedule.psu.edu/" #======================================= if __name__ == "__main__": # main app txdata = None #---------------------------- ##br.set_cookiejar(cj) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.addheaders = [('User-Agent', 'Firefox')] print "url =",url br.open(url) ##cj.save(COOKIEFILE) # resave cookies res = br.response() # this is a copy of response s = res.read() print "slen=",len(s) # s contains HTML not XML text d = libxml2dom.parseString(s, html=1) print "d",d name_=[] len_=0 name_ = d.xpath("//form") #name_ = d.xpath("/html/body/form") print "name1",name_ len_ = len(name_) print "len",len(name_) #print "sdlfs" sys.exit() # else: # print "err in form_ID" print "here..." -- http://mail.python.org/mailman/listinfo/python-list From wolfgang.grafen at ericsson.com Fri Aug 15 14:25:15 2008 From: wolfgang.grafen at ericsson.com (Wolfgang Grafen) Date: Fri, 15 Aug 2008 20:25:15 +0200 Subject: Passing an object through COM which acts like str but isn't In-Reply-To: <7256565d-f8a1-4e47-91de-cd86ec5b31b5@v13g2000pro.googlegroups.com> References: <3c632ccb-2fb0-436f-ae7f-b2c3ae5c803f@s1g2000pra.googlegroups.com> <7256565d-f8a1-4e47-91de-cd86ec5b31b5@v13g2000pro.googlegroups.com> Message-ID: Rafe schrieb: > On Aug 15, 10:27 pm, Wolfgang Grafen > wrote: >> Rafe schrieb: >> >>> Now if I try to pass this as I would a string, roughly like so... >>>>>> s = StrLike("test") >>>>>> Application.AnObject.attribute = "test" # works fine >>>>>> Application.AnObject.attribute = s >>> ERROR : Traceback (most recent call last): >>> File " ------=_NextPart_000_22D9BBBE_1.3E24F6BA-- ------=_NextPart_000_22D9BBBE_0.3E24F6BA-- From dullrich at sprynet.com Fri Aug 8 13:18:19 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 08 Aug 2008 12:18:19 -0500 Subject: Psycho question References: Message-ID: In article , "Delaney, Timothy (Tim)" wrote: > David C. Ullrich wrote: > > > f: 0.0158488750458 > > g: 0.000610113143921 > > h: 0.00200295448303 > > f: 0.0184948444366 > > g: 0.000257015228271 > > h: 0.00116610527039 > > I suspect you're hitting the point of diminishing returns with g, and > any further investigations into optimisation are purely for fun and > learning ;) No doubt. Hadn't meant to get into optimization, at least not here, but various people made various comments - when someone suggests this or that seems like I should try it. Curiously g is exactly how I'd planned on doing it before trying anything. The one thing that puzzles me about all the results is why // is so much slower than / inside that Psyco loop. > Tim Delaney -- David C. Ullrich From straton at lampsacos.demon.co.uk Mon Aug 25 18:09:52 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Mon, 25 Aug 2008 23:09:52 +0100 Subject: Private attribute In-Reply-To: <6hgmj5Flo1i6U4@mid.uni-berlin.de> References: <076a50cb-99ad-44c5-b4eb-17a45ee1abe9@c65g2000hsa.googlegroups.com> <6hgmj5Flo1i6U4@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Mon, 25 Aug 2008 21:44:49 +0100, Ken Starks wrote: > >>>> #################### >>>> >>>> def __getattr__(self,attrname): >>>> if attrname == 'gridsize': >>>> return 0.8 >>>> >>>> def __setattr__(self,attrname,value): >>>> if attrname == 'gridsize': >>>> pass >>>> else: >>>> self.__dict__[attrname]=value >>> [?] >> I admit I haven't used properties, and had to look them up. Pretty cool >> indeed ! But an extra unnecessary level of complexity for my needs >> here, I feel. > > Compare this with your approach above and point out the extra complexity > please: > > @property > def gridsize(self): > return 0.8 > > Ciao, > Marc 'BlackJack' Rintsch mea culpa. As i mentioned, I haven't used them before. I have already changed my class Foo: to class Foo(object): and I'll do the rest tomorrow. From deets at nospam.web.de Wed Aug 27 08:43:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 27 Aug 2008 14:43:27 +0200 Subject: unexpected from/import statement behaviour References: <42780654-8a54-470e-a494-ca53fd0504f5@p25g2000hsf.googlegroups.com> <7dbab131-7f7b-4266-b706-fff52670e9e1@l64g2000hse.googlegroups.com> Message-ID: <6hl0gdFmjg0iU2@mid.uni-berlin.de> nisp wrote: > On Aug 27, 9:56 am, Peter Otten <__pete... at web.de> wrote: >> nisp wrote: >> > Hi all ! >> >> > I'm trying to capture stderr of an external module I use in my python >> > program. I'm doing this >> > by setting up a class in my module overwriting the stderr file object >> > method write. >> > The external module outputs to stderr this way: >> >> > from sys import std err >> >> > .... >> >> > print >> stderr, "Some text" >> >> > While in my module I use >> >> > import sys >> >> > ..... sys.stderr ... sys.stdout >> >> > Well, as long as I do not change in the external module those from/ >> > import statements to just >> >> > import sys >> >> > .... >> >> > print >> sys.stderr, "Some text" >> >> > I'm not able to capture its stderr and of course I would like not to >> > do this kind of change. >> > I've always been convinced of the equivalence of the two ways of using >> > the import statement >> > but it's clear I'm wrong :-( >> >> > Please, someone can tell me what's going on ? >> >> > Thanks in advance ! >> >> A practical approach to complement Diez' link to the explanation: >> >> Instead of modifying the external module you can either redirect stderr >> before you import the external module >> >> import sys >> sys.stderr = whatever >> import external >> >> or monkey-patch: >> >> import sys >> import external >> >> sys.stderr = external.sterr = whatever >> >> Peter > > Hi all ! > > Thanks first of all ! I read the interesting Diez's link but something > still remains to me unclear, on the other hand it's clear the my > problem is concentrated there and on symbols. > Here is what I'm trying to do > > HelloWorld.py: this is a real simplification of my external module > though still reflecting its structure (commented out is the version > that, let's say, works) > > from sys import stderr This is your problem. You create a HelloWorld.stderr-alias to the object bound to sys.stderr. Rebinding the latter won't affect the former. That is precisely what the link I gave you explains. The short answer to the whole issue is: dont' use the from-import syntax until you really know what you are doing. Or not at all. Diez From steve at REMOVE-THIS-cybersource.com.au Mon Aug 18 10:23:20 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2008 14:23:20 GMT Subject: Bizarre method keyword-arg bug. References: <73104fb9-3f05-445e-83e6-2b1939316f15@d77g2000hsb.googlegroups.com> <4b056d24-5d3c-4610-a551-1a917fd765d4@m36g2000hse.googlegroups.com> Message-ID: <00b980c0$0$20315$c3e8da3@news.astraweb.com> On Mon, 18 Aug 2008 04:07:14 -0700, Paul Boddie wrote: > Ultimately, I suppose one could enforce some kind of least surprising > "best practice" by limiting default parameter values to being literals > of immutable objects or names, as opposed to expressions, thus > eliminating some potential confusion. -1 Firstly, I *like* the ability to use mutable objects as default arguments. I don't do it often, but when I do, I do it deliberately. I find it useful. Secondly, I think forbidding expressions as default arguments would be far worse than the so-called "problem" you wish to fix. It would make such simple default arguments as these unnecessarily complicated: def foo(x=2**64, sentinel=object()) Please don't try to "fix" this feature. -- Steven From dblubaugh at belcan.com Tue Aug 26 15:36:41 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Tue, 26 Aug 2008 15:36:41 -0400 Subject: Using Python to shared memory resources between Linux and Windows In-Reply-To: References: Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3804CF59D8@AWMAIL04.belcan.com> To All, I was wondering if it was possible to utilize python to share a memory resource between a linux and windows system?? It should be stated that both the Linux (CENTOS 5) and windows are physically located on the same computer. Is any of this possible? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From tjreedy at udel.edu Sun Aug 10 14:32:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 10 Aug 2008 14:32:14 -0400 Subject: Validation of parameters In-Reply-To: <4785d2c9-f1ce-4226-acfe-2cf35b8303dd@34g2000hsh.googlegroups.com> References: <1578181c-6013-4944-8abe-68148ca53960@d45g2000hsc.googlegroups.com> <4785d2c9-f1ce-4226-acfe-2cf35b8303dd@34g2000hsh.googlegroups.com> Message-ID: Kless wrote: > On 10 ago, 15:03, Paddy wrote: >> If you just want the absense of _foo to raise an exception then why to >> just reference self._foo and leave the hard work to ptyhon? Something >> like: >> >> self._foo >> >> If it is present then fine, if it is not then an exception is raised. > It only was an example but I need show a better message. The usual idiom is try: self._foo except AttrError as m: #3.0 From shahmed at sfwmd.gov Mon Aug 18 13:42:03 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Mon, 18 Aug 2008 13:42:03 -0400 Subject: help with parsing email In-Reply-To: References: Message-ID: -----Original Message----- From: python-list-bounces+shahmed=sfwmd.gov at python.org [mailto:python-list-bounces+shahmed=sfwmd.gov at python.org] On Behalf Of Werner F. Bruhin Sent: Monday, August 18, 2008 1:04 PM To: python-list at python.org Cc: python-win32 at python.org Subject: Re: help with parsing email Ahmed, Shakir wrote: > Thanks everyone who tried to help me to parse incoming email from an exchange server: > > Now, I am getting following error; I am not sure where I am doing wrong. I appreciate any help how to resolve this error and extract emails from an exchange server. > > > First I tried: >>>> mailserver = 'EXCHVS01.my.org' >>>> mailuser = 'myname' >>>> mailpasswd = 'mypass' >>>> mailserver = poplib.POP3(mailserver) > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\lib\poplib.py", line 96, in __init__ > raise socket.error, msg > error: (10061, 'Connection refused') > > > > The other way: > >>>> mailserver = 'pop.EXCHVS01.ad.my.org' >>>> mailuser = 'myname at my.org' >>>> mailpasswd = 'mypass' >>>> mailserver = poplib.POP3(mailserver) > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\lib\poplib.py", line 84, in __init__ > for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): > gaierror: (11001, 'getaddrinfo failed') Haven't used poplib myself, but was intrigued. Did you see this: http://www.python.org/doc/lib/pop3-example.html To me it looks like you are not setting the user/password. So, maybe something like: M = poplib.POP3(mailserver) M.user(mailuser) M.pass_(mailpasswd) .... Werner -- but I am getting error before that point and could not go to the user account or pass. M = poplib.POP3(mailserver) Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\lib\poplib.py", line 96, in __init__ raise socket.error, msg error: (10061, 'Connection refused') From fredrik at pythonware.com Fri Aug 15 03:35:21 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 15 Aug 2008 09:35:21 +0200 Subject: precedence of [] vs . In-Reply-To: <466f1a6b-d443-4803-8f9f-c10776dfa9f8@l42g2000hsc.googlegroups.com> References: <48390979-4759-43de-967c-8d9b712b61f7@l42g2000hsc.googlegroups.com> <15801a83-ddac-45ad-90e9-0d503f2bda73@d77g2000hsb.googlegroups.com> <466f1a6b-d443-4803-8f9f-c10776dfa9f8@l42g2000hsc.googlegroups.com> Message-ID: Carl Banks wrote: >> http://docs.python.org/ref/summary.html > > I think the summary is correct (am not going to bother to double- > check), but there's a subtle point you're missing. Here is a > simplified explanation. the rendered summary is broken; see my other post. From news1234 at free.fr Wed Aug 20 18:15:52 2008 From: news1234 at free.fr (nntpman68) Date: Thu, 21 Aug 2008 00:15:52 +0200 Subject: Negative integers In-Reply-To: References: Message-ID: <48ac9798$0$27334$426a74cc@news.free.fr> Hi, Dan's solution is probably the clearest. Just out of curiousity:. How would you in your program's context like 0 to be treated. should it be treated as a positive number or should it be treated as a case part. my suggestion a*b > 0 for example wouldn't work if you want 0 to be treated as positive number or if you compare 0 with 0 and want 'same sign' as answer bye N johnewing wrote: > I am trying to figure out how to test if two numbers are of the same > sign (both positive or both negative). I have tried > > abs(x) / x == abs(y) / y > > but that fails when one of the numbers is 0. I'm sure that there is > an easy way to do this. Any suggestions? > > Thanks From ricaraoz at gmail.com Wed Aug 20 09:19:02 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 20 Aug 2008 10:19:02 -0300 Subject: who to call a list of method inside the class itself In-Reply-To: References: <48ab30a4$0$12032$426a34cc@news.free.fr> Message-ID: <48AC19C6.5040309@bigfoot.com> Terry Reedy wrote: > > maduma at pt.lu wrote: >> Is the following code is ok. who to call all method. >> It is working but the call to m() without a reference to self seems >> strange > > The reference to self is bound to the methods by the way you look them up. > > >> class CustomMethod: >> def method1(self): >> .... >> def method2(self): >> .... >> def method3(self): >> .... >> >> def getAllMethod(self): >> return [self.method1, self.method2, self.method3] >> >> def applyAll(self): >> for m in self.getAllMethod(): >> m() > > If the list is static, there is no need to calculate it more than once, > at class-definition time. I might do this like so: > > class CustomMethod: > ... > all_methods = [method1, method2, method3] > def apply_all(self): > for m in self.all_methods: > m(self) > > Class code has access to the results of previous class code. > BTW, how would you guys go about registering the functions to be returned by apply_all()? I mean something like : class CustomMethod(object) : def __init__(self) : self.methodList = [] def method1(self) : ... self.registerMe(????send a reference to this method????) def method2(self) : ... self.registerMe(????send a reference to this method????) def registerMe(????receive a reference to some method????) : self.methodList.append(????the reference to the method????) def getAllMethods(self) : return self.methodList etc. From gminick at bzt.bzt Tue Aug 19 09:11:42 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Tue, 19 Aug 2008 13:11:42 +0000 (UTC) Subject: searching through a string and pulling characters References: <19039594.post@talk.nabble.com> Message-ID: On Mon, 18 Aug 2008 15:34:12 -0700 (PDT), Alexnb wrote: > Also, on a side-note, does anyone know a very simple dictionary site, that > isn't dictionary.com or yourdictionary.com. This one is my favourite: http://www.lingro.com/ -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From eliben at gmail.com Wed Aug 20 01:24:45 2008 From: eliben at gmail.com (eliben) Date: Tue, 19 Aug 2008 22:24:45 -0700 (PDT) Subject: exception handling in complex Python programs References: Message-ID: """ between file() and open() in Python 2 and 3, a NameError is thrown with open() in Python 3 and an IOError is thrown in the other three cases . """ This is *exactly* my concern with Python exceptions. You just never know what can be thrown at you. > You want to look up Easier to Ask Forgivness than Permission (EAFP) > which is touted as the "canonical" error-handling paradigm for Python. Any (semi)complete guides on this canonical paradigm online ? I've only found some references in maillist discussions. > ? def do_something(filename): > ? ? if not os.access(filename,os.R_OK): > ? ? ? return err(...) > ? ? f = open(filename) > ? ? ... > But does os.access cover absolutely all the errors that can happen during open() ? What guarantees it, and how can I know without you teaching me, just from the docs ? From michele.simionato at gmail.com Thu Aug 28 02:12:04 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 27 Aug 2008 23:12:04 -0700 (PDT) Subject: List of modules available for import inside Python? References: Message-ID: <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> On Aug 28, 6:21?am, ssecorp wrote: > Is there a way to view all the modules I have available for import > from within Python? > Like writing in the interpreter: Try: >>> help() help> modules Please wait a moment while I gather a list of all available modules... From eckhardt at satorlaser.com Wed Aug 6 04:39:48 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 06 Aug 2008 10:39:48 +0200 Subject: Locking around References: <87ej547vqs.fsf@nokile.rath.org> Message-ID: Nikolaus Rath wrote: > I need to synchronize the access to a couple of hundred-thousand > files[1]. It seems to me that creating one lock object for each of the > files is a waste of resources, but I cannot use a global lock for all > of them either (since the locked operations go over the network, this > would make the whole application essentially single-threaded even > though most operations act on different files). Just wondering, but at what time do you know what files are needed? If you know that rather early, you could simply 'check out' the required files, do whatever you want with them and then release them again. If one of the requested files is marked as already in use, you simply wait (without reserving the others) until someone releases files and then try again. You could also wait for that precise file to be available, but that would require that you already reserve the other files, which might unnecessarily block other accesses. Note that this idea requires that each access locks one set of files at the beginning and releases them at the end, i.e. no attempts to lock files in between, which would otherwise easily lead to deadlocks. Further, you could distinguish between read-only and read-write access as an optimisation. > My idea is therefore to create and destroy per-file locks "on-demand" > and to protect the creation and destruction by a global lock > (self.global_lock). For that, I add a "usage counter" > (wlock.user_count) to each lock, and destroy the lock when it reaches > zero. [...code...] > - Does that look like a proper solution, or does anyone have a better > one? This should work, at least the idea is not flawed. However, I'd say there are too many locks involved. Rather, you just need a simple flag and the global lock. Further, you need a condition/event that tells waiting threads that you released some of the files so that it should see again if the ones it wants are available. > - Did I overlook any deadlock possibilities? The normal deadlock possibilities when multiple locks are involved apply, you must make sure that they are always acquired in an order that prevents two threads waiting for a resource held by the other. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From jsmith1703 at aol.com Tue Aug 19 22:14:51 2008 From: jsmith1703 at aol.com (YouOverThere) Date: Tue, 19 Aug 2008 19:14:51 -0700 (PDT) Subject: IOError: decoder zip not available when using PIL Message-ID: <2362c6e2-1165-40ea-977a-f7056aab370b@o40g2000prn.googlegroups.com> I keep getting the error message "IOError: decoder zip not available" when using the Python Imaging Library. The error has occurred when trying to work with PNGs or JPEGs or when loading the fonts supplied with PIL. I can work with GIFs. I assume that I did something wrong when I built Python and/or PIL, but I'm at a loss as to what. I am running Python 2.5.1 with PIL 1.1.6 under SUSE Linux 10.2. I am stuck working on my own because our SysAdmin staff is loathe to install any Python packages. Thanks in advance! From Eric_Dexter at msn.com Fri Aug 22 05:13:14 2008 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Fri, 22 Aug 2008 02:13:14 -0700 (PDT) Subject: running exe file References: Message-ID: <5eaa72fa-fe51-4e45-ab02-d95a4c34d0f8@v1g2000pra.googlegroups.com> On Aug 22, 12:12?am, Saurabh Sharma wrote: > How can I run .exe file from my python script? import os os.startfile('file.exe') The downside is that it doesn't work on the mac.. but it does work on stuff like os.startfile('notepad.txt') I have been waiting for a good hacker to write a version to check what op system you have and then execute... I have more examples in my dex tracker package (use google) From stefan_ml at behnel.de Sun Aug 10 09:01:20 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 10 Aug 2008 15:01:20 +0200 Subject: Replace value of node using getElementsByTagName In-Reply-To: <2bc46eb6-d637-442f-b931-60f8f8fccad1@c58g2000hsc.googlegroups.com> References: <2bc46eb6-d637-442f-b931-60f8f8fccad1@c58g2000hsc.googlegroups.com> Message-ID: <489ee6a0$0$12942$9b4e6d93@newsspool2.arcor-online.net> Ouray Viney wrote: > Is there an easy way to replace the node value of ? Perhaps I am > trying to use the wrong python XML library? Looks like it. Try ElementTree. from xml.etree import ElementTree tree = ElementTree.parse("yourfile.xml") for ib in tree.findall("//ib"): ib.text = calculate_new_value(ib.text) Stefan From castironpi at gmail.com Sun Aug 24 10:02:09 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 24 Aug 2008 07:02:09 -0700 (PDT) Subject: property() usage - is this as good as it gets? References: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> Message-ID: On Aug 24, 5:00?am, alex23 wrote: > castironpi wrote: > > and we'll write Python. > > I haven't seen anything you've contributed to this group that would so > far be considered well-written Python. > > Confusing and border-line insane, yes. Pythonic? Not at all. > > Here's a tip: try actually developing some real-world application in > Python for a while, rather than the god-knows-what-you're-doing > attempts that you keep hijacking various threads with. Your code isn't > anywhere near as clever as you seem to think. Python isn't as clever as you think. It's a language. Do you want a link to clever code? I like to encourage creativity. From smanek at gmail.com Wed Aug 13 14:50:09 2008 From: smanek at gmail.com (shaneal) Date: Wed, 13 Aug 2008 11:50:09 -0700 (PDT) Subject: RPM Control from Python Message-ID: Hello, I'm trying to script some sysadmin stuff, that requires rpm manipulation (querying installed packages, removing packages, installing packages). Rather than manually parsing rpm's output, I noticed that someone had written python-bindings for the rpmlib library (called rpm-python). This seems much cleaner, but the documentation is sparse, and I haven't been able to get uninstalling to work. As root, I run the following: >>> import rpm >>> ts=rpm.ts() >>> ts.addErase("lynx") >>> I get no error messages/exceptions, but lynx is not removed. I've also tried things along the lines of: >>> mi = ts.dbMatch(rpm.RPMTAG_NAME, "lynx") >>> for idx in mi: ... instance = mi.instance() ... ts.addErase(instance) and >>> mi = ts.dbMatch(rpm.RPMTAG_NAME, "lynx") >>> for idx in mi: ... ts.addErase(idx) I've further confirmed that ts.dbMatch(rpm.RPMTAG_NAME, "lynx") does in fact find the header for the lynx package via something like: >>> mi = ts.dbMatch(rpm.RPMTAG_NAME, "lynx") >>> for hdr in mi: ... print hdr['name'], hdr['version'] ... lynx 2.8.5 The only real documentation I've been able to find is http://people.redhat.com/pnasrat/rpm-python/rpm-python-slides/frames.html Is there some other module I should be using for rpm manipulation? Or, if not, does anyone know what I'm doing wrong with this one? From mensanator at aol.com Tue Aug 26 19:16:55 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 26 Aug 2008 16:16:55 -0700 (PDT) Subject: Identifying the start of good data in a list References: <94524253-b946-4ffa-ae2e-ae6a555d4e7c@a1g2000hsb.googlegroups.com> Message-ID: <877a0a07-5dcd-4606-82ea-f5c87ac6b83e@m45g2000hsb.googlegroups.com> On Aug 26, 4:49?pm, tkp... at hotmail.com wrote: > I have a list that starts with zeros, has sporadic data, and then has > good data. I define the point at ?which the data turns good to be the > first index with a non-zero entry that is followed by at least 4 > consecutive non-zero data items (i.e. a week's worth of non-zero > data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, > 9], I would define the point at which data turns good to be 4 (1 > followed by 2, 3, 4, 5). > > I have a simple algorithm to identify this changepoint, but it looks > crude: is there a cleaner, more elegant way to do this? > > ? ? flag = True > ? ? i=-1 > ? ? j=0 > ? ? while flag and i < len(retHist)-1: > ? ? ? ? i += 1 > ? ? ? ? if retHist[i] == 0: > ? ? ? ? ? ? j = 0 > ? ? ? ? else: > ? ? ? ? ? ? j += 1 > ? ? ? ? ? ? if j == 5: > ? ? ? ? ? ? ? ? flag = False > > ? ? del retHist[:i-4] > > Thanks in advance for your help > > Thomas Philips Here's my attempt: LL = [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] i = 0 while (i Hi, I've used CTYPES module to access a function from a dll. This function provides me the version of the dll. This information is accessible to me as an array of 4 long inetegers. information as : 2, 1, 5, 0 I want to display these elements concatenated as "v2.1.5.0". This string ( I'm thinking of writing the above 4 array elements to a string) is to be displayed as label in a GUI ( the GUI used is Tk) Please suggest how can I write these elements to a string to get me the desired results as "v2.1.5.0". And, is writing to a string is right way? PS: this string also needs to be displayed in the GUI label well. FYI, the code written to access function from dll is as under: ******** from ctypes import * abc = windll.af1xEvdoRDll GetVersion = abc.af1xEvdoRDll_GetVersion print GetVersion versionArr = c_long * 4 version = versionArr(0, 0, 0, 0) GetVersion(version) print version for i in version: print i ************* Results are : 2, 1, 5, 0 Cheers, Rajat From bdesth.quelquechose at free.quelquepart.fr Wed Aug 13 12:11:20 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 13 Aug 2008 18:11:20 +0200 Subject: Calling "def" functions from another file. In-Reply-To: <8870982d-017b-418e-be50-5e46c463c1a4@8g2000hse.googlegroups.com> References: <8870982d-017b-418e-be50-5e46c463c1a4@8g2000hse.googlegroups.com> Message-ID: <48a3239c$0$29472$426a34cc@news.free.fr> frankrentef a ?crit : > Newbie here.... > > I'm writing a Python program that has "def" functionality functions > growing in > leaps and bounds. I'm a newbie to Python so be detailed. Is there a > way to create a py file with all the "def's" listed and just call them > from the "program" py file? yes. Put all your functions in a .py file, and import that file from the main 'program' file. > How would I do this? All this is in the FineManual(tm), here: http://docs.python.org/tut/node8.html I strongly suggest you read this first, experiment a bit, then come back here if you have any trouble or question. > Say my "def" py > file was named def.py Bad name. 'def' is a reserved word, so you can't name a module (a .py file) that way. From nodrogbrown at gmail.com Fri Aug 29 13:18:08 2008 From: nodrogbrown at gmail.com (gordon) Date: Fri, 29 Aug 2008 10:18:08 -0700 (PDT) Subject: Tkinter event loop question References: <9eaef6c3-c913-497f-8ca2-0466eb178c7a@z6g2000pre.googlegroups.com> Message-ID: <759a12fe-75c8-429a-9a64-19dc73a0b779@b30g2000prf.googlegroups.com> On Aug 29, 4:45 am, "Russell E. Owen" wrote: >your Controller object should not create root nor should > it call mainloop to start the event loop. guys thanks for the helpful replies..I rewrote the code as you advised. It creates a controller object and a gui object from main script.However i had to chain some method calls in my code.i am wondering if that can be avoided in some way. this is the sequence 1.user enters some value in the textfield,and clicks OKbutton 2.on OKbuttonclick ,the gui takes userinput value and quits eventloop.It then calls controller and pass the userinputvalue. 3.controller does some calculation(i shd have an external program to do calculation,but for simplicity i just wrote a method inside controller) with the given value,obtains the result and calls gui's updateDisplay(), passing the result value. 4.the gui creates the result as text on a canvas.then the mainloop() is called to resume event loop again user enters some value in the textfield,and clicks OKbutton ... I exit the application by clicking quitButton that calls destroy() on top level window. I tried my application by entering some value on text field and then clicking OKbutton ,the calculated result is displayed on canvas .I do this process say 3 times ..Then i click the Quit button and the window closes. I have put a print statement inside the gui's updateDisplay()method right after the resuming of event loop by parent.mainloop().This print statement gets printed as many times as i had clicked the OK button(here in this case 3 times).Is this due to clearing of the stack ? I feel that it was not a good design ..I would be grateful if someone would tell me how i could improve it..can those chaining of method calls be avoided? this is how i restructured the code moduleA.py ----------- import moduleB from Tkinter import Tk class MyController(object): def __init__(self): print "controller()" def validateSelection(self,userinputVal): if(userinputVal > 50 or userinputVal==0): userinputVal=50 self.doSomeCalculation(userinputVal) def doSomeCalculation(self,userinputVal): resultvalue=2*userinputVal +10 self.updateResults(resultvalue) def updateResults(self,resultvalue): self.myapp.updateDisplay(resultvalue); if __name__ == "__main__": controller=MyController() root = Tk() root.wm_title("MyUIApp") controller.myapp =moduleB.MyUI(root,controller) root.mainloop() moduleB.py ----------- from Tkinter import * class MyUI(object): def __init__(self, parent,controller): self.myParent = parent self.mainframe = Frame(parent,background="grey") self.mainframe.pack(fill=BOTH,expand=YES) self.controller=controller ....added a canvas and OK,QUIT buttons def okBtnClick(self): print "okBtnClicked" self.okButton.configure(state=DISABLED) userinputvalue = self.getUserInputValue() self.myParent.quit() #quits event loop self.controller.validateSelection(userinputvalue) def quitBtnClick(self): print "Quit Btn clicked" self.myParent.destroy() def updateDisplay(self,resultValue): message='result is='+str(resultValue) self.canvresult.delete(ALL) self.canvresult.create_text(1, 40, anchor=W, text=message, width=280) self.okButton.configure(state=NORMAL) self.myParent.mainloop() # resumes event loop print 'in updateDisplay():called mainloop' thanks gordon From arigo+google at codespeak.net Sat Aug 23 13:22:37 2008 From: arigo+google at codespeak.net (arigo+google at codespeak.net) Date: Sat, 23 Aug 2008 10:22:37 -0700 (PDT) Subject: Psycho question References: Message-ID: On Aug 8, 7:18 pm, "David C. Ullrich" wrote: > The one thing that puzzles me about > all the results is why // is so much slower than / inside > that Psyco loop. Just an oversight. The optimization about '/' between integers was not copied for the case of '//' between integers. Fixed in the svn head :-) Armin From elessar at nienna.org Sun Aug 17 15:23:08 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Sun, 17 Aug 2008 13:23:08 -0600 Subject: Good python equivalent to C goto In-Reply-To: <1a1eedf0-2164-4377-a77a-be105b37cceb@k37g2000hsf.googlegroups.com> References: <48a744b6$0$299$7a628cd7@news.club-internet.fr> <1a1eedf0-2164-4377-a77a-be105b37cceb@k37g2000hsf.googlegroups.com> Message-ID: <48A87A9C.1060407@nienna.org> info at orlans-amo.be wrote: > On Aug 17, 8:09 pm, Matthew Fitzgibbons wrote: >> Kurien Mathew wrote: >>> Hello, >>> Any suggestions on a good python equivalent for the following C code: >>> while (loopCondition) >>> { >>> if (condition1) >>> goto next; >>> if (condition2) >>> goto next; >>> if (condition3) >>> goto next; >>> stmt1; >>> stmt2; >>> next: >>> stmt3; >>> stmt4; >>> } >>> Thanks >>> Kurien >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> I would not be too happy if I saw C code like that in my repository. >> This is equivalent: >> >> while (loopCondition) { >> if (!(condition1 || condition2 || condition3)) { >> stmt1; >> stmt2; >> } >> stmt3; >> stmt4; >> >> } >> >> In Python: >> >> while (loopCondition): >> if not (condition1 or condition2 or condition3): >> stmt1 >> stmt2 >> stmt3 >> stmt4 >> >> If stmt3 and stmt4 are error cleanup code, I would use try/finally. >> >> while loopCondition: >> try: >> if condition1: >> raise Error1() >> if condition2: >> raise Error2() >> if condition3: >> raise Error3() >> stmt1 >> stmt2 >> finally: >> stmt3 >> stmt4 >> >> This will also bail out of the loop on and exception and the exception >> will get to the next level. If you don't want that to happen, put an >> appropriate except block before the finally. >> >> -Matt- Hide quoted text - >> >> - Show quoted text - > > class Goto_Target(Exception): > pass > > def Goto_is_not_dead(nIn): > try: > if (nIn == 1): raise Goto_Target > if (nIn == 2): raise Goto_Target > > inv = 1.0 / nIn > print 'Good Input ' + str(nIn) + ' inv=' + str(inv) > > except Goto_Target: > pass > except Exception, e: > print 'Error Input ' + str(nIn) + ' ' + str(e) > finally: > print 'any input ' + str(nIn) > > if __name__ == '__main__': > Goto_is_not_dead(0) > Goto_is_not_dead(2) > Goto_is_not_dead(3) > -- > http://mail.python.org/mailman/listinfo/python-list > I think this is needlessly ugly. You can accomplish the same with a simple if-else. In this case you're also masking exceptions other than Goto_Target, which makes debugging _really_ difficult. If you need to have the cleanup code executed on _any_ exception, you can still use try-finally without any except blocks. Your code is equivalent to this: def goto_is_dead(n): try: if n == 0 or n == 1 or n == 2: # if you're validating input, validate the input print "Error Input %s" % n else: print "Good Input %s inv= %s" % (n, (1. / n)) finally: print "any input %s" % n if __name__ == '__main__': goto_id_dead(0) goto_id_dead(2) goto_id_dead(3) More concise, readable, and maintainable. -Matt From tjreedy at udel.edu Fri Aug 1 17:06:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 01 Aug 2008 17:06:57 -0400 Subject: Strong/weak typing In-Reply-To: <6727fa22-aee9-4a9b-b9c0-08534aab6b34@m45g2000hsb.googlegroups.com> References: <6727fa22-aee9-4a9b-b9c0-08534aab6b34@m45g2000hsb.googlegroups.com> Message-ID: MartinRinehart at gmail.com wrote: > I'm writing Python as if it were strongly typed, never recycling a > name to hold a type other than the original type. Names are bound to objects with types. > Is this good software engineering practice, If you expand 'type' to 'category', then yes. > or am I missing something Pythonic? Most Python code is or could be generic. def sum(iterable,start): for item in iter(iterable): start += item return start Iterable can be any collection that is homogeneous with respect to the class of start and the operation of addition. And throughout my code, I never use 'iterable' for anything other that a homegeneous-for-the-purpose collection. I would never, for instance, bind it to a number. tjr From elessar at nienna.org Tue Aug 26 12:50:15 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Tue, 26 Aug 2008 10:50:15 -0600 Subject: Programmatically exit the REPL In-Reply-To: References: <288810.50426.qm@web7904.mail.in.yahoo.com> Message-ID: <48B43447.60700@nienna.org> Alexander Schmolck wrote: > Without reading your post properly or having tried to do the same thing > myself: I think you might want to have a look at ipython; it gives a better > REPL and "embedding ipython" should give you plenty of hits as well. > Thanks for the tip; I hadn't heard of ipython before. I will certainly check it out. However, if anyone knows how to break out of the interactive interpreter from another thread, I'd still very much like to hear about it. :) -Matt From ewertman at gmail.com Sat Aug 30 21:32:18 2008 From: ewertman at gmail.com (Eric Wertman) Date: Sat, 30 Aug 2008 21:32:18 -0400 Subject: Writing to ms excel In-Reply-To: References: Message-ID: <92da89760808301832o716d89e2s138d5f46b91645d2@mail.gmail.com> Yes sorry, that's a really poorly formed sentence all the way around... not a dig on xlrd, but a warning to the OP that they may not find what they are looking for there. > On Aug 31, 12:57 am, "Eric Wertman" wrote: >> If you have >> to interface with an exsisting excel file, you can try http://pypi.python.org/pypi/xlrd, but it may not support writing xls >> files, still. > > That remark appears to be an inverted cousin of the old joke question > "Have you stopped beating your wife?" :-) From thomasmallen at gmail.com Thu Aug 14 09:54:15 2008 From: thomasmallen at gmail.com (tmallen) Date: Thu, 14 Aug 2008 06:54:15 -0700 (PDT) Subject: An FTP Client...My first real program! References: <228e4214-01cf-4152-acdb-3743594f0581@e53g2000hsa.googlegroups.com> Message-ID: On Aug 13, 11:53?pm, "Python Nutter" wrote: > sorry cut off due to original email being sent not to the list due to gmail: > > A second for that suggestion--the ftp module in the python standard library is > very low level and not very useful for beginners as a lot of the heavy > lifting and management is still left up to you, the programmer. > > 2008/8/14 Python Nutter : > > > ery low level and not very useful for beginners as a lot of the heavy > > lifting and management is still left up to you, the programmer. > > > The module ftputil is a high-level interface to the ftplib module. The > > FTPHost objects generated from it allow many operations similar to > > those of os and os.path. An example: > > > # download some files from the login directory > > host = ftputil.FTPHost('ftp.domain.com', 'user', 'secret') > > names = host.listdir(host.curdir) > > for name in names: > > ? if host.path.isfile(name): > > ? ? ? host.download(name, name, 'b') ?# remote, local, binary mode > > # make a new directory and copy a remote file into it > > host.mkdir('newdir') > > source = host.file('index.html', 'r') ?# file-like object > > target = host.file('newdir/index.html', 'w') ?# file-like object > > host.copyfileobj(source, target) ?# similar to shutil.copyfileobj > > source.close() > > target.close() > > > Now if you are again purely in it for a challenge or for and > > educational roller coaster ride, ignore the suggestion to look at > > higher level ftp modules =) > > > Cheers, > > PN > > What work, specifically, am I duplicating? I have my eyes on a larger application, so if this part can easily be taken care of, I'm all ears. From sjmachin at lexicon.net Wed Aug 27 20:48:25 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 27 Aug 2008 17:48:25 -0700 (PDT) Subject: finding out the number of rows in a CSV file [Resolved] References: <3aaa109e-9a7e-4d02-8af5-0161251d7678@t54g2000hsg.googlegroups.com> <0bc6097f-af52-4951-a413-e9a983df93c7@79g2000hsk.googlegroups.com> Message-ID: <59b93881-47e6-4108-87ca-074f23df48b0@v39g2000pro.googlegroups.com> On Aug 28, 7:51 am, norseman wrote: > Peter Otten wrote: > > John S wrote: > > >> [OP] Jon Clements wrote: > >>> On Aug 27, 12:54 pm, SimonPalmer wrote: > >>>> after reading the file throughthe csv.reader for the length I cannot > >>>> iterate over the rows. How do I reset the row iterator? > >> A CSV file is just a text file. Don't use csv.reader for counting rows > >> -- it's overkill. You can just read the file normally, counting lines > >> (lines == rows). > > > Wrong. A field may have embedded newlines: > > >>>> import csv > >>>> csv.writer(open("tmp.csv", "w")).writerow(["a" + "\n"*10 + "b"]) > >>>> sum(1 for row in csv.reader(open("tmp.csv"))) > > 1 > >>>> sum(1 for line in open("tmp.csv")) > > 11 > > > Peter > > -- > >http://mail.python.org/mailman/listinfo/python-list > > ============================= > Well..... a semantics's problem here. > > A blank line is just an EOL by its self. Yes. Or a line containing blanks. Yes what? > I may want to count these. Could be indicative of a problem. If you use the csv module to read the file, a "blank line" will come out as a row with one field, the contents of which you can check. > Besides sum(1 for len(line)>0 in ...) handles problem if I'm not > counting blanks and still avoids tossing, re-opening etc... What is "tossing", apart from the English slang meaning? What re-opening? > > Again - it's how you look at it, but I don't want EOLs in my dbase > fields. Most people don't want them, but many do have them, as well as Ctrl-Zs and NBSPs and dial-up line noise (and umlauts/accents/suchlike inserted by the temporarily-employed backpacker to ensure that her compatriots' names and addresses were spelled properly) ... and the IT department fervently believes the content is ASCII even though they have done absolutely SFA to ensure that. > csv was designed to 'dump' data base fields into text for those > not affording a data base program and/or to convert between data base > programs. By the way - has anyone seen a good spread sheet dumper? One > that dumps the underlying formulas and such along with the display > value? That would greatly facilitate portability, wouldn't it? (Yeah - > the receiving would have to be able to read it. But it would be a start > - yes?) Everyone got the point? Just because it gets abused doesn't > mean .... Are we back on track? Number of lines equals number of > reads - which is what was requested. No bytes magically disappearing. No > slight of hand, no one dictating how to or what with .... > > The good part is everyone who reads this now knows two ways to approach > the problem and the pros/cons of each. No loosers. IMHO it is very hard to discern from all that ramble what the alleged problem is, let alone what are the ways to approach it. From ryanlists at gmail.com Thu Aug 7 11:11:24 2008 From: ryanlists at gmail.com (Ryan Krauss) Date: Thu, 7 Aug 2008 10:11:24 -0500 Subject: problem calling parent's __init__ method Message-ID: I am trying to call a parent's __init__ method from the child's: class ArbitraryBlock(InnerBlock): def __init__(self, codelist, noout=False, **kwargs): InnerBlock.__init__(self, codelist, noout=noout, **kwargs) I get this error: : unbound method __init__() must be called with InnerBlock instance as first argument (got ArbitraryBlock instance instead) I found a thread that talked about the parent and child being different types, so I tried setting up the parent class 3 different ways: class InnerBlock: class InnerBlock(object): class InnerBlock(empty_class): where class empty_class(object): def __init__(self,_d={},**kwargs): kwargs.update(_d) self.__dict__=kwargs I still get the same error. Why doesn't this work? Thanks, Ryan From 4564 at 755189.45 Thu Aug 7 03:49:59 2008 From: 4564 at 755189.45 (Enrico) Date: Thu, 7 Aug 2008 09:49:59 +0200 Subject: Using an DTD not specified in XML file for validation References: <87ej547vqs.fsf@nokile.rath.org> <87y73aa3se.fsf@nokile.rath.org><87sktia0uf.fsf@nokile.rath.org> <1836659a-99e9-4b51-953d-b5622c22fec5@k37g2000hsf.googlegroups.com><87prom9vcu.fsf@nokile.rath.org> Message-ID: <489aa952$0$1079$4fafbaef@reader2.news.tin.it> "Brian Quinlan" ha scritto nel messaggio news:mailman.1200.1218043709.922.python-list at python.org... > Hey, > > I'm trying to figure out how I can validate an XML file using a DTD that > isn't specified in the XML file. I did it once using lxml. You can read from: http://codespeak.net/lxml/validation.html With this package is quite simple (code not tested): from lxml import etree dtd = etree.DTD('mydtd.dtd') f = file('mydoc.xml') xml = etree.XML(f.read()) dtd.validate(xml) Enrico From steve at REMOVE-THIS-cybersource.com.au Fri Aug 22 20:52:14 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 23 Aug 2008 00:52:14 GMT Subject: Generators can only yield ints? References: Message-ID: <00bf5a06$0$20312$c3e8da3@news.astraweb.com> On Fri, 22 Aug 2008 15:44:15 -0700, defn noob wrote: > def letters(): > a = xrange(ord('a'), ord('z')+1) > B = xrange(ord('A'), ord('Z')+1) > while True: > yield chr(a) > yield chr(B) > > >>>> l = letters() >>>> l.next() > > Traceback (most recent call last): > File "", line 1, in > l.next() > File "", line 5, in letters > yield chr(a) > TypeError: an integer is required >>>> >>>> > > Any way to get around this? Yes, write code that isn't buggy :) Generators can return anything you want. Your problem is that you're passing an xrange object to chr() instead of an int. Try this: def letters(): a = xrange(ord('a'), ord('z')+1) B = xrange(ord('A'), ord('Z')+1) for t in zip(a, B): yield chr(t[0]) yield chr(t[1]) But (arguably) a better way is: def letters(): from string import ascii_letters as letters for a,b in zip(letters[0:26], letters[26:]): yield a yield b Note that it is important to use ascii_letters rather than letters, because in some locales the number of uppercase and lowercase letters differ. -- Steven From dudeja.rajat at gmail.com Sun Aug 17 10:25:29 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sun, 17 Aug 2008 10:25:29 -0400 Subject: Windows / Tkinter - problem with grid - not able to place widgets at desired places Message-ID: Hi, I'm learning Python and Tkinter. I've started programming in Eclipse with PyDev. I'm intending to create a GUI. I'm not able to understand the Grid manager perhaps because there is quite a less documentation available for it on the net. My desired GUI is attached in the mail. Although I've tried writing a class module for this GUI but I'm not able to set all things right in the GUI. The Biggest problem seems to be with the Grid Manager in terms how it divides a window in Rows / columns. etc. I'm not able to place none of the widgets correctly in the GUI. For your convenience, I'm attaching this code also as myModule1.py . Please some one review it and help create me this GUI. PS: The desired GUI is attached as a GIF file. The version v1.4.5.1 is a label the contents of which are dynamically picked. Thanks and regards, Rajat -------------- next part -------------- A non-text attachment was scrubbed... Name: Desired GUI.GIF Type: image/gif Size: 21640 bytes Desc: not available URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: myModule1.py URL: From __peter__ at web.de Mon Aug 25 09:45:49 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 25 Aug 2008 15:45:49 +0200 Subject: Python String Immutability Broken! References: <000b01c906f1$a493bb80$0d00a8c0@hendrik> <00c2a9b1$0$20312$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Mon, 25 Aug 2008 03:43:01 -0700, Ken Seehart wrote: > >> You can also use ctypes to globally change the value of integers less >> than 101. Personally, I don't particularly like the number 14. I >> changed it to 9 and I am much happier now. > > Okay, you've got me curious. How do you do that, and why only up to 101? Up to 256 in current Python. Small integers are shared to save memory. After a quick look into the ctypes tutorial and the python source I came up with # 64-bit linux >>> from ctypes import * >>> libc = cdll.LoadLibrary("libc.so.6") >>> libc.memset(id(14)+16, 0, 8) 7742336 >>> 14 0 >>> 14 == 0 True Peter From castironpi at gmail.com Tue Aug 26 00:11:24 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 25 Aug 2008 21:11:24 -0700 (PDT) Subject: Return a string result with out breaking loop References: Message-ID: <631fff4c-0332-427f-9a1f-9ce7f47788ff@k7g2000hsd.googlegroups.com> On Aug 25, 6:37?pm, Andrew wrote: > Hi I was wondering if there is anyway with XML RPC to send a string of > text from the server to the client with out calling return thus breaking > ? my loop > > for example > > ? def somefunc(): > ? ? ? ?for action, files in results: > ? ? ? ? ? ? ? ?full_filename = os.path.join(path_to_watch, files) > ? ? ? ? ? ? ? ?theact = ACTIONS.get(action, "Unknown") > ? ? ? ? ? ? ? ?out2 = ?str(full_filename) + ?" " + str(theact) > ? ? ? ? ? ? ? ?return out2 > > the return statement will return a result breaking my loop. My goal is > to have it continue looping and updating the client > > any ideas? > > Cheers > > Andrew > > Thanks in advance > > Pyhon 2.5.2 > > Windows XP Andrew, I have generators working on both sides of a SimpleXMLRPCServer instance. You ask for a server-side generator, and I won't post the whole program, as it's long, so here's an important part: server = SimpleXMLRPCServer(("localhost", 8000)) server.register_introspection_functions() def gen( ): while 1: yield 1 yield 2 yield 3 servg= gen( ) server.register_function( servg.next, 'gen' ) Called 's.gen( )' four times, output: localhost - - [25/Aug/2008 23:08:28] "POST /RPC2 HTTP/1.0" 200 - 1 localhost - - [25/Aug/2008 23:08:29] "POST /RPC2 HTTP/1.0" 200 - 2 localhost - - [25/Aug/2008 23:08:30] "POST /RPC2 HTTP/1.0" 200 - 3 localhost - - [25/Aug/2008 23:08:31] "POST /RPC2 HTTP/1.0" 200 - 1 As expected. I guess that your problem was on this line: server.register_function( servg.next, 'gen' ) where instead you just wrote server.register_function( servg, 'gen' ) #wrong or perhaps even server.register_function( gen, 'gen' ) #wrong I'll offer an explanation of the difference too, for the asking. From deets at nospam.web.de Thu Aug 28 09:10:45 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 28 Aug 2008 15:10:45 +0200 Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> <6fe0scFaus40U1@mid.uni-berlin.de> <6bc8bc07-eab0-4303-b8a4-c9470f96038d@c65g2000hsa.googlegroups.com> <6fe1n2Faus40U3@mid.uni-berlin.de> <6ff0ifFbbpfbU1@mid.uni-berlin.de> Message-ID: <6hnmffFn5mm9U1@mid.uni-berlin.de> > Zen's lesson for today: > THOU SHALT NOT MESS WITH ANY PYTHON'S SEMI-GODS, DEMI-GODS, AND > PYTHON'S GOD. > > You're lucky Diez still want to help you with your attitude like that. > May I remind you that we here helps you for free in our free time, be > rude, especially to a frequent member, and you'll get what you deserve. Thanks Lie, but I certainly don't consider myself being part of Python's olymp... :) Others here of course are, and a friendly and open attitude from everybody sure helps keeping this institution helpful. This goes also for frequent members - and I do include myself here, as I *sometimes* forget that myself, but try hard not to. Diez From deets at nospam.web.de Tue Aug 26 12:15:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Aug 2008 18:15:33 +0200 Subject: Are dictionaries the same as hashtables? References: <6hi153Fliuu4U1@mid.uni-berlin.de> Message-ID: <6hioi7Fmdo37U1@mid.uni-berlin.de> Cameron Laird wrote: > In article <6hi153Fliuu4U1 at mid.uni-berlin.de>, > Diez B. Roggisch wrote: >>Martin Marcher wrote: >> >>> On 2008-08-26 00:32:20, cnb wrote: >>>> Are dictionaries the same as hashtables? > . > . > . >>Python does not have a "one key maps to a list of values"-semantics - >>which I consider the sane choice... >> >>However, you can have that using the defaultdict for example: >> >>listdict = defaultdict(list) >> >>listdict[key].append(value) >> >>Diez > > ? I'm lost. As I understand your terms, Python's dictionaries > map keys to objects, but you would prefer that Python's > dictionaries map keys only to lists of values. That *sounds* > like a complexification, at best. Are you trying to make a > point about implementation aligning with semantics? The OP seems to want that (or at least sees it as one of two viable design choices), see his other answer in this thread. I certainly *don't* agree with that, I merely pointed out that python comes with means to easily create such a data-structure in the case it is needed. Diez From castironpi at gmail.com Mon Aug 25 01:49:52 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 24 Aug 2008 22:49:52 -0700 (PDT) Subject: property() usage - is this as good as it gets? References: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> <9dc512a3-a0ba-461a-a242-c2681b7db42e@a8g2000prf.googlegroups.com> <7098004b-3bc2-4740-870d-ce32ab81bf6c@25g2000prz.googlegroups.com> Message-ID: On Aug 24, 10:41?pm, alex23 wrote: > On Aug 25, 12:42?pm, castironpi wrote: > > > I'm baffled. ?I don't understand what you write. ? > > Which is pretty much how I feel about -all- of your posts. Alright. You're articulate. I'm getting a better picture of what your problem with me is. What we have is a misunderstanding, *not a war*. If you think I leave the grounds of civil argument, be sure to say so. Otherwise, I'll expect observation, premise, conclusion. Just like a good A.I. would. (Computers are good at something, and that's logic.) > > I think someone in > > my shoes would be justified in dismissing it as either malicious or a > > miscommunication. ? > > No, it's frustration at the sharp decrease in signal:noise that this > newsgroup has undertaken since your arrival. You also want to assign causality and/or blame as a result. The evidence is circumstantial. I'm sorry you're frustrated. If I've had a negative influence, which is hard to prove, that would mean that I'm influential (in the bad way). I'm not sure I can accept that at this point in my life. It's a problem. But I also feel that I've been plonked without hearing me out, which only escalates the frustration. (Google search castironpi+plonk. Ha.) > But how about this, your code snippet from this very thread, > your -first- of two seemingly independent replies to the original > post: > > > ?def _getbalance( self ): > > ? ?return self._tree.geti( > > ? ? ?self.where+ self.lookup[ 'balance' ] ) > > > ?def _getparent( self ): > > ? ?return self._tree.getI( > > ? ? ?self.where+ self.lookup[ 'parent' ] ) > > > Where 'balance' and 'parent' could both come from something generic: > > > balance= property( tree_lookup( 'balance' ) ) > > parent= property( tree_lookup( 'parent' ) ) > > In your 'example', you reference one marked-as-implementation > attribute, two unspecified attributes, one unspecified method and one > unspecified function. That you refer to one function as both 'geti' > and 'getI' leads me to believe this -isn't- workable code and you've > just re-keyed this in without testing. It is from real code. If you want the link say so. It's an in-place memory manager that I think is quite nifty... *and* functional. *And* pure Python. Others earlier proposed similar things; mine was just more specialized. Miles: x = defaultproperty('_x') y = defaultproperty('_y') Medardo: x = property(*attrmanager('_x')) y = property(*attrmanager('_y')) I see a similarity between theirs and mine, but you only criticize mine. Do you agree that mine was similar? If I would have said, "Where 'balance' and 'parent' both share something generic", instead of "could both come from something generic", would that have made more sense? That would definitely be my fault. Word choice is definitely a weakness and I am not perfect. > I've also -no- idea what you're trying to demonstrate here. It's not > clear nor obvious, and I can't see how your _getwhatever methods tie > in with the property definition. My point was, "Here's one snippet you could clear up with some abstraction." It answers the OP's question directly: "It works well enough, but I can't help feeling there a cleaner more readable way of doing this (with less duplication, etc). Is this as good as it gets?" But I did not organize my post well, so I can see your confusion. > > For instance, "I won't like it if you do" and "I won't think it's > > clever if you do" aren't consistent belief structures, they're fight > > structures. ?You have made such claims. > > No, what I've stated is I've yet to see -any- code samples that you've > provided be of any real, clear use to -anyone-. This isn't a 'fight > structure', this is an opinion formed by the overwhelming amount of > evidence you keep contributing to this group. I'm lost. Do you want to see some clever code, even if I wrote it, and even if I think it is clever too? I am wanting a code review. > > In the post above, I make two claims, ask two questions, and encourage > > a brainstorm. ?I don't see how what you say applies to it. > > What you said was: "When brainstorming, don't restrict yourself to > Python syntax-- make > something up, and we'll write Python." > > What I'm contesting is your ability to write Python. > > Furthermore, people -aren't- posting questions to the "castironpi > hour", they're asking questions to help further their understanding of > Python, not to give you further opportunity to emphasise your > misunderstanding of it. Suggesting they 'brainstorm' without any > understanding of the language itself and that you'll somehow magically > generate Python code for them is, based on what you've written here, > laughable. No, and this is not my editorial, blog, or advice column, no matter how much I write. Brainstorming is healthy and productive. The OP was looking for a way to improve something he'd written and was already working. I was urging him to think outside the box, then get help getting back "in to the box," metaphorically. This is different than inviting someone to brainstorm who is asking for help with the 'range' function, you know. Python makes a lot of things possible that other languages don't, and I don't believe that anyone knows the extent of that. > > I am willing to change the way I communicate. ?I want to communicate > > effectively. ?But, until someone takes something I want to say, and > > says it the right way, I can't learn how. ?So I wait and write Python, > > and share my frustration with my peers. > > Given how many people have publicly killfiled you on this group, I'm > not sure who you consider to be your 'peers'. There was a -lot- of > initial frustration at your post, along with even more dismissal of it > as the output of a poorly written AI experiment. YES, no kidding. I'm amazed myself, but I just chalk it up to my being new on Usenet and bad with people. I'll work on it but Rome wasn't built in a day. My peer is someone who is bad at communicating. How am I supposed to establish communication with him or her? > You're -failing- the Turing test. If that isn't telling you something > is wrong with your communication style, I don't really know what will. I am aware, thanks to the group, that something is wrong. But I don't know what it is. > Assumed by someone... [snip, ok?] > Which leads me to reiterate my original statement, only framing it now > as a question: what -real world- applications or systems have you > worked on...in -any- language? I find it difficult to believe you've > ever worked on any, or even more pointedly, had to work on -someone > else's real world code-. Because the sample code fragments you post, > when not broken, at best seem to relate to pointless wankery on your > behalf, without any practical application whatsoever, and at worst > carry deep-seated misunderstandings about how Python works. Most of my programming is either academic research, academic study, or hobbyist. If you're asking if I have any experience, yes I do. If you're asking whether I've been forced to write awful code under someone else's deadline, no I haven't. That's important. I don't know what trait that gives my code, maybe abstractness, but no my experience is not typical. And the academic research wasn't for the business colleges either. If you want my credentials, e-mail me. I went to a 4-year Research 1, but I believe that people's work should speak for itself. My offer stands to show you my code. Probably not my resume or work history though. Fair? Lastly, if I spend too much time on the newsgroup (300 in February, wow), that is, on this one newsgroup, it's important to bring that to my attention. That is not something that anyone can judge for themselves. (A famous philosopher contends that friends are the harshest critics.) It is Ok to have that opinion and it's ok if you notice it; that doesn't automatically mean you do too. I could use a kick in the rear to branch out, and perhaps diversify my time. I think I would find it most productive to point-blank say so. From gzlist at googlemail.com Tue Aug 26 11:20:05 2008 From: gzlist at googlemail.com (Martin (gzlist)) Date: Tue, 26 Aug 2008 16:20:05 +0100 Subject: [ctypes-users] ctypes - loading 'librsvg-2-2.dll' In-Reply-To: <48B3B8B3.5070309@sil.org> References: <48B3B8B3.5070309@sil.org> Message-ID: On 26/08/2008, Tim Grove wrote: > Any ideas why a particular dll won't load on Windows XP Pro using > ctypes? I'm going to take a stab in the dark here and suggest it's because you have multiple (different) copies of iconv.dll on your PATH. > l=CDLL(r'D:\SILSign\librsvg-2-2.dll') > Traceback (most recent call last): > File "", line 1, in > File "C:\PYTHON25\LIB\ctypes\__init__.py", line 349, in __init__ > self._handle = _dlopen(self._name, mode) > WindowsError: [Error 127] The specified procedure could not be found I get this on my current setup, where I've been messing around trying to recompile lynx against iconv. I also get a popup saying "The procedure entry point libiconv_set_relocation_prefix could not be located in the dynamic link library iconv.dll." Doing this worked for me: C:\>set PATH=C:\Program Files\Common Files\GTK\2.0\bin C:\>"C:\Python24\python.exe" -c "import ctypes; print ctypes.CDLL('librsvg-2-2')" Change the paths to your equivalents and try it, see if you have the same or a similar dependency problem. Martin From mathieu.prevot at ens.fr Thu Aug 21 01:41:54 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Thu, 21 Aug 2008 07:41:54 +0200 Subject: subprocess seems to "detach" / ignore wait() In-Reply-To: References: Message-ID: <3e473cc60808202241j2825bc3cl7f1050f1ec68563b@mail.gmail.com> 2008/8/20 Gabriel Genellina : > En Wed, 20 Aug 2008 12:22:16 -0300, Wojtek Walczak escribi?: > >> On Wed, 20 Aug 2008 15:09:11 +0200, Mathieu Prevot wrote: >> >>> child = Popen(cmd.split(), stderr=flog) >>> print "Server running [PID %s]"%(child.pid) >>> fpid.write(child.pid) >> >> I think that the problem here is that fpid.write() fails silently >> (probably TypeError), because it takes string as its first argument, >> not integer. > > Exactly, but it doesn't fail "silently" (that would be a bug). The exception is raised, but due to the finally clause ending in sys.exit(0), it has no chance of being handled. > This is the original code, for reference: > > flog = open(logfile, 'w') > fpid = open(pidfile, 'w') > try: > child = Popen(cmd.split(), stderr=flog) > print "Server running [PID %s]"%(child.pid) > fpid.write(child.pid) > child.wait() > except KeyboardInterrupt: > print "INT sent to vnc server" > finally: > fpid.close() > flog.close() > os.remove(pidfile) > os.remove(logfile) > sys.exit(0) > > -- > Gabriel Genellina Indeed, I got TypeError: argument 1 must be string or read-only character buffer, not int and Wojtek's code works. So what is the right thing to do so my script returns 1 or 0 depending on its state and success ? Mathieu From harrrrpo at gmail.com Mon Aug 25 12:57:04 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Mon, 25 Aug 2008 19:57:04 +0300 Subject: QT 4.4 and timedelta In-Reply-To: References: Message-ID: <538050a90808250957j573f7a0ascf21aa0f9179c81e@mail.gmail.com> I'm not very sure about this , but it's logicallay enough to be said i think the QTableView ordering mechanism must provide some overriding functionality through accepting a comparing function from you check it On Mon, Aug 25, 2008 at 7:48 PM, admoore wrote: > Maybe I'm missing something obvious, but is there a QT object to > represent time intervals, a la datetime.timedelta? > > I'm working on a utility that displays database query results from a > postgres database (using psycopg2) in a QTableView. For columns > created using "age(some_date_column)", I get a datetime.timedelta > object from psycopg2. > > What I'd like is to be able to format this column in a friendly way > (say "7 years, 2 months, 4 days"), yet have the QTableView treat it > properly (e.g. for sorting purposes, not sorting it lexically but by > the actual length of time). > > Anyone have any input or ideas on this? > -- > http://mail.python.org/mailman/listinfo/python-list > From castironpi at gmail.com Thu Aug 21 13:50:11 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 21 Aug 2008 10:50:11 -0700 (PDT) Subject: getattr() on nested functions? References: <48abe483$0$31875$426a74cc@news.free.fr> <48AC322E.9000404@arimaz.com> <48ad5980$0$4634$426a74cc@news.free.fr> <48ad8631$0$3819$426a74cc@news.free.fr> Message-ID: <8f3774ac-2c90-4a7a-a3d8-e39bcd8738cd@79g2000hsk.googlegroups.com> On Aug 21, 10:14?am, Bruno Desthuilliers wrote: > Gabriel Rossetti a ?crit : > > > > > Bruno Desthuilliers wrote: > >> Gabriel Rossetti a ?crit : > >>> Terry Reedy wrote: > >> (snip) > >>>> Unlike the class approach, this requires recreating the constant > >>>> functions and dict with each call to _test. ?Quick to write but a > >>>> bit 'dirty', in my opinion. ?Another standard idiom is to set up the > >>>> constants outside the function: > > >>>> def request(params): > >>>> ? ? pass > >>>> def submit(params, values): > >>>> ? ? pass > >>>> def update(params, values): > >>>> ? ? pass > >>>> def delete(params): > >>>> ? ? pass > >>>> dispatch = {'request':request, 'submit':submit, 'update':update, > >>>> 'delete':delete} > > >>>> def _test(self, action, *args): > >>>> ? ? return resultToXmo(dispatch[action](*args)) > > >>> That's how I had done it originally (before the use of eval()), but > >>> in this case also, since the functions are still nested, > > >> Uh ??? You probably want to re-read the above code snippet. > > > Uh...yes, I didn't see the external/parent function was no longer there. > > I prefer to nest mine though because I have several parent functions for > > different tasks, so each child/nested function has a diff. > > implementation, I find that cleaner than having n*4+n top-level > > functions (+ n dicts), e.g. I prefer this : > > > ? ?def __task1(self, action, *args): > > ? ? ? ?def request(params): > > ? ? ? ? ? ?pass > > ? ? ? ?def submit(params, values): > > ? ? ? ? ? ?pass > > ? ? ? ?def update(params, values): > > ? ? ? ? ? ?pass > > ? ? ? ?def delete(params): > > ? ? ? ? ? ?pass > > ? ? ? ?return resultToXml(locals()[action](*args)) > > > ? ?def __task2(self, action, *args): > > ? ? ? ?def request(params): > > ? ? ? ? ? ?pass > > ? ? ? ?def submit(params, values): > > ? ? ? ? ? ?pass > > ? ? ? ?def update(params, values): > > ? ? ? ? ? ?pass > > ? ? ? ?def delete(params): > > ? ? ? ? ? ?pass > > ? ? ? ?return resultToXml(locals()[action](*args)) > > > over this : > > (snip) > > > I could use your callable approach, but like you said it may not be > > worth the trouble. > > The "trouble" I was talking about was not with using callable objects, > but with trying to hack func.func_code to extract nested functions (if > ever possible). > > But anyway... The point of using callable objects is to avoid going thru > the whole "setup" part again and again and again. Now if all your task > functions only differ by the dispatch dict, there's at least another > ways to avoid this runtime repetition - as well as coding repetition > FWIW (warning : untested code): > > def _make_task(func): > ? ? ?dispatch = func() > ? ? ?def _task(action, *args): > ? ? ? ? ?return resultToXml(dispatch[action](*args)) > ? ? ?_task.__name__ = _task.func_name = func.__name__ > ? ? return _task > > @_make_task > def _task1(): > ? ? ?def request(params): > ? ? ? ? ?pass > ? ? ?def submit(params, values): > ? ? ? ? ?pass > ? ? ?def update(params, values): > ? ? ? ? ?pass > ? ? ?def delete(params): > ? ? ? ? ?pass > ? ? ?return locals() > > HTH Here's more ideas: Use a wrapper to give the function access to itself as an object: @auto def f( self, arg ): assert self== f In your original example: @auto def toto( toto ): def titi(): pass f = getattr(toto, "titi") print str(f) Should work, untested. Another is to use a wrapper to participate functions in a dictionary: @entry( 'a' ) def a( arg ): a_stuff( ) @entry( 'b' ) def b( arg ): b_stuff You could even make 'entry' a class instance, so you can specialize and vary it in other cases, untested. Last one is just use a class, untested: class __Test: def __test(self, action, *args): result = getattr(self, action)(*args) return resultToXml(result) def request(self,params): pass def submit(self,params, values): pass def update(self,params, values): pass def delete(self,params): pass Keep us posted which one works for you. From alexis.boutillier at arteris.com Fri Aug 29 03:48:59 2008 From: alexis.boutillier at arteris.com (Alexis Boutillier) Date: Fri, 29 Aug 2008 09:48:59 +0200 Subject: Syntax error in ".py" file and globals variable values not available. In-Reply-To: References: <48B5232D.6080205@arteris.com> <48B6647F.8090402@arteris.com> Message-ID: <48B7A9EB.4020003@arteris.com> Timothy Grant a ?crit : > On Thu, Aug 28, 2008 at 1:40 AM, Alexis Boutillier > wrote: >> Timothy Grant a ?crit : >>> On Wed, Aug 27, 2008 at 2:49 AM, Alexis Boutillier >>> wrote: >>>> Hi, >>>> >>>> I have a strange behaviour of python with pdb and import statement. >>>> Here is the example code : >>>> >>>> file my1.py: >>>> import my2 >>>> >>>> file my2.py: >>>> a=5 >>>> toto >>>> >>>> I intentionnaly put a syntax error in file my2.py. >>>> >>>> If I run "python -i my2.py" and run pdb I got : >>>> NameError: name 'toto' is not defined >>>>>>> import pdb >>>>>>> pdb.pm() >>>> -> toto >>>>>>> print a >>>> 5 >>>> >>>> If I run "python -i my1.py" and run pdb I got : >>>> NameError: name 'toto' is not defined >>>>>>> import pdb >>>>>>> pdb.pm() >>>> -> toto >>>>>>> print a >>>> None >>>> >>>> Why can't I get access to variable a in pdb when the process generating >>>> the >>>> error came from an import statement ? >>>> >>>> With python 2.3.5, it works fine and in the two cases I get the correct >>>> value of 5 for variable "a". >>>> with python 2.43,2.5.1,2.5.2, it doesn't work and I get "None" value for >>>> variable a. >>>> >>>> Somebody can explain me this behaviour ? >>>> >>>> >>>> Thanks. >>>> -- >>>> Boutillier Alexis >>>> Methodology engineer >>>> >>>> Arteris SA >>>> The Network-on-Chip Company TM >>>> www.arteris.net >>>> >>>> 6 par Ariane Immeuble Mercure >>>> 78284 Guyancourt Cedex >>>> France >>>> Office: (+33) 1 61 37 38 71 >>>> Fax: (+33) 1 61 37 38 41 >>>> Alexis.Boutillier at arteris.net >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>>> >>> >>> Because of the syntax error the module wasn't loaded. >>> >>> What kind of behaviour would you expect on code that has been flagged >>> as not executable? >>> >> I got the same behaviour with : >> file my2.py: >> a=5 >> raise SystemError,"" >> >> In pdb, I can't have the value of attribute a. >> So this is not linked to the fact that it is a SyntaxError or a SystemError. >> >> I expect to be able to have the value of all attributes that have been used >> before the error occured. >> This is problematic because in a more complicated code, you can't have the >> value of the attribute that was used before the error occured. >> Python know that this attribute exist, it only don't have its value. other >> attribute affected are : __name__,__doc__,__file__. >> >> -- >> Boutillier Alexis >> Methodology engineer >> >> Arteris SA >> The Network-on-Chip Company TM >> www.arteris.net >> >> 6 par Ariane Immeuble Mercure >> 78284 Guyancourt Cedex >> France >> Office: (+33) 1 61 37 38 71 >> Fax: (+33) 1 61 37 38 41 >> Alexis.Boutillier at arteris.net >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > So if you were writing C code and the file failed to compile you would > still expect to have a working executable that just worked up until > the point of the syntax error? > > I'm not sure why you just don't fix the syntax error and move on. > > As you can see in my last response, this problem is not linked to the type of error, If I "raise" a SystemError instead of creating a SyntaxError I still can't access variable defined before the error. -- Boutillier Alexis Methodology engineer Arteris SA The Network-on-Chip Company TM www.arteris.net 6 par Ariane Immeuble Mercure 78284 Guyancourt Cedex France Office: (+33) 1 61 37 38 71 Fax: (+33) 1 61 37 38 41 Alexis.Boutillier at arteris.net From castironpi at gmail.com Sun Aug 24 11:28:50 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 24 Aug 2008 08:28:50 -0700 (PDT) Subject: In-place memory manager, mmap (was: Fastest way to store ints and floats on disk) References: <1cf85075-17a1-4a1d-8ea5-bf5104541528@s50g2000hsb.googlegroups.com> Message-ID: On Aug 24, 9:52?am, Kris Kennaway wrote: > castironpi wrote: > > Hi, > > > I've got an "in-place" memory manager that uses a disk-backed memory- > > mapped buffer. ?Among its possibilities are: storing variable-length > > strings and structures for persistence and interprocess communication > > with mmap. > > > It allocates segments of a generic buffer by length and returns an > > offset to the reserved block, which can then be used with struct to > > pack values to store. ?The data structure is adapted from the GNU PAVL > > binary tree. > > > Allocated blocks can be cast to ctypes.Structure instances using some > > monkey patching, which is optional. > > > Want to open-source it. ?Any interest? > > Just do it. ?That way users can come along later. > > Kris How? My website? Google Code? Too small for source forge, I think. From paul at boddie.org.uk Fri Aug 29 15:15:24 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 29 Aug 2008 12:15:24 -0700 (PDT) Subject: problem with packages and path References: <8c1351f9-d349-4c0c-97a4-024c9472bff3@z11g2000prl.googlegroups.com> <41e605c6-05e3-4a5a-a8f4-978d63e64cf6@k36g2000pri.googlegroups.com> Message-ID: On 29 Aug, 19:08, Daniel wrote: > > I have tried running both commands above from the mypackage directory > and unittests directory. I get the following response universtally. > > C:\mypackage>dir > Volume in drive C is Default > > Directory of C:\mypackage > > 08/29/2008 11:04 AM . > 08/29/2008 11:04 AM .. > 08/29/2008 11:05 AM module1 > 08/29/2008 11:05 AM module2 > 08/29/2008 11:06 AM unittests > 08/29/2008 11:04 AM 0 __init__.py > 1 File(s) 0 bytes > 5 Dir(s) 55,402,070,016 bytes free If you run unittests\alltests.py from here, sys.path will initially refer to this directory (C:\mypackage) and to anything else set up in your environment. The extra path modification that you put in alltests.py will append (or insert) the following... os.path.normpath( os.path.join( __file__, "../../" )) -> os.path.normpath( os.path.join( "C\\:mypackage\\unittests\ \alltests.py", "../../" )) -> os.path.normpath( "C\\:mypackage" ) -> "C\\:mypackage" Since the import statement then tries to access mypackage, which isn't itself in the C:\mypackage directory - it's in the C:\ directory - the import fails. The previous, automatically added entry in sys.path is duplicated by the path modifications shown above, so that won't help here, either. > C:\mypackage>dir unittests > Volume in drive C is Default > > Directory of C:\mypackage\unittests > > 08/29/2008 11:06 AM . > 08/29/2008 11:06 AM .. > 08/29/2008 11:05 AM 0 alltests.py > 08/29/2008 11:05 AM 0 test1.py > 08/29/2008 11:05 AM 0 test2.py > 08/29/2008 11:04 AM 0 __init__.py > 4 File(s) 0 bytes > 2 Dir(s) 55,401,988,096 bytes free Here, sys.path should refer to C:\mypackage\unittests somewhere, which won't help Python find mypackage. The path modification in alltests.py should perform as above, producing C:\mypackage which won't help. I guess the easiest thing to do is to change the path modification code to use "../../.." which should produce a reference to C:\ instead of C:\mypackage. The confusion with this particular piece of the code is the way ".." doesn't cause os.path.join to operate on the directory C:\mypackage\unittests but instead on the file C:\mypackage\unittests \alltests.py - that's almost to be expected, however, since os.path.join doesn't really know that its first argument is really a file or that ".." is being combined with a file. What I tend to do, especially with __file__, is to first use os.path.split to remove the filename - strictly speaking, it's the leafname - and then to apply the kind of modifications mentioned above, although there's probably no real difference or, indeed, any advantage with either approach. Paul From ggpolo at gmail.com Thu Aug 14 11:05:32 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 14 Aug 2008 12:05:32 -0300 Subject: Tkinter updates - Easiest way to install/use Tile? In-Reply-To: References: Message-ID: On Wed, Aug 13, 2008 at 2:10 PM, Mudcat wrote: > So I haven't programmed much in Python the past couple of years and > have been catching up the last few days by reading the boards. I'll be > making commercial Python applications again and wanted to see what's > new in the Gui department. > > I started using Tkinter several years ago and have a lot of stuff > written in it. As a result, it's hard to switch to another interface > (wxPython, PyQt, etc) with all the hours it would take to reproduce > code I will re-use. (I mention this to avoid the inevitable post > asking why I'm still using it). While I was able to produce some nice > applications in the past and am comfortable with the functionality I > was able to achieve I still wanted to find a way to improve the look > since the old look is even more dated now. > > I was reading about Tile, and it sounds like I should be able to wrap > a style around my current code to give it a different look. However it > doesn't sound like it's quite ready for prime time yet. I downloaded > the latest stable version of Python 2.5 which apparently still uses > Tcl 8.4. So my options at this point appear to be: > > 1) Download beta version of Python 2.6 which has Tcl 8.5. > Tile is supposed to be included with Tcl 8.5, but there's not much > information on how to use it with older code. Do I still need wrapper > code, or if I install 2.6 will it be available already. > > 2) Install Tcl 8.5 to use with Python 2.5. > How do you do this? In other posts it mentions recompiling source tcl > code with Python. If that's the case it doesn't sound like something I > want to mess with. If I stray too far from default configurations I > start to have problems with py2exe. > > 3) Install Tile with Python 2.5 and Tcl 8.4 and use wrapper code to > make it work. > However all the posts concerning this approach assume that Tile is > already installed. I downloaded the code for the latest version of > Tile which was a .kit extension. This also may need to be compiled, > and if that's the case I again start to have problems with freezing my > application. The other points were answered already, so let me give some more insight on this last one. For Windows there is a .zip you can download (following the links at http://tktable.sourceforge.net/tile/) which requires no installation, just unpacking. For Linux there is a package named tk-tile in Ubuntu. In case you are using Windows, just unpacking the .zip doesn't guarantee that Tk will find the tile package (unless you unpack at whatever places Tk looks by default). If Tk doesn't find it, you need to set the TILE_LIBRARY environment variable to whatever place tile was unzipped to. I'm assuming you will be using the previously mentioned ttk wrapper, which will look at TILE_LIBRARY, if necessary, to load tile. > > What's the easiest way to do this? I really couldn't find a place that > gave instructions for any of the current release configurations. It > sounds if it's available already in Python 2.6 that it would be the > easiest way, but I couldn't find any threads talking about the > availability of it for that release yet. > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From simon at mullis.co.uk Thu Aug 14 05:26:31 2008 From: simon at mullis.co.uk (Simon Mullis) Date: Thu, 14 Aug 2008 11:26:31 +0200 Subject: From Ruby to Python? In-Reply-To: <23d7e1bb0808130545w28fb4c04s205c1de2a39dcb36@mail.gmail.com> References: <23d7e1bb0808130545w28fb4c04s205c1de2a39dcb36@mail.gmail.com> Message-ID: <23d7e1bb0808140226r63fed22ev2ad83718b591f398@mail.gmail.com> In case anyone else has the same question: This has been very useful: http://www.poromenos.org/tutorials/python Short, concise. Enough to get me going. SM 2008/8/13 Simon Mullis > Hi All, > > I just finally found 30 minutes to try and write some code in Python and > realized after a couple of minor syntactic false starts that I'd finished my > initial attempt without needing to refer to any documention... And after the > first few minutes I stopped noticing the whitespace thing that had scared me > off previously. (Admittedly it's a very basic script using telnetlib to log > into a bunch of network devices via a few console servers and put the > results of some remote commands into a data-structure). > > So, after this initially promising start: > > Are there any good cheatsheets / guides for a Ruby programmer to learn > Python? > > I searched this list and couldn't find anything, and wasn't successful with > google either... > > Many thanks in advance, > > SM > > -- > -- Simon Mullis _________________ simon at mullis.co.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: From mdboldin at gmail.com Wed Aug 6 15:40:12 2008 From: mdboldin at gmail.com (mmm) Date: Wed, 6 Aug 2008 12:40:12 -0700 (PDT) Subject: SMTP via GMAIL References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> Message-ID: <93afa637-9292-4628-9028-ca6f8b299914@x35g2000hsb.googlegroups.com> On Aug 5, 12:18?am, Tim Roberts wrote: > >But when using smtp.gmail.com as the server I learned that any > >@gmail.com address in the ?Cc: text block would > >receive mail even if I changed the code to have the RECEIVERS list to > >ignore the CC addresses or not include the gmail address in the CC > >list as below > > Interesting. ?If true, that is incorrect behavior. I ran some more tests and now I am pretty sure session.sendmail(SENDER, RECEIVERS, BODY) is only sending to the RECEIVERS list, ignoring the Cc: field in the body (as it should) What fooled me is that I was using my own gmail account (i.e., me at gmail.com) as a Cc: field and not putting it in the RECEIVERS list. It seems Gmail creates two links (or copies?) to the message: (1) as it is stored in the SENT box (as it should since the message was sent by my gmail account) and (2) another in my INBOX because the mail reading software reads the Cc: field. Other smtp servers such as comcast do not create the stored SENT mail and hence behave different in terms of how they treat Cc: fields of the same account (me at comcast.net in this case). Most important, using another gmail account (not me at gmail.com) as a Cc: field does not create another sent message (outside of what is in the RECEIVERS field). Sorry for confusion, and I do appreciate the tips as I now see how almost anything To:, Cc:, Bcc: combination can be handled by a proper RECEIVERS list. Below is python code that can be used by anyone that wants to test what I did (just fill in the SMTPuser and password variables) and then check you gmail inbox import sys, os, glob, datetime, time import smtplib ## Parameters for SMTP session port=587 SMTPserver= 'smtp.gmail.com' SMTPuser= 'you at gmail.com' pw= 'fill in here' SENDER= SMTPuser ## Message details FROM= SENDER TO= 'notgmail at a.com' CC=FROM ##RECEIVERS= (TO, CC) ##proper way to send to both TO and CC RECEIVERS= (TO,) ## ignore the CC address subject= 'Test 1a' message='*** Email test *** ' print 'Starting SMTP mail session on %s as %s ' % (SMTPserver,SMTPuser) session = smtplib.SMTP(SMTPserver,port) session.set_debuglevel(0) # set debug level to 1 to see details session.ehlo(SMTPuser) # say hello session.starttls() # TLS needed session.ehlo(SMTPuser) # say hello again, not sure why session.login(SMTPuser, pw) ##Create HEADER + MESSAGE HEADER= 'From: %s\r\n' % FROM HEADER= HEADER + 'To: %s\r\n' % TO HEADER= HEADER + 'Cc: %s\r\n' % CC HEADER= HEADER + 'Subject: %s\r\n' % subject BODY= HEADER + '\r\n' + message print BODY SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) ## send email session.close() From mikael at isy.liu.se Thu Aug 21 04:06:59 2008 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 21 Aug 2008 10:06:59 +0200 Subject: Negative integers In-Reply-To: References: Message-ID: Derek Martin wrote: > Zero is a problem, no matter how you slice it. I definitely agree with that. Depends on the the real problem that is behind the OP:s question. > Zero can be considered > positive or negative (mathematically, 0 = -0). I've read quite a few articles written by mathematicians and mathematically oriented engineers, and my impression is that most of them, and therefore me included, use those words with the following meaning: Positive: >0 Negative: <0 When zero is to be included, the following terms are used: Non-negative: >=0 Non-positive: <=0 Using this convention, zero is neither positive nor negative. Wikipedia seems to agree with that: http://en.wikipedia.org/wiki/Positive_number /MiO From zondo42 at googlemail.com Fri Aug 29 14:26:37 2008 From: zondo42 at googlemail.com (Glenn Hutchings) Date: Fri, 29 Aug 2008 19:26:37 +0100 Subject: When to use try and except? References: <8a2dd955-6641-493d-b7eb-3e29c14686a5@26g2000hsk.googlegroups.com> <914fde08-5084-455f-ac68-bef7e06cc3dc@i76g2000hsf.googlegroups.com> Message-ID: cnb writes: > A ZeroDivisionError is better avoided wth an if-clause, don't you > think? It is a predictable exception... It depends. If zero-division is unlikely, then things would probably[*] run faster without checking. If speed is what you're interested in, that is... Glenn [*] Haven't checked, so don't really know :-) From fredrik at pythonware.com Wed Aug 13 17:31:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Aug 2008 23:31:42 +0200 Subject: Replace Several Items In-Reply-To: References: <513926b0-64fe-4fdc-bb33-bc4b8ad3ab10@a70g2000hsh.googlegroups.com> Message-ID: Wojtek Walczak wrote: >> I wish to replace several characters in my string to only one. >> Example, "-", "." and "/" to nothing "" >> I did like that: >> my_string = my_string.replace("-", "").replace(".", "").replace("/", >> "").replace(")", "").replace("(", "") >> >> But I think it's a ugly way. >> >> What's the better way to do it? > > The regular expression is probably the best way to do it, > but if you really want to use replace, you can also use > the replace method in loop: suggested exercise: benchmark re.sub with literal replacement, re.sub with callback (lambda m: ""), repeated replace, and repeated use of the form if ch in my_string: my_string = my_string.replace(ch, "") on representative data. From david at abbottdavid.com Sat Aug 2 16:34:02 2008 From: david at abbottdavid.com (David) Date: Sat, 02 Aug 2008 16:34:02 -0400 Subject: raw_input on several lines In-Reply-To: References: Message-ID: <4894C4BA.90309@abbottdavid.com> TP wrote: > Hi everybody, > > When using raw_input(), the input of the user ends when he types Return on > his keyboard. > How can I change this behavior, so that another action is needed to stop the > input? For example, CTRL-G. It would allow the user to input several lines. > > Thanks > > Julien > > > How about; student_scores = {} name = raw_input("Please enter a student name (q quits): ") while(name != 'q'): score = input("Please enter the students score: ") student_scores[name] = score name = raw_input("Please enter a student name (q quits): ") for current_key in student_scores.keys(): print "The current students are:", current_key -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From vinay_sajip at yahoo.co.uk Wed Aug 20 07:02:25 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 20 Aug 2008 04:02:25 -0700 (PDT) Subject: Logging library unicode problem References: <4d726712-ef30-4292-9b1d-28e3cb8c3282@r35g2000prm.googlegroups.com> Message-ID: On 13 Aug, 11:08, Victor Lin wrote: > Hi, > I'm writting a application using python standardloggingsystem. I > encounter some problem with unicode message passed tologginglibrary. > I found that unicode message will be messed up bylogginghandler. > > piese of StreamHandler: > > try: > self.stream.write(fs % msg) > except UnicodeError: > self.stream.write(fs % msg.encode("UTF-8")) > > It just write the message to stream. If there is some unicode error, > it would rewrite msg with utf8 encoding. > > I write some code to try: > > import sys > print u'?????' > print sys.stdout.encoding > sys.stdout.write(u'??') > > result of that program: > > ????? > cp950 > Traceback (most recent call last): > File "update_stockprice.py", line 92, in > sys.stdout.write(u'???') > UnicodeEncodeError: 'ascii' codec can't encode characters in position > 0-1: ordin > al not in range(128) > > It show that.... > > 1. print statement encode what it get with stream.encoding? > 2. stream.write don't do anything like encoding, just write it > (because it might be binary data?) > > So the problem is : the StreamHandler of standardlogginglibrary use > stream.write to log message, if there is unicode error, unicode string > will be encode to utf8. This behavior mess my unicode up. > > Here I modify the code of StreamHandler: > > try: > print >> self.stream, msg > #self.stream.write(fs % msg) > except UnicodeError: > self.stream.write(fs % msg.encode("UTF-8")) > > I replace stream.write with print statement, so that it will try to > use stream.encoding to encode msg. Now everything works fine. > > My question is : > Could the behavior of StreamHandler be considered as a bug? > If it is, how to report this bug? > Is my solution correct? > Are there any side effect will caused by doing so? > If the code I write is fine, and solve that problem, how to report it > to Python's project? > I think this could be helpful for people who also encountered this > problem. > > Thanks. > Victor Lin. Hi Victor, Can you try modifying your patch to use the following logic instead of the print statement? if hasattr(self.stream, 'encoding'): self.stream.write(fs % msg.encode(self.stream.encoding)) else: self.stream.write(fs % msg) Does this work in your scenario? Regards, Vinay Sajip From support.desk.ipg at gmail.com Tue Aug 26 18:03:48 2008 From: support.desk.ipg at gmail.com (Support Desk) Date: Tue, 26 Aug 2008 17:03:48 -0500 Subject: Adding Icons to my Programs In-Reply-To: <801533.35218.qm@web83916.mail.sp1.yahoo.com> References: <801533.35218.qm@web83916.mail.sp1.yahoo.com> Message-ID: <016401c907c7$a120d6a0$a601a8c0@office.ipglobal.net> Take a look at this: http://www.velocityreviews.com/forums/t332696-setting-icon-using-py2exe.html -----Original Message----- From: Kevin McKinley [mailto:kem1723 at yahoo.com] Sent: Tuesday, August 26, 2008 4:37 PM To: python-list at python.org Subject: Adding Icons to my Programs I've been turn my script into executible programs with Py2exe. Is there a way to change the icon for the main exe file? Thank you, Kevin McKinley From lists at cheimes.de Thu Aug 28 18:11:17 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 29 Aug 2008 00:11:17 +0200 Subject: Checking if the file is a symlink fails In-Reply-To: <803e077e-c0c9-43d3-b40a-99511c2e55f3@25g2000prz.googlegroups.com> References: <803e077e-c0c9-43d3-b40a-99511c2e55f3@25g2000prz.googlegroups.com> Message-ID: saswat at gmail.com wrote: > File symLinkTest is a symbolic link. > > Why S_ISLNK(mode) returns False and S_ISREG(mode) returns True ? Because you are using os.stat() instead of os.lstat(). http://docs.python.org/lib/os-file-dir.html Christian From rafesacks at gmail.com Tue Aug 19 13:39:44 2008 From: rafesacks at gmail.com (Rafe) Date: Tue, 19 Aug 2008 10:39:44 -0700 (PDT) Subject: cathing uncaught exceptions References: <497a32e3-a14d-469c-b331-e7a32d40ed80@a3g2000prm.googlegroups.com> Message-ID: <75ac3305-7d0f-455b-89df-cbe7a4268ae0@w39g2000prb.googlegroups.com> On Aug 18, 10:02 pm, Alexandru Mosoi wrote: > how can I catch (globally) exception that were not caught in a try/ > catch block in any running thread? i had this weird case that an > exception was raised in one thread, but nothing was displayed/logged. Any chance you might have missed the word "raise", e.g. except Exception, err: Exception(err) vs. except Exception, err: raise Exception(err) This is from the list of stupid things I have done myself, - Rafe From sunp1028 at gmail.com Sun Aug 17 20:57:46 2008 From: sunp1028 at gmail.com (Patrol Sun) Date: Mon, 18 Aug 2008 08:57:46 +0800 Subject: how many nested for can we utilize? In-Reply-To: References: <27cbc0fa0808152200l4be2ca5gc24d8b01458b6e62@mail.gmail.com> Message-ID: <27cbc0fa0808171757h79c7fd10ibc4884040ebc3472@mail.gmail.com> Of course We needn't 100 levels,but I use the exec function can concise the code. See the attachment. 2008/8/17 Fredrik Lundh > Nick Dumas wrote: > > A good quote I read (I can't remember who it was from, though) is "If >> you need more than three levels of indentation, then something is >> seriously wrong with your code." Possibly Guido himself? Anyway. If >> you've got 100 levels of for, you're probably making things way harder >> than they need to be. >> > > assuming 100 levels of for and 2 items in each sequence, you'll end up with > 1267650600228229401496703205376 iterations through the inner loop. assuming > each iteration takes a picosecond, it'll take approx 40 billion years to run > the program. > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: 052.py URL: From Lie.1296 at gmail.com Mon Aug 18 11:04:18 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 18 Aug 2008 08:04:18 -0700 (PDT) Subject: how many nested for can we utilize? References: <27cbc0fa0808152200l4be2ca5gc24d8b01458b6e62@mail.gmail.com> Message-ID: On Aug 17, 4:23?pm, Fredrik Lundh wrote: > Patrol Sun wrote: > > when I use 20 for ,"SystemError: too many statically nested blocks" > > When I use 100 for ,"IndentationError: too many levels of indentation" > > How to handle these errors? > > so why exactly are you trying to nest 20 or 100 for-in loops? > > I think most (all?) algorithm that might use 20+ levels of for-in loops could almost always be replaced with a recursive function. Or at least they could be broken into smaller functions. From martin at see.sig.for.address.invalid Mon Aug 18 05:33:44 2008 From: martin at see.sig.for.address.invalid (Martin Gregorie) Date: Mon, 18 Aug 2008 09:33:44 +0000 (UTC) Subject: The Importance of Terminology's Quality References: <48617847$0$5021$607ed4bc@cv.net> <486ae06b$0$5011$607ed4bc@cv.net> <4883bc90$0$7327$607ed4bc@cv.net> <48a4b2ba$0$20923$607ed4bc@cv.net> <48a782e9$0$20913$607ed4bc@cv.net> <48a8df27$0$7362$607ed4bc@cv.net> Message-ID: On Sun, 17 Aug 2008 22:30:35 -0400, John W Kennedy wrote: > I said "machine language" and I meant it. > OK - I haven't touched that since typing ALTER commands into the console of a 1903 running the UDAS executive or, even better, patching the executive on the hand switches. I was fascinated, though by the designs of early assemblers: I first learnt Elliott assembler, which required the op codes to be typed on octal but used symbolic labels and variable names. Meanwhile a colleague had started on a KDF6 which was the opposite - op codes were mnemonics but all addresses were absolute and entered in octal. I always wondered about the rationale of the KDF6 assembler writers in tackling only the easy part of the job. > Even shops that used assembler nevertheless frequently did bug fixes as > machine-language patches, rather than take the time to run the assembler > again. (SPS, the non-macro basic assembler, ran at about 70 lines a > minute, tops.) > Even a steam powered 1901 (3.6 uS for a half-word add IIRC) running a tape based assembler was faster than that. It could just about keep up with a 300 cpm card reader. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From gh at ghaering.de Mon Aug 25 10:48:49 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 25 Aug 2008 16:48:49 +0200 Subject: newbie question In-Reply-To: References: Message-ID: sharon k wrote: > hi all, > > i am new to python. > > i fetch a webpage with urllib, extract a few numbers in a format as follow; > > 10,884 > 24,068 > > my question is how to remove the comma between the number, since i have > to add them up later. Strings have a replace method. Calling replace(",", "") on the string will do the trick here. -- Gerhard From fredrik at pythonware.com Wed Aug 13 18:31:00 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 00:31:00 +0200 Subject: Replace Several Items In-Reply-To: References: <513926b0-64fe-4fdc-bb33-bc4b8ad3ab10@a70g2000hsh.googlegroups.com> Message-ID: Wojtek Walczak wrote: >> suggested exercise: benchmark re.sub with literal replacement, re.sub >> with callback (lambda m: ""), repeated replace, and repeated use of the form >> >> if ch in my_string: >> my_string = my_string.replace(ch, "") >> >> on representative data. > > I don't have to, I can anticipate the results. Chances are that you're wrong. From cjames at callone.net Tue Aug 26 13:34:50 2008 From: cjames at callone.net (c james) Date: Tue, 26 Aug 2008 12:34:50 -0500 Subject: sum up numbers in a list In-Reply-To: References: Message-ID: >>> L=['10','15','20'] >>> sum(int(x) for x in L) 45 or >>> sum(map(int,L)) 45 sharon kim wrote: > hi all, > > i have a list, for example; > > >>> L=[] > >>> L.append('10') > >>> L.append('15') > >>> L.append('20') > >>> len(L) > 3 > >>> print L > ['10', '15', '20'] > > is there a way to sum up all the numbers in a list? the number of > objects in the list is vary, around 50 to 60. all objects are 1 to 3 > digit positive numbers. > > all i can think of is check the length of the list (in the above > example, 3), then L[0]+L[1]+L[2] ...... > > is there a better way to do the job? thanks. From benjamin.michiels at gmail.com Tue Aug 12 10:41:23 2008 From: benjamin.michiels at gmail.com (Benjamin Michiels) Date: Tue, 12 Aug 2008 16:41:23 +0200 Subject: Thesaurus / ontology / taxonomy Python library Message-ID: Hi, I am curently looking for a library allowing the creation and management of a thesaurus. Our requirements are the following: - creation of our own thesaurus (that is, terms AND relations between terms), and indexing (and retrieving) documents with terms defined in our thesaurus, - "thesauraus management facilities", such as batch editing of content items (e.g. for all documents indexed by keyword "A" and "B", replace keywords "A" and "B" by keyword "C"). - user-friendly interface. This could a be tree-like structure (with - ideally - several levels of indexing), such as: Shape - TS: Square + TS: Triangle - TS: Scalene triangle + TS: Equilateral triangle - [...] Ideally, this library would be ready-for-Plone3.x-Zope2.10; but after some - basic - searches, it appeared that such thesaurus management tools are rather rare, so I was wondering whether there would even exist such a library in Python... What do you think of it and/or is there already a discussion on this topic? Thank you in advance, Benjamin Michiels -------------- next part -------------- An HTML attachment was scrubbed... URL: From info at thegrantinstitute.com Wed Aug 13 05:14:46 2008 From: info at thegrantinstitute.com (Anthony Jones) Date: 13 Aug 2008 02:14:46 -0700 Subject: Professional Grant Proposal Writing Workshop (September 2008: British Columbia Institute of Technology - Vancouver Campus) Message-ID: <20080813021446.8C98E6D340E4553A@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Aug 22 12:53:05 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 22 Aug 2008 09:53:05 -0700 (PDT) Subject: Should Python raise a warning for mutable default arguments? References: <00becb2d$0$20312$c3e8da3@news.astraweb.com> Message-ID: On Aug 22, 9:42?am, Steven D'Aprano wrote: > Sometimes it seems that barely a day goes by without some newbie, or not- > so-newbie, getting confused by the behaviour of functions with mutable > default arguments. No sooner does one thread finally, and painfully, fade > away than another one starts up. > > I suggest that Python should raise warnings.RuntimeWarning (or similar?) > when a function is defined with a default argument consisting of a list, > dict or set. (This is not meant as an exhaustive list of all possible > mutable types, but as the most common ones that I expect will trip up > newbies.) The warning should refer to the relevant FAQ or section in the > docs. > > What do people think? > > -- > Steven I like the idea of calling it to your attention. +1. If a warning, you should be able to silence it with an annotation, decorator, or a module-level flag. Or perhaps, require it be declared explicit, and make it an error. def test(x, a=defmut([])): Python raises an actual error unless default arguments are known immutable or instances of 'defmut'. From gminick at nie.ma.takiego.adresu.w.sieci.pl Wed Aug 13 18:39:58 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Wed, 13 Aug 2008 22:39:58 +0000 (UTC) Subject: Suggestion for improved ImportError message References: Message-ID: Dnia Wed, 13 Aug 2008 22:15:48 +0000 (UTC), Wojtek Walczak napisa?(a): > Then go for it :-) You can prepare a patch and ask on python-dev > if the developers are interested. > > I was never hacking the import things on C level before, > but a hint: you have to modify import_from function from > Python/ceval.c > > My quick attempt: > http://www.stud.umk.pl/~wojtekwa/patches/from-import-py2.5.1.patch Uh, and an example: Python 2.5.1 (r251:54863, Aug 14 2008, 00:04:00) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from os import qweasd Traceback (most recent call last): File "", line 1, in ImportError: cannot import name qweasd (/home/gminick/Python-2.5.1/Lib/os.pyc) >>> -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From jparker104 at gmail.com Tue Aug 19 10:37:20 2008 From: jparker104 at gmail.com (jparker104 at gmail.com) Date: Tue, 19 Aug 2008 07:37:20 -0700 (PDT) Subject: How to access an Array and a struct within a struct wrapped by Swig ? References: <6c21cc96-eab4-4823-97c6-c94e1d3da1ec@d1g2000hsg.googlegroups.com> Message-ID: On Aug 17, 11:30?pm, emmanuel.rivo... at gmail.com wrote: > Anish Chapagain, I already know how to use structure, as my example > shown it. > I had trouble only with the nested structures, and it was coz of > missing typedef (ie: Swig need C struct declaration, not C++). > > And I still cannot find how to get my arrays... :-S I was having the same problem with arrays and found a workaround here: http://www.swig.org/papers/PyTutorial97/PyTutorial97.pdf slide 39, "Helper Functions" I got it to work, hope this helps From hubaghdadi at gmail.com Thu Aug 14 05:43:16 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Thu, 14 Aug 2008 02:43:16 -0700 (PDT) Subject: You advice please References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> Message-ID: <2a611c23-16a9-4a9d-8c93-3b24d7b404af@e39g2000hsf.googlegroups.com> On Aug 13, 11:14 am, Alia Khouri wrote: > Hussein B wrote: > > I'm a Java/Java EE developer and I'm playing with Python these days. > > I like the Python language so much and I like its communities and the > > Django framework. > > Sounds familiar... (-: > > > My friends are about to open a Ruby/Rails shop and they are asking me > > to join them. > > In this case, I think you have to make decision that is not technology- > centric but application-centric, and you should also consider closely > the opportunity set and capability set available to you and your > friends. > > > I don't know what, sure I'm not leaving Java, but they are asking me > > to stop learning Python and concentrate on Ruby/Rails. > > I don't think you should stop learning anything that rings your bell.. > I love learning other languages (e.g. Haskell, Lua, Ruby, C#, Java, > boo, etc..) and I will code projects as per the requirements at the > time, but I tend to Python because, like you, I like the language and > the community. > > In _addition_ to your love for Python and Django, why not learn Ruby/ > Rails? It's not a bad framework at all, and Ruby is quite fun to > program in as well...? > > > The sad fact (at least to me), Ruby is getting a lot of attention > > these days. > > Not a sad fact, What's good for ruby is good for python and vice > versa... Friendly competition is always positive and usually good > ideas cross-pollinate across the languages... > > > Why Python isn't getting this attention although is a much more mature > > language and it is used by many big, big names? > > Who says Python is not getting attention? Last time I checked, > Python's popularity was at all time high, and the big guns in the > industry favor (witness Google AppEngine, Microsoft Ironpython > preceding Ironruby, etc..) > > > And do I dare to say it is much more charming? > > That is an aesthetic judgement... (-: > > > What do you think of Ruby/Rails? do they worth learning and working > > with? > > (see above) > > > Any way, I'm not leaving Python and I will try to study it every time > > I get a chance... > > Good for you (-: > > > Thanks. But this critisim looks so serious: http://en.wikipedia.org/wiki/Ruby_programming_language#Criticism From hubaghdadi at gmail.com Wed Aug 20 06:08:59 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Wed, 20 Aug 2008 03:08:59 -0700 (PDT) Subject: Basic importing question Message-ID: Hey, Suppose I have a Python application consists of many modules (lets say it is a Django application). If all the modules files are importing sys module, how many times the sys module will be compiled and executed? Only once (the first time the PVM locates, compiles and executes the sys module)? or once for each module importing sys? Thanks. From b-cousson at ti.com Tue Aug 12 05:29:18 2008 From: b-cousson at ti.com (Cousson, Benoit) Date: Tue, 12 Aug 2008 11:29:18 +0200 Subject: Why nested scope rules do not apply to inner Class? Message-ID: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> Hi, I'd like to be able to use a nested class (C1) from another sibling nested class (C3). This looks very similar to the nested scopes of functions except that it does not work. class A(object): pass class B(object): class C1(object): pass class C2(C1): foo = A class C3(object): foo = C1 The funny thing is that C2 can inherit from C1 but C3 cannot reference C1. B.C1 does not work either, but in that case it makes sense since B is still being defined. Is this a language limitation or something that does not make sense at all? I'm wondering as well if the new nonlocal statement will fix that in py3k? Thanks in advance, Benoit From castironpi at gmail.com Thu Aug 7 17:29:13 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 7 Aug 2008 14:29:13 -0700 (PDT) Subject: Limits of Metaprogramming References: <0c56829a-7ad2-4ff2-b225-7981538e7c7a@j22g2000hsf.googlegroups.com> <07c3d5f8-563c-43bc-8772-5eb60de52c82@8g2000hse.googlegroups.com> <95cebacd-6221-478f-81ae-1040b1711b40@k13g2000hse.googlegroups.com> <5306b80e-81ff-43a5-a472-4f9f05764e4a@e39g2000hsf.googlegroups.com> <4fbbc028-9649-4de4-86e5-af6887b5bc67@z72g2000hsb.googlegroups.com> Message-ID: On Aug 7, 2:01?pm, Wilson wrote: > On Aug 6, 6:04?pm, castironpi wrote: > > > > > On Aug 6, 7:24?am, Wilson wrote: > > > > On Aug 4, 9:23?pm, castironpi wrote: > > > > > On Aug 4, 1:57?pm, Wilson wrote: > > > > > > On Aug 4, 6:49?pm, castironpi wrote: > > > > > > > Two, if all your methods will have uniform signatures and closures, > > > > > > you can store class methods as only their co_code objects: > > > > > > > >>> C.g.im_func.func_code.co_code > > > > > > > 'd\x00\x00S' > > > > > > > And fabricate them dynamically into full live types as needed. > > > > > > Thanks for your comments and advice. This second option intrigues me; > > > > > could you elaborate further, I don't follow you... > > > > > > Thanks Paul > > > > > Depending on the complexity of the functions, a code string could be > > > > all you need to store to determine (redetermine) a function's > > > > behavior. ?For something moderately simple, > > > > > def trans1( self, prev, trans ): > > > > ? ? ? ? if prev== 0 and trans== 'a': > > > > ? ? ? ? ? ? ? ? return 1 > > > > ? ? ? ? if prev== 1 and trans== 'b': > > > > ? ? ? ? ? ? ? ? return 0 > > > > ? ? ? ? return prev > > > > > I found you need to store code.co_nlocals, code.co_code, and > > > > code.co_consts, to distinguish from a blank stub. ?With extra > > > > variables, I needed code.co_names and code.co_varnames too. ?To > > > > recreate a code object completely, you need 12 variables (14 to > > > > include closures), some of which are composite objects and would need > > > > to be pickled to be stored. > > > > Still don't really understand this so I'm going to admit defeat. > > > Thanks all for your advice... Very much appreciated! > > > I was describing an alternative to storing functions in a way that > > wasn't in serial in plain text. ?It was off-topic from state-machine > > transitions. > > > Can you start with this? > > > # state, input, next state > > transitions= [ > > ? ( 0, 'a', 1 ), > > ? ( 1, 'a', 2 ), > > ? ( 2, 'a', 0 ), > > ? ( 0, 'b', 0 ), > > ? ( 1, 'b', 0 ), > > ? ( 2, 'b', 2 ) > > ] > > > What further? > > My problem relates to the states really. I'd like to import a file > containing the state classes into a "state editor" that is just a > class editor really. Then, at *runtime* I'd like to add and remove > methods from this class and change its attributes (__dict__). I'd also > like to be able to add and remove classes from the module. When done, > I was hoping to do introspection upon which classes were associated > with this module and write back the modified class definitions to the > same module. Next time the module is imported, the changes would > remain intact. Unfortunately, inspect.getsource() reads the original > file and does not magically return source from the runtime objects. > > Hope that makes sense! > Paul I see. You want: import states def funa( ): something( ) states.funa= funa And have those changes appear in the actual text of 'states.py'. Are you certain that classes are your best choice for representing states? I am interpreting that you want one class per state, and one method per transition out of that state. How close is that? If you are seeking to generate a .py file from a data structure, why not just edit the data structure directly? If you do need a .py file, can you just regenerate it? From larry.bates at websafe.com` Sat Aug 9 10:41:07 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 09 Aug 2008 09:41:07 -0500 Subject: Large production environments using ZODB/ZOE? In-Reply-To: References: Message-ID: Phillip B Oldham wrote: > I've been reading a lot recently on ZODB/ZOE, but I've not seen any > reference to its use in large-scale production envrironments. > > Are there any real-world examples of ZODB/ZOE in use for a large > system? By large, I'm thinking in terms of both horizontally-scaled > systems and in terms of data storage size. I have been told (by one of the developers) that Viacom uses it for their video streaming website which is quite large. There is also a list of organizations on Zope's webside that is pretty impressive. -Larry From geraint.williams at gmail.com Thu Aug 28 06:20:29 2008 From: geraint.williams at gmail.com (GHZ) Date: Thu, 28 Aug 2008 03:20:29 -0700 (PDT) Subject: filter in for loop Message-ID: <2b50828b-14e4-48a2-884c-220b70216568@d77g2000hsb.googlegroups.com> I would like to say something like: for x in l if : e.g. for filename in os.listdir(DIR) if filename[-4:] == '.xml': instead of having to say: for filename in os.listdir(DIR): if filename[-4:] == '.xml': or for filename in (f for f in os.listdir(DIR) if f[-4] == '.xml'): is there a shortcut I'm missing? From castironpi at gmail.com Sun Aug 17 15:29:30 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 17 Aug 2008 12:29:30 -0700 (PDT) Subject: dynamic attribute syntax Message-ID: Hi all, Thinking of a syntax for 'getattr' and 'setattr' dynamic access. 'obj.prop' has an easy access, but att= 'prop' getattr( obj, att ) is much clumsier, while no less useful, maybe more. What are the changes, pros and cons, involved in something like: obj:att for a dynamic access, and obj.att for static? Snice readability is a factor, I'm open to other markings than ':'. '$' and '?' are available, and I note that a~b, a:b, and, a!b for identifiers 'a' and 'b' are unambiguous. From ironfroggy at gmail.com Wed Aug 13 19:59:30 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Wed, 13 Aug 2008 19:59:30 -0400 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: <200808140141.38909.maric@aristote.info> References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> <200808122240.22517.maric@aristote.info> <76fd5acf0808121415h41cc580bj85d96e648c54ab4b@mail.gmail.com> <200808140141.38909.maric@aristote.info> Message-ID: <76fd5acf0808131659i361d7fbdo595bebf57aeab317@mail.gmail.com> On Wed, Aug 13, 2008 at 7:41 PM, Maric Michaud wrote: > I was not aware of any "nested classes are unsupported" before and didn't > consider nested classes as bad practice till now, even with the pickle > limitation (not every class are intended to be pickled), more you didn't give > any evidence or any pertinent quote of this and at least one of Guido in the > above threads seems contradict you : > http://mail.python.org/pipermail/python-dev/2002-November/029906.html Of course, I don't have to agree with Guido, but I don't really think his comment there counts as some encouragement of the practice. It also isn't an example that actually demonstrates the things people misuse about nesting classes, although its definitely an example that I think could be done much better without them, at all. The use of nested classes to define some hierarchical structure is subject, at best. And, the examples I see aren't even hierarchical. The nesting doesn't seem to gain them anything. As a matter of fact, wouldn't that example be a lot more clear with one class and some "Attribute" properties describing the structure? What rubs me the wrong way about nested classes is that they aren't even "real" classes. That is, they aren't being used to instantiate instances, but just as dummy scopes to hold some attributes. They are abusing classes as property bags. > BTW my concern was not really about nested classes but the asymetry between > function scope and classes scope, there are at least two examples that come > to my mind and for which I don't see good argument to keep the situation as > it is. First is the very odd behavior of genexp, second is the dynamic type > factory, I know it's not a big deal to in each case and can live with this, > but these pieces of code fail unexpectedly while even a experimented python > programmer would have thought they work at first glance, and the explanation > of why they fail to a newcomer is not easy (specially for the first) > > (1) this fail only on the last line while it would have work well with > listcomp and works well in a function definition > class A(object) : > l = range(5) > m = list(a+b for a in l for b in range(5)) > n = list(a+b for a in range(5) for b in l) I can admit that this behavior can be surprising, but it isn't something I really see cropping up as a problem. How often do you see that you need to have any kind of procedural behavior in a class body? In other words, in all but rare cases, the order of the class body lines shouldn't change the resulting class, but this example breaks that expectation. > (2) This won't work as it would with nested functions, you need to build the > new calss directly with type('dynamic', (object,), {"type_": type_}) > > def create_type(type_) : > class dynamic(object) : > type_ = type_ > return dynamic This is simply completely invalid. That code at the beginning of any body will _always_ raise either an UnboundLocalError or a NameError, because you are assigning to the same name you are dereferencing. That line will always be either an error or a no-op, anywhere it appears. It has nothing to do with nesting of any sort. > > -- > _____________ > > Maric Michaud > -- > http://mail.python.org/mailman/listinfo/python-list -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy From mensanator at aol.com Mon Aug 4 16:18:11 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 4 Aug 2008 13:18:11 -0700 (PDT) Subject: What Python looks like References: Message-ID: On Aug 4, 2:06?pm, iu2 wrote: > Hi, > > This is a little bit strange post, but I'm curious... > > I learned Python from its tutorial step by step, and practicing > writing small scripts. > I haven't seen a Python program before knowing Python. > > I'm curious, what did Python code look like to those of you who have > seen a bunch of Python code for the first time before knowing Python? To me, when I started transitioning from perl to Python, Python Python from 2002 -------------------------------------------------------------- import sys import string # Python Collatz tester j = string.atol(sys.argv[1]) i = 2**(6*j-1)-1 print i,"\n" r1 = 0 r2 = 0 count = 0 while i>1: z = divmod(i,2) if z[1]==0: i = z[0] r1 = r1 + 1 if z[1]>0: i = i*3 + 1 r2 = r2 + 1 print "[1]",r1 print "[2]",r2,"\n" -------------------------------------------------------------- looked just like perl, but without the braces (which seemed a lot more important than the $s). Perl from 2002 -------------------------------------------------------------- use Math::BigInt ':constant'; $j = @ARGV[0]; $i = 2**(6*$j-1)-1; print "$i\n"; $r1 = 0; $r2 = 0; while ($i>1) { if ($i =~ /.*?[0,2,4,6,8]$/) { $i = $i/2; $r1++; } else { $i = $i*3 + 1; $r2++; } } print "[1] ",$r1; print " [2] ",$r2,"\n"; -------------------------------------------------------------- > > (I can tell, for example, that seeing perl for the first time looked > like C with many $$$, I wouldn't say that, the $s are minor, big thing is the declarations and pointers. C from 2005 (not complete program) -------------------------------------------------------------- long collatz (mpz_ptr r) { mpz_t result, twee, twoo, cee; mpz_init (result); mpz_init_set_ui (cee, 1); mpz_init_set_ui (twee, 3); mpz_init_set_ui (twoo, 2); long rule1 = 0; long rule2 = 0; long f; while (mpz_cmp (r, cee) > 0) { f = mpz_scan1 (r, 0); if (f>0) /* even */ { mpz_tdiv_q_2exp (result, r, f); rule1 = rule1 + f; } else /* odd */ { mpz_set (result, cee); mpz_addmul (result, r, twee); rule2++; } mpz_swap (r, result); } printf ("\nRule1: %8d Rule2: %8d\n\n", rule1, rule2); return rule1 + rule2; } -------------------------------------------------------------- > I could see "if" and "for" and "while" but they > were meaningless. Maybe you looked at a crappy example. > Or Lisp for the first time looked like many words, > no operators, Aren't some of the words operators? I never used used Lisp, but I did dabble in Scheme and have no trouble identifying the operators (although not the overall program). Scheme from 2004 -------------------------------------------------------------- (define n 1) (define collatz (lambda (n) (if (even? n) (/ n 2) (+ 1 (* n 3)) ))) (define sequence (lambda (n) (do ((count 0 (+ count 1))) ((= n 1) (display "stopping: ") (display count)) (set! n (collatz n)) (display n) (display " ") ))) -------------------------------------------------------------- > how could that make a program???) You have to think differently with functional languages. The functional snobs say you'll never "get" it once your mind has been poisoned by imperative languages. > > Thanks From Edwin.Madari at VerizonWireless.com Sat Aug 9 11:22:48 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Sat, 9 Aug 2008 11:22:48 -0400 Subject: Extract string from log file In-Reply-To: Message-ID: <20080809152259.22E341E4002@bag.python.org> from each line separate out url and request parts. split the request into key-value pairs, use urllib to unquote key-value pairs......as show below... import urllib line = "GET /stat.gif?stat=v&c=F-Secure&v=1.1%20Build%2014231&s=av%7BNorton%20360%20%28Symantec%20Corporation%29+69%3B%7Dsw%7BNorton%20360%20%28Symantec%20Corporation%29+69%3B%7Dfw%7BNorton%20360%20%28Symantec%20Corporation%29+5%3B%7Dv%7BMicrosoft%20Windows%20XP+insecure%3BMicrosoft%20Windows%20XP%20Professional+f%3B26027%3B26447%3B26003%3B22452%3B%7D&r=0.9496 HTTP/1.1" words = line.split() for word in words: if word.find('?') >= 0: req = word[word.find('?') + 1:] kwds = req.split('&') for kv in kwds: print urllib.unquote(kv) stat=v c=F-Secure v=1.1 Build 14231 s=av{Norton 360 (Symantec Corporation)+69;}sw{Norton 360 (Symantec Corporation)+69;}fw{Norton 360 (Symantec Corporation)+5;}v{Microsoft Windows XP+insecure;Microsoft Windows XP Professional+f;26027;26447;26003;22452;} r=0.9496 good luck Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of josephtys86 at googlemail.com Sent: Saturday, August 09, 2008 10:48 AM To: python-list at python.org Subject: Extract string from log file 203.114.10.66 - - [01/Aug/2008:05:41:21 +0300] "GET /stat.gif? stat=v&c=F-Secure&v=1.1%20Build%2014231&s=av%7BNorton %20360%20%28Symantec%20Corporation%29+69%3B%7Dsw%7BNorton %20360%20%28Symantec%20Corporation%29+69%3B%7Dfw%7BNorton %20360%20%28Symantec%20Corporation%29+5%3B%7Dv%7BMicrosoft%20Windows %20XP+insecure%3BMicrosoft%20Windows%20XP%20Professional+f %3B26027%3B26447%3B26003%3B22452%3B%7D&r=0.9496 HTTP/1.1" 200 43 "http://dfstage1.f-secure.com/fshc/1.1/release/devbw/1.1.14231/ card.html" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)" does anyone know how can i extract certain string from this log file using regular expression in python or using XML. can teach me. -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From jwkenne at attglobal.net Sat Aug 23 21:22:05 2008 From: jwkenne at attglobal.net (John W Kennedy) Date: Sat, 23 Aug 2008 21:22:05 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> <48af8cc4$0$20919$607ed4bc@cv.net> Message-ID: <48b0b81f$0$7353$607ed4bc@cv.net> Martin Gregorie wrote: > On Sat, 23 Aug 2008 00:06:28 -0400, John W Kennedy wrote: > >> Martin Gregorie wrote: >>> Not necessarily. An awful lot of CPU cycles were used before microcode >>> was introduced. Mainframes and minis designed before about 1970 didn't >>> use or need it >> No, most S/360s used microcode. > > I never used an S/360. > > I thought microcode came into the IBM world with S/370 and Future Series > (which later reappeared as the AS/400, which I did use). Didn't the S/370 > load its microcode off an 8 inch floppy? Some did, but not all. The 370/145 was the first, and made a big splash thereby. As to the 360s: 20 (Incompatible subset) I don't know 22 (Recycled end-of-life 30) CROS 25 Loaded from punched cards 30 CROS 40 TROS 44 (Subset) None 50 CROS 60, 62, 65 ROS 64, 66, 67 ROS 70, 75 None 85 I don't know 91, 95 I don't know -- probably none 195 I don't know CROS used plastic-coated foil punched cards as the dielectrics of 960 capacitors each. TROS used little transformer coils that might or might not be severed. ROS means it was there, but I don't know the technology. -- John W. Kennedy "Those in the seat of power oft forget their failings and seek only the obeisance of others! Thus is bad government born! Hold in your heart that you and the people are one, human beings all, and good government shall arise of its own accord! Such is the path of virtue!" -- Kazuo Koike. "Lone Wolf and Cub: Thirteen Strings" (tr. Dana Lewis) From metaperl at gmail.com Thu Aug 28 15:27:41 2008 From: metaperl at gmail.com (Terrence Brannon) Date: Thu, 28 Aug 2008 12:27:41 -0700 (PDT) Subject: re.compile versus r'' References: <0bf4b8de-e11e-451c-8d18-58c1a4138375@e53g2000hsa.googlegroups.com> Message-ID: <69661017-f461-4ab5-a798-268e9180c2f6@c58g2000hsc.googlegroups.com> Oh my god, how embarrassing. the r'' notation is to create raw string I thought it was some form of blessing a string into a regular expression class. From kem1723 at yahoo.com Fri Aug 29 13:37:21 2008 From: kem1723 at yahoo.com (Kevin McKinley) Date: Fri, 29 Aug 2008 10:37:21 -0700 (PDT) Subject: Memory Leek, critique me. Thanks!!! Message-ID: <333736.18680.qm@web83911.mail.sp1.yahoo.com> # I posted a few days ago about a memory leak that I think i'm having with my first Tkinter program. # I've had trouble pinpointing what is wrong so i thought i would submit the code and see if anyone would # like to critique it. # I have one more problem that i can't figure out either. There are a bunch of Entry widgets that require number values. # My problem is if someone inputs a letter or space the program will have error that makes part of the # Program nonfunctional. # Description Of The Program: I made this program to help me with common calculations that i do on a day-to-day # basis. I'm a outside sales rep and this program figures out Gross profit and price increase. Oh, and where it # said to enter COG that stands for Cost of Goods. I know it doesn't really matter but figure i would let you guys # in on the use of the program. # Thank you, # Kevin McKinley from Tkinter import * class MyApp: def __tini__(self, parent): self.myParent = parent self.myFunctionContainer = Frame(parent) self.myFunctionContainer.grid(row=0, column=0) self.COG1 = DoubleVar() self.COG2 = DoubleVar() self.COG3 = DoubleVar() self.COG4 = DoubleVar() self.GP = DoubleVar() self.increase = DoubleVar() self.markup = DoubleVar() self.gpRange(1) # This Function is for the Markup Tab for a range of GP% def gpRange(self, event): self.clearScreen() self.gpRangeTab = Button(self.myFunctionContainer, width=14, relief=FLAT, text="Multi-Markup") self.gpRangeTab.bind("", self.gpRange) self.gpRangeTab.grid(row=0, column=0) self.gpExactTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Single Markup") self.gpExactTab.bind("", self.gpExact) self.gpExactTab.grid(row=0, column=1) self.priceIncreaseTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Product Increase") self.priceIncreaseTab.bind("", self.priceIncrease) self.priceIncreaseTab.grid(row=0, column=2) self.gpFinderTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Calculate GP") self.gpFinderTab.bind("", self.gpFinder) self.gpFinderTab.grid(row=0, column=3) self.markup1(1) self.myContainer2 = Frame(self.myFunctionContainer, borderwidth=2, relief=GROOVE) self.myContainer2.grid(padx=0, pady=2, row=4, column=0, columnspan=4, sticky=W+E) self.title1 = Label(self.myFunctionContainer, font="bold", relief=GROOVE, text="Multi-Markup Calculator") self.title1.grid(padx=0, pady=2, row=1, column=0, columnspan=4, sticky=W+E) self.entry1 = Entry(self.myFunctionContainer, textvariable=self.COG1) self.entry1.select_range(0, END) self.entry1.bind("", self.markup1) self.entry1.focus_force() self.entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.entryTitle = Label(self.myFunctionContainer, text="Enter COG:") self.entryTitle.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.title2 = Label(self.myContainer2, text="Gross Profit % ") self.title2.grid(padx=2, pady=2, row=1, column=1, sticky=W) self.title3 = Label(self.myContainer2, text=" Markup Price") self.title3.grid(padx=2, pady=2, row=1, column=2, sticky=E) self.button1 = Button(self.myFunctionContainer, text="Calculate") self.button1.bind("", self.markup1) self.button1.grid(padx=2, pady=2, row=3, column=1, columnspan=2, sticky=W+E) def gpExact(self, event): self.clearScreen() self.gpRangeTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Multi-Markup") self.gpRangeTab.bind("", self.gpRange) self.gpRangeTab.grid(row=0, column=0) self.gpExactTab = Button(self.myFunctionContainer, width=14, relief=FLAT, text="Single Markup") self.gpExactTab.bind("", self.gpExact) self.gpExactTab.grid(row=0, column=1) self.priceIncreaseTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Product Increase") self.priceIncreaseTab.bind("", self.priceIncrease) self.priceIncreaseTab.grid(row=0, column=2) self.gpFinderTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Calculate GP") self.gpFinderTab.bind("", self.gpFinder) self.gpFinderTab.grid(row=0, column=3) self.markup2(1) self.title1 = Label(self.myFunctionContainer, font="bold", relief=GROOVE, text="Single Markup Calculator") self.title1.grid(padx=0, pady=2, row=1, column=0, columnspan=4, sticky=W+E) self.entry1 = Entry(self.myFunctionContainer, textvariable=self.COG2) self.entry1.select_range(0, END) self.entry1.focus_force() self.entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.entry2 = Entry(self.myFunctionContainer, textvariable=self.GP) self.entry2.select_range(0, END) self.entry2.bind("",self.markup2) self.entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) self.entryTitle = Label(self.myFunctionContainer, text="Enter COG:") self.entryTitle.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.entryTitle2 = Label(self.myFunctionContainer, text="Enter GP%:") self.entryTitle2.grid(padx=2, pady=2, row=3, column=1, sticky=E) self.button = Button(self.myFunctionContainer, text="Calculate") self.button.bind("", self.markup2) self.button.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) def priceIncrease(self, event): self.clearScreen() self.gpRangeTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Multi-Markup") self.gpRangeTab.bind("", self.gpRange) self.gpRangeTab.grid(row=0, column=0) self.gpExactTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Single Markup") self.gpExactTab.bind("", self.gpExact) self.gpExactTab.grid(row=0, column=1) self.priceIncreaseTab = Button(self.myFunctionContainer, width=14, relief=FLAT, text="Product Increase") self.priceIncreaseTab.bind("", self.priceIncrease) self.priceIncreaseTab.grid(row=0, column=2) self.gpFinderTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Calculate GP") self.gpFinderTab.bind("", self.gpFinder) self.gpFinderTab.grid(row=0, column=3) self.increase1(1) self.title1 = Label(self.myFunctionContainer, font="bold", relief=GROOVE, text="Product Price Increase") self.title1.grid(padx=0, pady=2, row=1, column=0, columnspan=4, sticky=W+E) self.entry1 = Entry(self.myFunctionContainer, textvariable=self.COG3) self.entry1.select_range(0, END) self.entry1.focus_force() self.entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.entry2 = Entry(self.myFunctionContainer, textvariable=self.increase) self.entry2.select_range(0, END) self.entry2.bind("", self.increase1) self.entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) self.entryTitle = Label(self.myFunctionContainer, text="Enter COG:") self.entryTitle.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.entryTitle2 = Label(self.myFunctionContainer, text="Enter Increase %:") self.entryTitle2.grid(padx=2, pady=2, row=3, column=1, sticky=E) self.button = Button(self.myFunctionContainer, text="Calculate") self.button.bind("", self.increase1) self.button.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) def gpFinder(self, event): self.clearScreen() self.gpRangeTab = Button(self.myFunctionContainer, width=14, bg="dark grey",relief=SUNKEN, text="Multi-Markup") self.gpRangeTab.bind("", self.gpRange) self.gpRangeTab.grid(row=0, column=0) self.gpExactTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Single Markup") self.gpExactTab.bind("", self.gpExact) self.gpExactTab.grid(row=0, column=1) self.priceIncreaseTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Product Increase") self.priceIncreaseTab.bind("", self.priceIncrease) self.priceIncreaseTab.grid(row=0, column=2) self.gpFinderTab = Button(self.myFunctionContainer, width=14, relief=FLAT, text="Calculate GP") self.gpFinderTab.bind("", self.gpFinder) self.gpFinderTab.grid(row=0, column=3) self.gpCalc1(1) self.title1 = Label(self.myFunctionContainer, font="bold", relief=GROOVE, text="GP Finder") self.title1.grid(padx=0, pady=2, row=1, column=0, columnspan=4, sticky=W+E) self.entry1 = Entry(self.myFunctionContainer, textvariable=self.COG4) self.entry1.select_range(0, END) self.entry1.focus_force() self.entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.entry2 = Entry(self.myFunctionContainer, textvariable=self.markup) self.entry2.select_range(0, END) self.entry2.bind("", self.gpCalc1) self.entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) self.entryTitle = Label(self.myFunctionContainer, text="Enter COG:") self.entryTitle.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.entryTitle2 = Label(self.myFunctionContainer, text="Enter Markup $:") self.entryTitle2.grid(padx=2, pady=2, row=3, column=1, sticky=E) self.button = Button(self.myFunctionContainer, text="Calculate") self.button.bind("", self.gpCalc1) self.button.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) def markup1(self, event): a = [5,10,15,17,18,19,20,21,22,23,24,25,26,27,28,29,30,32,35,40,45,50,55] colors = ['#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF', '#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF', '#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF'] b = 1 row = 4 while b < len(a): gp = 1-((a[b-1]/100.0)) color = colors[b-1] row = row + 1 markup = round((self.COG1.get()/gp),2) self.gp1 = Label(self.myFunctionContainer, bg=color, width=6, relief=RIDGE, text=(((1-gp)*100),"%")) self.gp1.grid(padx=2, pady=1, row=row ,column=1) self.price1 = Label(self.myFunctionContainer, bg=color, relief=RIDGE, width=10, text=("$",markup)) self.price1.grid(padx=2, pady=1, row=row ,column=2) b = b + 1 def markup2(self, event): GP = 1 - (round((self.GP.get()/100),2)) self.price1 = Label(self.myFunctionContainer, relief=GROOVE, bg="white", width=10, font="bold", text=("$",round((self.COG2.get()/GP),2))) self.price1.grid(pady=1, row=5 ,column=1, columnspan=2) def increase1(self, event): increase = 1+(self.increase.get()/100) self.price1 = Label(self.myFunctionContainer, relief=GROOVE, bg="white", width=10, font="bold", text=("$",round((self.COG3.get()*increase),2))) self.price1.grid(pady=1, row=5 ,column=1, columnspan=2) def gpCalc1(self, event): COG4 = self.COG4.get() markup = self.markup.get() if COG4==0.0 or markup==0.0: self.price1 = Label(self.myFunctionContainer, relief=GROOVE, bg="white", width=10, font="bold", text="") self.price1.grid(pady=1, row=5 ,column=1, columnspan=2) else: GP = 100*(1-(self.COG4.get()/self.markup.get())) self.price1 = Label(self.myFunctionContainer, relief=GROOVE, bg="white", width=10, font="bold", text=(round(GP,2),"%")) self.price1.grid(pady=1, row=5 ,column=1, columnspan=2) def clearScreen(self): self.clear = Label(self.myFunctionContainer) self.clear.grid(row=1, column=0, rowspan=30, columnspan=6, sticky=N+E+S+W) return root = Tk() myapp = MyApp(root) root.mainloop() From bedouglas at earthlink.net Tue Aug 26 11:28:10 2008 From: bedouglas at earthlink.net (bruce) Date: Tue, 26 Aug 2008 08:28:10 -0700 Subject: libxml2dom - parsing maligned html Message-ID: <121101c90790$5966bc80$0301a8c0@tmesa.com> Hi... I'm using quick test with libxml2dom =============== import libxml2dom aa=libxml2dom.parseString(foo) ff=libxml2dom.toString(aa) print ff =============== ---------------------------------- when i start, foo is: . . . ------------------------------- when i print ff it's: ------------------------------- so it's as if the parseString only reads the initial "html" tree. i've reviewed as much as i can find regarding libxml2dom to try to figure out how i can get it to read/parse/handle both html trees/nodes. i know, the html is maligned/screwed-up, but i can't seem to find any app (tidy/beautifulsoup) that can "know" which one of the html trees to throw out/remove!! technically, both html trees are valid, it's just that they both shouldn't be in the file!!! thoughts/comments appreciated thanks From gagsl-py2 at yahoo.com.ar Wed Aug 27 00:25:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 27 Aug 2008 01:25:49 -0300 Subject: Setting my Locale References: <9611.72753382034$1219748098@news.gmane.org> Message-ID: En Tue, 26 Aug 2008 07:52:21 -0300, Robert Rawlins escribi?: > I'm running python 2.5 on a Debian based system and I'm looking for your > advice on how to set the locale for my application. I've read through the > locale module documentation http://docs.python.org/lib/module-locale.html > and tried a couple of the examples but can't seem to get it working. > > > For instance, when I attempt to run the following code: > > > import locale > > locale.setlocale(locale.LC_ALL, 'de_DE') > > > I get an exception raised by the application which says: > > > Traceback (most recent call last): > > File "locale_test.py", line 2, in > > locale.setlocale(locale.LC_ALL, 'de_DE') > > File "/usr/lib/python2.5/locale.py", line 478, in setlocale > > return _setlocale(category, locale) > > locale.Error: unsupported locale setting > > > My questions are; what would be causing this error? Do I need any > additional > packages installed on the system for this locale support to work > properly? Probably you don't have support for 'de_DE' locale. Try using locale.setlocale(locale.LC_ALL, '') and see what you get in response. > How can I get a list of available locales? I'd like to know how to retrieve that too... -- Gabriel Genellina From fredrik at pythonware.com Sat Aug 30 07:15:26 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 30 Aug 2008 13:15:26 +0200 Subject: Which is faster? In-Reply-To: References: Message-ID: cnb wrote: > how does doing something twice not change complexity? yes it maybe > belongs to the same complexity-class but is still twice as slow no? doing two things quickly can still be faster than doing one thing slowly. From larry.bates at websafe.com` Thu Aug 14 12:18:06 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 14 Aug 2008 11:18:06 -0500 Subject: ActiveState Python v2.5 doesn't come with Tkinter or Tk installed. In-Reply-To: References: Message-ID: <5IWdnVWSR6FWxznVnZ2dnUVZ_uqdnZ2d@comcast.com> Dudeja, Rajat wrote: > Hi, > > So, now I've finally started using Eclipse and PyDev as an IDE for my > GUI Application. I just wrote some sample programs as an hands on. > > Now I would like to take up Tkinter. I'm using Active State Python > version 2.5 and found that there is not Tkinter and Tk module in it. > > To use Tkinter do I actually require Tk installed on my machine? Please > suggest and where can I find both these modules? > > Also, please direct me to a good and short document on using Tkinter or > Tk in Python. > > Cheers, > Rajat > > > > Notice: This e-mail is intended solely for use of the individual or entity to which it is addressed and may contain information that is proprietary, privileged, company confidential and/or exempt from disclosure under applicable law. If the reader is not the intended recipient or agent responsible for delivering the message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If this communication has been transmitted from a U.S. location it may also contain data subject to the International Traffic in Arms Regulations or U.S. Export Administration Regulations and cannot be disseminated, distributed or copied to foreign nationals, residing in the U.S. or abroad, without the prior approval of the U.S. Department of State or appropriate export licensing authority. If you have received this communication in error, please notify the sender by reply e-mail or collect telephone call and delete or destroy all copies of this e-mail message, any physical copies made of this e-mail message and/or any file attachment(s). > > NOTE: Please begin your posts with what platform (Linux/Mac/Windows) you are running on so we can answer your questions better. From ActiveState's webpage: All platforms * Tcl/Tk 8.4.14 and Tix 8.4.2 upgrades. It is certainly on my machine which is Windows ActiveState install. You better check again. If you are on Windows, you can use py2exe to package up your program and you won't have to have Python/Tk installation. First hit on Google is: http://wiki.python.org/moin/TkInter -Larry -Larry From michele.simionato at gmail.com Sat Aug 16 10:11:16 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 16 Aug 2008 07:11:16 -0700 (PDT) Subject: Dynamically defined functions via exec in imported module References: <036d8731-5984-4c23-a15d-efe7e01b5d07@x35g2000hsb.googlegroups.com> <979a8a16-0930-4838-9625-0a03784e590b@w7g2000hsa.googlegroups.com> Message-ID: On Aug 16, 4:02?pm, Maric Michaud wrote: > I'd say that everywhere exec/eval are used in a application/function/lib that > doesn't mean to interpret arbitrary and user provided python code, it is a > bad usage Problem is, there are things you cannot do without exec/eval: for instance look at the implementation of my own decorator module, which uses eval to guarantee a good signature for the decorated function. Probably it could be done without exec, with bytecode hacks, but I regard fiddling with bytecodes as something worse than exec itself. I am not sure if in Python 3.0 the signature object is powerful enough to do the job, I never had to time to check how it works. Michele Simionato From cito at online.de Sun Aug 10 07:18:58 2008 From: cito at online.de (Christoph Zwerschke) Date: Sun, 10 Aug 2008 13:18:58 +0200 Subject: Missing exceptions in PEP 3107 In-Reply-To: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> References: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> Message-ID: Matimus schrieb: >> The expr in that "raises" clause should be a list of Exceptions. > > You are clearly confusing the annotation feature with a possible > application of the annotation feature. Annotation could be used for > many different applications besides type safety. Sorry, I wanted to say "*could* be a list of Exceptions". Though this is the most obvious application. In the end, the annotations need to be given a semantical meaning anyway. > Annotation simply creates a dictionary. The name `return` was chosen > for the return value because it _is_ a keyword and therefore could not > conflict with the name of any of the parameters. Using "raises" would > mean that we would have to introduce the name "raises" as a new > keyword. It would be better just to use they existing keyword "raise". Yes, it later also occured to me that it ought to be an existing keyword, i.e. "raise" (or maybe "except"). That's porbably the reason why it is "throw" in C++, and not "throws". > With all of that being said, a package or application that uses > annotation could simply use the data-structure associated with > "return" to also contain exception information. That might not seem > intuitive, but keep in mind that the value associated with "return" in > the associations dictionary is going to be a special case anyway. > > def foo(a: "a info", b: "b info") -> "return info", "exception info": > return "hello world" That would be possible. But I still think it makes sense to separate them, like so: def foo(a: "a info", b: "b info") -> "ret info" raise "exc info": return "hello world" And then the annotation dictionary would contain another key "raise" containing the exc info. This cannot conflict with the name of any other parameter either. Maybe the following syntax would be even more intuitive: def foo(a: "a info", b: "b info") return "ret info" raise "exc info": return "hello world" I don't know how determined the "->" syntax is already. -- Christoph From arne at vajhoej.dk Tue Aug 12 20:40:07 2008 From: arne at vajhoej.dk (=?ISO-8859-1?Q?Arne_Vajh=F8j?=) Date: Tue, 12 Aug 2008 20:40:07 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <48617847$0$5021$607ed4bc@cv.net> <486ae06b$0$5011$607ed4bc@cv.net> <4883bc90$0$7327$607ed4bc@cv.net> Message-ID: <48a22d60$0$90273$14726298@news.sunsite.dk> Robert Maas, http://tinyurl.com/uh3t wrote: > John W Kennedy wrote: > JWK> Into the 60s, indeed, there were still machines being made > JWK> that had no instruction comparable to the mainframe BASx/BALx > JWK> family, or to Intel's CALL. You had to do a subprogram call by > JWK> first overwriting the last instruction of what you were > JWK> calling with a branch instruction that would return back to > JWK> you. > > That's not true, that you needed to do that, that there was no > other way available. The subroutine linkage I invented for S.P.S. > (Symbolic Programming System, i.e. IBM 1620 assembly language) was > to reserve a 5-digit space immediately before the subroutine entry > point for storing the return address. So the caller needed to know > only one address, the entry point, and do both store-return-address > and jump relative to that address, rather than needing to know both > the entry point and the last-instruction-JUMP-needs-patch address > as independent items of information. CDC Cyber did something very similar. Not very recursion friendly. Arne From mblstreet at gmail.com Sat Aug 9 04:59:28 2008 From: mblstreet at gmail.com (Majestic_Mbl) Date: Sat, 9 Aug 2008 01:59:28 -0700 (PDT) Subject: Free Mobile Softwares Message-ID: <9ea26898-3f63-45e5-97d3-fe77dfcd1879@x35g2000hsb.googlegroups.com> Http://www.mobilestreet.net Mobilestreet Download Free Mobile Stuff From Mobile Street. Largest Collection of Mobile Stuff On Internet , Themes , Games , Islamic Section , Ringtones, Funny Movies and Naat Much More Avaliable, Nokia , Sony Ericsson, Motorola, Smart Phones, Pocket Pc and Much More..... http://www.mobilestreet.net From circularfunc at yahoo.se Wed Aug 27 19:50:03 2008 From: circularfunc at yahoo.se (cnb) Date: Wed, 27 Aug 2008 16:50:03 -0700 (PDT) Subject: How come Python software, tools and libraries is so good? A hug to Gvr and the Python community! Message-ID: I have been testing different tools for cvs, math etc and I am constantly amazed how many great tools and libraries there are for Python. SAGE, Mercurial as 2 outstanding tools and there a re excellent libraries fro anything you want, natural language processing, any kind of parsing, math, simulation, neural networks, genetic algorithms, data visualization etc. And everythign just works, download and go! Is this a consequense of the language being so intuitive and easy to use and superwell documented? This then affects how people write code and what programmers are attracted in the first place. Being a bit of a fanboy here but I have never experinced such a satisfaction with a language before. Sure it can get better(I won't take that up in this thread do) but in general I want to give a big hug to GvR and the Python community. From steve at REMOVE-THIS-cybersource.com.au Sun Aug 3 19:02:47 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 03 Aug 2008 23:02:47 GMT Subject: Decimals not equalling themselves (e.g. 0.2 = 0.2000000001) References: Message-ID: <00a6346b$0$20302$c3e8da3@news.astraweb.com> On Sun, 03 Aug 2008 17:30:29 -0500, Larry Bates wrote: >> As you can see, the last two decimals are very slightly inaccurate. >> However, it appears that when n in 1/n is a power of two, the decimal >> does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2 >> and not 0.20000000000000001? >> >> This discrepancy is very minor, but it makes the whole n-th root >> calculator inaccurate. :\ > > What are they teaching in computer science classes these days? I don't know about these days, but 20-odd years ago there was no discussion of floating point accuracy in the Comp Sci classes I did at Melbourne Uni. I did a class in computational mathematics, run by the maths department, and it discussed a lot of issues about accuracy in float calculations. However, if they mentioned anything about e.g. 0.2 not being exactly representable in binary, I slept through it. Maybe that's why I failed that class. *wry grin* -- Steven From sjmachin at lexicon.net Wed Aug 20 18:32:23 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 20 Aug 2008 15:32:23 -0700 (PDT) Subject: Negative integers References: Message-ID: <1e54ed85-7f63-4749-a711-3c571e851f83@r15g2000prh.googlegroups.com> On Aug 21, 7:46 am, Fredrik Lundh wrote: > johnewing wrote: > > I am trying to figure out how to test if two numbers are of the same > > sign (both positive or both negative). I have tried > > > abs(x) / x == abs(y) / y > > > but that fails when one of the numbers is 0. I'm sure that there is > > an easy way to do this. Any suggestions? > > (a < 0) == (b < 0) > That supposes that the OP understands "sign" to mean "the sign bit". Another possibility is the sgn/sign/signum function (http:// en.wikipedia.org/wiki/Sign_function). In that case the answer would be cmp(a, 0) == cmp(b, 0) -- with one big caveat: Although cmp appears to return only -1, 0, or +1, it is documented to return "negative", "zero" or "positive". >>> help(cmp) Help on built-in function cmp in module __builtin__: cmp(...) cmp(x, y) -> integer Return negative if xy. >>> cmp(10, 90) -1 Perhaps safer and better documentation to define your own sign and samesign: sign = lambda x: x < 0 or sign = lambda x: -1 if x < 0 else 0 if x == 0 else 1 samesign = lambda a, b: sign(a) == sign(b) Cheers, John From notvalid2 at sbcglobal.net Fri Aug 22 21:01:04 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Fri, 22 Aug 2008 18:01:04 -0700 Subject: Filling in Degrees in a Circle (Astronomy) In-Reply-To: <511395ff-e823-4d59-ad57-cd6b1ad01d8a@w7g2000hsa.googlegroups.com> References: <511395ff-e823-4d59-ad57-cd6b1ad01d8a@w7g2000hsa.googlegroups.com> Message-ID: Mensanator wrote: > On Aug 22, 6:12 pm, "W. eWatson" wrote: >> The other night I surveyed a site for astronomical use by measuring the >> altitude (0-90 degrees above the horizon) and az (azimuth, 0 degrees north >> clockwise around the site to 360 degrees, almost north again) of obstacles, >> trees. My purpose was to feed this profile of obstacles (trees) to an >> astronomy program that would then account for not sighting objects below the >> trees. >> >> When I got around to entering them into the program by a file, I found it >> required the alt at 360 azimuth points in order from 0 to 360 (same as 0). >> Instead I have about 25 points, and expected the program to be able to do >> simple linear interpolation between those. >> >> Is there some simple operational device in Python that would allow me to >> create an array (vector) of 360 points from my data by interpolating between >> azimuth points when necessary? All my data I rounded to the nearest integer. >> Maybe there's an interpolation operator? >> >> As an example, supposed I had made 3 observations: (0,0) (180,45) and >> (360,0). I would want some thing like (note the slope of the line from 0 to >> 179 is 45/180 or 0.25): >> alt: 0, 0.25, 0.50, 0.75, ... 44.75, 45.0 >> az : 0, 1, 2, 3, 180 >> >> Of course, I don't need the az. > > On Aug 22, 6:12 pm, "W. eWatson" wrote: >> The other night I surveyed a site for astronomical use by measuring the >> altitude (0-90 degrees above the horizon) and az (azimuth, 0 degrees north >> clockwise around the site to 360 degrees, almost north again) of obstacles, >> trees. My purpose was to feed this profile of obstacles (trees) to an >> astronomy program that would then account for not sighting objects below the >> trees. >> >> When I got around to entering them into the program by a file, I found it >> required the alt at 360 azimuth points in order from 0 to 360 (same as 0). >> Instead I have about 25 points, and expected the program to be able to do >> simple linear interpolation between those. >> >> Is there some simple operational device in Python that would allow me to >> create an array (vector) of 360 points from my data by interpolating between >> azimuth points when necessary? All my data I rounded to the nearest integer. >> Maybe there's an interpolation operator? >> >> As an example, supposed I had made 3 observations: (0,0) (180,45) and >> (360,0). I would want some thing like (note the slope of the line from 0 to >> 179 is 45/180 or 0.25): >> alt: 0, 0.25, 0.50, 0.75, ... 44.75, 45.0 >> az : 0, 1, 2, 3, 180 >> >> Of course, I don't need the az. > >>>> for az in xrange(181): > print (az,az*0.25), > > (0, 0.0) (1, 0.25) (2, 0.5) (3, 0.75) > (4, 1.0) (5, 1.25) (6, 1.5) (7, 1.75) > (8, 2.0) (9, 2.25) (10, 2.5) (11, 2.75) > (12, 3.0) (13, 3.25) (14, 3.5) (15, 3.75) > (16, 4.0) (17, 4.25) (18, 4.5) (19, 4.75) > (20, 5.0) (21, 5.25) (22, 5.5) (23, 5.75) > etc. Yes, that works, but that was only a simple illustration. My data looks in fact looks like this (only a few values given: Az Alt 0 18 18 18 27 16 34 20 48 20 ... 268 28 290 32 ... So the python software should generate 0 18 1 18 2 18 3 18 ... the trees are all about 18 degrees high 18 18 19 17.9 we have a slight slope. I'm using values that might be close 20 27.75 21 ... 27 16 28 16.4 now the trees are starting to get a little higher 29 16.9 ... 359 18 (most likely. I didn't have the patience to make a measure at 359) That should pretty well illustrate it. In actuality, as I swept around the circle, the tree line becomes much more abrupt than those first few data points. The tallest tree is at 36 degrees and is among some other equally tall trees. > > But are you saying if you have two readings of tree tops > > * > * > x * > x * > * x * > * x * > ____*_x_*______ > > > And you linearly interpret between them exactly. I put a value there -- x > > / > /* > / * > / * > / * > /* * > * * > ____*___*______ > > that the area below the dashed line is assumed to be hidden? Yes, the telescope software will see that it cannot move the telescope into that area. Surprisingly, they use interpolation. For example, suppose the two trees in your illustration are at an az of 100 and 101, and the two altitudes are 3 and 7. Suppose the telescope wants to go below the line into 100.622 az and an alt of 2.42. The software will say no you don't. > > That wouldn't necessarily be true, as the tree profile could > dip below the line. > > / > /* > / * > / ** > / *** > /* **** > ** **** > ___***_****____ > > Of course, if you take enough points, the open areas may be small > enough not to be practical to worry about. From rweir at ertius.org Wed Aug 13 02:07:57 2008 From: rweir at ertius.org (Rob Weir) Date: Wed, 13 Aug 2008 16:07:57 +1000 Subject: Downloading and Installing gasp References: Message-ID: <87k5eltpky.fsf@hypercube.ertius.org> On 13 Aug 2008, Cyprian Kumwaka wrote: > I am a beginner in Python. Please tell me how to go about in > downloading and installing the module gasp.I am using Python 2.5.2. What OS are you using? Do you have PyGame installed already? -- -rob From dlenski at gmail.com Mon Aug 18 11:28:53 2008 From: dlenski at gmail.com (Dan Lenski) Date: Mon, 18 Aug 2008 08:28:53 -0700 (PDT) Subject: Factory for Struct-like classes References: Message-ID: On Aug 13, 1:30?pm, Christian Heimes wrote: > Trynamedtuplehttp://code.activestate.com/recipes/500261/ > > Anamedtupleimplementation is part of Python 2.6 and 3.0. For older > versions of Python use the recipe from activestate. > > Christian This named tuple recipe is pretty cool... I think there may be a slight bug in the Python docs, though. The ActiveState page explains that it avoids the overhead of a per-instance __dict__ by using the __slots__ variable. However, according to the most-recent Python docs, __slots__ does *NOT* work with subclasses of list, str, or tuple. From http://docs.python.org/ref/slots.html#l2h-222: # __slots__ do not work for classes derived from ``variable-length'' built-in types such as long, str and tuple. On the other hand, nametuple does appear to work as advertised. >>> Person=namedtuple.namedtuple('Person', ('name', 'age', 'height')) >>> p=Person('Bob', 24, 1.86) >>> p.name 'Bob' >>> p.shoe_size AttributeError: 'Person' object has no attribute 'shoe_size' >>> p.__dict__ AttributeError: 'Person' object has no attribute '__dict__' So is there a bug in the Python docs? Does __slots__ in fact work with subclasses of tuple? Dan From __peter__ at web.de Mon Aug 18 12:27:53 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 18 Aug 2008 18:27:53 +0200 Subject: Weird expression result References: <83803185-725e-45bb-b2fe-1add2868bd34@c58g2000hsc.googlegroups.com> Message-ID: Dan Lenski wrote: > On Mon, 18 Aug 2008 18:04:32 +0200, Peter Otten wrote: >> This works just like a < b < c: >> >>>>> 3 in [3] and [3] == True >> False > Interesting. I agree with the OP that it is confusing! > > Does this expansion really get invoked every time there is an expression > of the form?? > > expr1 binary_op1 expr2 binary_op2 expr3 ... > > Seemingly, the answer is yes: > > >>> 3 in [3] in [[3],[4]] in [[[3],[4]],5] == [[[3],[2+2]],5] > True > > How does this play with standard precedence rules? Simple, all comparisons have the same priority: http://docs.python.org/ref/comparisons.html Peter From ewertman at gmail.com Tue Aug 19 21:44:04 2008 From: ewertman at gmail.com (Eric Wertman) Date: Tue, 19 Aug 2008 21:44:04 -0400 Subject: Storing Passwords Message-ID: <92da89760808191844p1c05cd30qad208fe4b28ba8b2@mail.gmail.com> I've a number of scripts set up that require a username/password combination to log in elsewhere. It's gotten to the point where I need to keep them in a more secure location, instead of just in the scripts themselves. I did a bit of searching, and haven't come up with a great way to store passwords using 2-way encryption (I have to send them as plain text). Has anyone seen anything that fits this need? I whipped up something using base64 and pickle, to keep them in a dictionary and at least prevent them from being plain text, but it seems a bit insecure all the same. Any ideas, much appreciated. Thanks! Eric From nodrogbrown at gmail.com Wed Aug 27 13:10:57 2008 From: nodrogbrown at gmail.com (gordon) Date: Wed, 27 Aug 2008 10:10:57 -0700 (PDT) Subject: Tkinter event loop question Message-ID: <9eaef6c3-c913-497f-8ca2-0466eb178c7a@z6g2000pre.googlegroups.com> is it possible to send a message to the gui instance while the Tk event loop is running?I mean after i create a gui object like root=Tk() mygui=SomeUI(root) and call root.mainloop() can i send message to mygui without quitting the ui or closing the window?i tried some code like mygui.someMethod() but it only gets executed after i close the the ui window.Is there a way to get this message passing while gui is running ? (forgive me ,it is a repeat question..but i am a bit desperate) thanks gordon From dullrich at sprynet.com Tue Aug 12 12:27:26 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 12 Aug 2008 11:27:26 -0500 Subject: How to best explain a "subtle" difference between Python and Perl ? References: <4290ea3f-43b9-455d-bd60-587369842c5b@s50g2000hsb.googlegroups.com> Message-ID: In article <4290ea3f-43b9-455d-bd60-587369842c5b at s50g2000hsb.googlegroups.com>, Palindrom wrote: > Hi everyone ! > > I'd like to apologize in advance for my bad english, it's not my > mother tongue... > > My girlfriend (who is a newbie in Python, but knows Perl quite well) > asked me this morning why the following code snippets didn't give the > same result : > > ### Python ### > > liste = [1,2,3] > > def foo( my_list ): Right now my_list is a local variable - since you called foo(liste), the name my_list is bound to the object liste > my_list = [] But this line doesn't modify liste, instead it binds the name my_list to a different object. If you want to modify the list that my_List points to you could do it in either of two ways: def foo1(my_liste): del my_liste[:] def foo2(my_liste): my_liste[:] = [] > foo(liste) > > print liste# she expected liste to be an empty list > > ### Perl ### > > @lst =(1,2,3); > $liste =\@lst; > foo($liste); > print "@lst\n"; > > sub foo { > my($my_list)=@_; > @{$my_list}=() > } > > I have to admit that I don't know how to clearly explain to her the > differences between these results. > Could someone please help us understand these difference between > Python and Perl ? > > Thanks in advance, > P4|1ndr0m -- David C. Ullrich From avinashvora at gmail.com Mon Aug 4 03:25:20 2008 From: avinashvora at gmail.com (Avinash Vora) Date: Mon, 4 Aug 2008 12:55:20 +0530 Subject: Teething troubles with Python on a Mac In-Reply-To: <4896725F.20806@cosc.canterbury.ac.nz> References: <6651edd6-d47f-4e10-bf0b-0875190b9bc2@a1g2000hsb.googlegroups.com> <489546F1.9050102@cosc.canterbury.ac.nz> <3dcf39de-3c3c-4e47-abb4-508d1601a9e2@z11g2000prl.googlegroups.com> <4896725F.20806@cosc.canterbury.ac.nz> Message-ID: (Greg: You only sent the email to me: you probably wanted to add the mailing list to the recipients.) On Aug 4, 2008, at 8:37 AM, greg wrote: > Avi wrote: > >> On that: how would I go about updating the system Python, then? > > The usual advice is not to try to do that at all. > Generally it's best to treat anything in /System > as off-limits. Right, but I meant if there is an Apple-sanctioned way. I guess not? >> (I used to do so, but it >> caused so many issues with installing new packages that I gave up on >> it) > > I've very rarely had any problem with maintaining my > own Python installation, but as I said, I always install > packages using "python setup.py". I guess I'll give it a shot, then. Alias in bash to MacPython, I assume? > Python itself copes very well with having multiple > versions installed, on all platforms, but you have to > do things the Python way. My point was that it seems to be a bit of a hack. Thanks for the advice from everyone, though. -- Avi From rocksportrocker at googlemail.com Sat Aug 2 07:07:35 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Sat, 2 Aug 2008 04:07:35 -0700 (PDT) Subject: Interconvert a ctypes.Structure to/from a binary string? References: Message-ID: On 2 Aug., 08:35, Andrew Lentvorski wrote: > Basically, I'd like to use the ctypes module as a much more descriptive > "struct" module. > > Is there a way to take a ctypes.Structure-based class and convert it > to/from a binary string? > > Thanks, > -a My first idea was : from ctypes import * from pickle import * class T(Structure): pass print dumps(T()) which raises an TypeError, "abstract class". And then I found http://osdir.com/ml/python.ctypes/2006-03/msg00009.html Greetings, Uwe From michael.pearmain at tangozebra.com Wed Aug 13 06:56:43 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Wed, 13 Aug 2008 03:56:43 -0700 (PDT) Subject: Perl to Python using MqSQLdb References: Message-ID: <25143519-21fd-4b2e-962d-b20c34331435@z66g2000hsc.googlegroups.com> Thanks for that Daniel, I've been able to apply the logic to the rest of the script i'm converting. There are only two bits that i don't understand in the Perl script that i need to convert, my $sql = shift; and my @row = $sth->fetchrow_array; $$StartDate = $row[0]; $$EndDate = $row[1]; $sth->finish() can you offer any advise? Mike From deets at nospam.web.de Mon Aug 25 18:38:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Aug 2008 00:38:57 +0200 Subject: Replace reduce with listcomprehension? In-Reply-To: <3a99c7ea-4cc9-4b9f-b6f8-60856cbd8837@c58g2000hsc.googlegroups.com> References: <3a99c7ea-4cc9-4b9f-b6f8-60856cbd8837@c58g2000hsc.googlegroups.com> Message-ID: <6hgqk1Flobm0U1@mid.uni-berlin.de> ssecorp schrieb: > GvR wants to eliminate all the functional stuff (lambda map reduce > filter) which kind of makes sense for Python, listcomprehensions are > more efficient(at least as implemented inpython) from what i have > gathered and they can express everything map/reduce/filter with > crippled lambdas can. > > but what about this: > reduce(lambda x,y:x*y+x,[1,2,3,4,5,6]) > > how would I express that in a listcomprehension? You can't. And AFAIK your are wrong - GvR doesn't wan to eliminate the functional stuff. http://www.artima.com/weblogs/viewpost.jsp?thread=98196 http://www.python.org/dev/peps/pep-3099/ Diez From martin at v.loewis.de Mon Aug 11 17:28:02 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 11 Aug 2008 23:28:02 +0200 Subject: dict.update() useful or not? In-Reply-To: References: <00b06f78$0$14351$c3e8da3@news.astraweb.com> Message-ID: <48a0aee2$0$24005$9b622d9e@news.freenet.de> >> def create_request(url, headers): >> headers.update(DEFAULT_HEADERS) >> req = urllib2.Request(url, None, headers) >> # ... >> return req >> >> but of course this second example does the Wrong Thing, replacing >> explicit headers with default values. > > There's a second code smell with that: even if it did what you want it > isn't nice to mutate the parameter passed in as headers. What if the caller > wants to reuse the headers again for another call? Just in case it isn't clear what the problem with that code is: create_request is a function, ie. it returns a value. As such, it shouldn't have any side effects. If it has side effects, it should be considered a procedure, and return None. Regards, Martin From max at alcyone.com Tue Aug 26 02:52:59 2008 From: max at alcyone.com (Erik Max Francis) Date: Mon, 25 Aug 2008 23:52:59 -0700 Subject: why in returns values for array and keys for dictionary In-Reply-To: <3e4f4d98-3255-4916-9337-e926aaeb6a20@p10g2000prf.googlegroups.com> References: <3e4f4d98-3255-4916-9337-e926aaeb6a20@p10g2000prf.googlegroups.com> Message-ID: ++imanshu wrote: > Wouldn't it be nicer to have 'in' return values (or keys) for both > arrays and dictionaries. Arrays and Dictionaries looked so similar in > Python until I learned this difference. It's because dealing with keys makes far more sense, since that's how the dictionary data structure works. If you're doing this an awful lot -- whether testing for inclusion or iterating -- then you're probably using the wrong data structure. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Well I have been puppetized / Oh how I have compromised -- Lamya From cniall at icedcerulean.com Sun Aug 3 10:02:31 2008 From: cniall at icedcerulean.com (CNiall) Date: Sun, 03 Aug 2008 15:02:31 +0100 Subject: Decimals not equalling themselves (e.g. 0.2 = 0.2000000001) Message-ID: <4895BA77.2030508@icedcerulean.com> I am very new to Python (I started learning it just yesterday), but I have encountered a problem. I want to make a simple script that calculates the n-th root of a given number (e.g. 4th root of 625--obviously five, but it's just an example :P), and because there is no nth-root function in Python I will do this with something like x**(1/n). However, with some, but not all, decimals, they do not seem to 'equal themselves'. This is probably a bad way of expressing what I mean, so I'll give an example: >>> 0.5 0.5 >>> 0.25 0.25 >>> 0.125 0.125 >>> 0.2 0.20000000000000001 >>> 0.33 0.33000000000000002 As you can see, the last two decimals are very slightly inaccurate. However, it appears that when n in 1/n is a power of two, the decimal does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2 and not 0.20000000000000001? This discrepancy is very minor, but it makes the whole n-th root calculator inaccurate. :\ From fredrik at pythonware.com Fri Aug 15 10:55:17 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 15 Aug 2008 16:55:17 +0200 Subject: Early halt for iterating a_list and iter(a_list) In-Reply-To: References: Message-ID: Lie wrote: > When you've got a nested loop a StopIteration in the Inner Loop would > break the loop for the outer loop too: > > a, b, c = [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5] > > def looper(a, b, c): > for a_ in a: > for b_ in b: > for c_ in c: > print a_, b_, c_ > > looper(a, b, c) # Intended behavior [1] > a, b, c = iter(a), b, iter(c) # b is intentionally not iter()-ed > looper(a, b, c) # Inner StopIteration prematurely halt outer loop [2] iterators are once-only objects. there's nothing left in "c" when you enter the inner loop the second time, so nothing is printed. >>> a = range(10) >>> a = range(5) >>> a = iter(a) >>> for i in a: ... print i ... 0 1 2 3 4 >>> for i in a: ... print i ... >>> > This is a potential problem since it is possible that a function that > takes an iterable and utilizes multi-level looping could be > prematurely halted and possibly left in intermediate state just by > passing an iterator. it's a problem only if you confuse iterators with sequences. From robert2821 at verizon.net Thu Aug 21 22:22:15 2008 From: robert2821 at verizon.net (robert2821) Date: Thu, 21 Aug 2008 22:22:15 -0400 Subject: Decorators using instance variables Message-ID: <48AE22D7.2070803@verizon.net> Hi, I'm new; greetings all! I'm wondering if the following program should work. I think it should print 'Hello, World', but instead it produces a TypeError. Is this a bug in decorators, a feature of them, or a mistake or misunderstanding on my part? TIA, Bob def getdec (f): dec = decorator (f) return dec. docall class decorator: def __init__ (self, f): self. f = f def docall (self, *a): return self. f (*a) class test: @ getdec def doit (self, message): print message if __name__ == '__main__': foo = test () foo. doit ('Hello, world') -------------- next part -------------- A non-text attachment was scrubbed... Name: Dec.py Type: text/x-python Size: 327 bytes Desc: not available URL: From rafesacks at gmail.com Fri Aug 15 14:02:36 2008 From: rafesacks at gmail.com (Rafe) Date: Fri, 15 Aug 2008 11:02:36 -0700 (PDT) Subject: Handling Property and internal ('__') attribute inheritance and creation Message-ID: Hi, I've been thinking in circles about these aspects of Pythonic design and I'm curious what everyone else is doing and thinks. There are 3 issues here: 1) 'Declaring' attributes - I always felt it was good code practice to declare attributes in a section of the class namespace. I set anything that is constant but anything variable is set again in __init__(): Class A(object): name = "a name" type = "a typee" childobject = None def __init__(self, obj): self.childobject = object This makes it easy to remember and figure out what is in the class. Granted there is nothing to enforce this, but that is why I called it 'code practice'. Do you agree or is this just extra work? 2) Internal attributes (starting with 2x'_') aren't inherited. Do you just switch to a single '_' when you want an "internal" attribute inherited? These are attributes I want the classes to use but not the user of these classes. Of course, like anything else in Python, these aren't really private. It is just a convention, right? (The example for #3 shows this.) 3) It isn't possible to override a piece of a Property Descriptor. To get around this, I define the necessary functions in the class but I define the descriptor in the __new__() method so the inherting class can override the methods. Am I overlooking some basic design principle here? This seems like a lot of work for a simple behavior. Example: class Base(object): def __new__(cls): setattr(cls, "state", property(fget = cls._Get_state, fset = cls._Set_state, fdel = None, doc = cls._doc_state)) obj = super(Base, cls).__new__(cls) return obj state = None # Set in __new__() _state = True _doc_state = "The state of this object" def _Get_state(self): return self._state def _Set_state(self, value): self._state = value class Child(Base): def _Get_state(self): # Do some work before getting the state. print "Getting the state using the child's method" return self._state print Child().state Please share your thoughts, - Rafe From dudeja.rajat at gmail.com Fri Aug 29 12:16:06 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Fri, 29 Aug 2008 17:16:06 +0100 Subject: How to check is something is a list or a dictionary or a string? Message-ID: Hi, How to check if something is a list or a dictionary or just a string? Eg: for item in self.__libVerDict.itervalues(): self.cbAnalysisLibVersion(END, item) where __libVerDict is a dictionary that holds values as strings or lists. So now, when I iterate this dictionary I want to check whether the item is a list or just a string? Thanks, Rajat From jake at vapourforge.com Wed Aug 6 20:37:23 2008 From: jake at vapourforge.com (Jake Anderson) Date: Thu, 07 Aug 2008 10:37:23 +1000 Subject: benchmark In-Reply-To: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> Message-ID: <489A43C3.8050207@vapourforge.com> Jack wrote: > I know one benchmark doesn't mean much but it's still disappointing to see > Python as one of the slowest languages in the test: > > http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy/ > > > -- > http://mail.python.org/mailman/listinfo/python-list > Something to note though, The python version is ~ half the length of the rest of them ;-> From poojaangali at gmail.com Fri Aug 15 05:59:50 2008 From: poojaangali at gmail.com (pooja) Date: Fri, 15 Aug 2008 02:59:50 -0700 (PDT) Subject: EARN MONEY $1500-$5000 PER MONTH Message-ID: <8d4fba5d-21c2-424a-982e-707afc3dfa64@u6g2000prc.googlegroups.com> EARN MONEY $1500-$5000 PER MONTH SIMPLE ONLINE SURVEY CREATE UR ACCOUNT AND EARN IMMEDIATLY ************************************************************************* http://www.AWSurveys.com/HomeMain.cfm?RefID=kingraja666 ************************************************************************* From woodygar at sky.com Thu Aug 7 13:55:46 2008 From: woodygar at sky.com (garywood) Date: Thu, 7 Aug 2008 18:55:46 +0100 Subject: very newbie question Message-ID: <5F1D8E1D20CE4B7D9E874FED0AFFD677@Home> stuck on python for absolute beginners chapter 6 i actually done what i was supposed to do use the function ask_number for guess a number but for some reason it does not count correctly the number of tries # Guess My Number # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money import random print "\tWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 100." print "Try to guess it in as few attempts as possible.\n" # set the initial values def ask_number(): the_number = random.randrange(100) + 1 guess = int(raw_input("Take a guess: ")) tries = 1 while (guess != the_number): if (guess > the_number): print "Lower..." else: print "Higher..." tries += 1 guess = int(raw_input("Take a guess: ")) tries += 1 ask_number() print "You guessed it! The number was", the_number print "And it only took you", tries, "tries!\n" raw_input("\n\nPress the enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: From gjhames at gmail.com Thu Aug 14 11:25:55 2008 From: gjhames at gmail.com (Gewton Jhames) Date: Thu, 14 Aug 2008 12:25:55 -0300 Subject: Replace Several Items In-Reply-To: <48A40A6C.3030509@egenix.com> References: <513926b0-64fe-4fdc-bb33-bc4b8ad3ab10@a70g2000hsh.googlegroups.com> <1218664455.5179.20.camel@jmk> <48A40A6C.3030509@egenix.com> Message-ID: <23bdbe700808140825na62bbbby7b957e630fe69ff8@mail.gmail.com> thanks, guys. On Thu, Aug 14, 2008 at 7:35 AM, M.-A. Lemburg wrote: > On 2008-08-13 23:54, John Krukoff wrote: > >> On Wed, 2008-08-13 at 09:39 -0700, gjhames wrote: >> >>> I wish to replace several characters in my string to only one. >>> Example, "-", "." and "/" to nothing "" >>> I did like that: >>> my_string = my_string.replace("-", "").replace(".", "").replace("/", >>> "").replace(")", "").replace("(", "") >>> >>> But I think it's a ugly way. >>> >>> What's the better way to do it? >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> >> The maketrans interface is a bit clunky, but this is what >> string.translate is best at: >> >> ?>>> import string >> >>> '-./other'.translate( string.maketrans( '', '' ), '-./' ) >>>>> >>>> 'other' >> >> It'd be interesting to see where it falls in the benchmarks, though. >> >> It's worth noting that the interface for translate is quite different >> for unicode strings. >> > > Right. Unicode .translate() uses a dictionary for defining the > mapping. > > Another approach is to use the re module: > > >>> import re > >>> re.sub('[-./()]', '', '-./other') > 'other' > > -- > Marc-Andre Lemburg > eGenix.com > > Professional Python Services directly from the Source (#1, Aug 14 2008) > >>> Python/Zope Consulting and Support ... http://www.egenix.com/ > >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ > >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ > ________________________________________________________________________ > > :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: > > > eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 > D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg > Registered at Amtsgericht Duesseldorf: HRB 46611 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From duane.kaufman at gmail.com Thu Aug 7 10:13:05 2008 From: duane.kaufman at gmail.com (TheSeeker) Date: Thu, 7 Aug 2008 07:13:05 -0700 (PDT) Subject: Adding Microsoft objects in Boa Constuctor Palette References: <26b16796-f717-40bb-b6e9-a918598b44e2@d77g2000hsb.googlegroups.com> Message-ID: <92cc447d-e3b4-4092-b755-529bbcc07a22@x41g2000hsb.googlegroups.com> On Aug 6, 5:59 pm, Sid K wrote: > This is what I wanted to do: > > Add Microsoft Active objects like Excel sheets and Word files to the > Palette in Boa Constructor. There is a User tab in the GUI builder > menu, but I'm not sure how to use/enable it. > > 1. Does anyone know how to do this? > 2. Is anyone aware of any work that is currently going on to support > adding Microsoft objects in Boa. > 3. Does any other Python GUI creator/editor exist out there that can > do this? > 4. How would one add an excel sheet to a wx.Panel in general w/ or w/o > Boa? > > Looking forward to replies... > > -SK Hi, You might get a response by trying the wxPython list: wxPython- users at lists.wxwidgets.org or the Boa list: boa-constructor- users at lists.sourceforge.net Duane From google at mrabarnett.plus.com Thu Aug 21 21:29:44 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 21 Aug 2008 18:29:44 -0700 (PDT) Subject: Unexpected regex result Message-ID: <1ea54287-7228-448c-a9f9-ad67e05a4663@r66g2000hsg.googlegroups.com> I'm working on the sources for the regex module (_sre.c) but I've come across some behaviour that I wasn't aware of before: >>> re.match('((a)|b)*', 'abc').groups() ('b', 'a') The regex module was modified to return this instead of the previous ('b', '') in issue #725106 because both Perl and sed returned this. My version of the module returns ('b', None), which was what I thought/ expected was the correct answer. Could someone explain to me what the rationale for returning ('b', 'a') is? Is it just because Perl and sed do this? (And if so, why has it been decided that it shouldn't be possible to split a string on a zero-width match even though Perl does? :-() From castironpi at gmail.com Mon Aug 25 16:03:09 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 25 Aug 2008 13:03:09 -0700 (PDT) Subject: Struct class random access Message-ID: <7986a90f-bf53-47f9-a327-f6249680594c@z66g2000hsc.googlegroups.com> struct.Struct lets you encode Python objects into structured memory. It accepts a format string, and optionally a buffer and offset to/from which to read/write the structure. What do you think of random access for the results? (unproduced) >>> packer= struct.Struct( 'IIIf255p' ) >>> packer.pack_into( buf, off, 10, 20, 30, 0.5, 'abc' ) >>> packer.unpack_from( buf, off, 2 ) #reads field 2 30 Does this take a PEP, or just a patch submission? From larry.bates at websafe.com` Mon Aug 4 08:25:35 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 04 Aug 2008 07:25:35 -0500 Subject: Using two pythons in an application In-Reply-To: References: Message-ID: Allen wrote: > Larry Bates wrote: >> Allen wrote: >>> I'm in the process of developing an application that will use Python >>> for a scripting support. In light of the upcoming changes to Python, >>> I was wondering if it is possible to link to and use two different >>> versions of Python so that in the future, scripts could be migrated >>> to the new version, and older scripts would still work as well. If >>> so are there any code examples of this. >>> >>> Brian Vanderburg II >> >> Unlike languages you pay for, Python has on real motivation to >> "obsolete" old versions of Python (e.g. to force you to pay of an >> upgrade). You can still get version 1.5.2 of Python and it is MANY >> years old and most could consider quite obsolete. I just would not >> worry about it and stick with 2.5/2.6 for development and begin >> looking at Python 3.0 so I can learn what's new and exciting. >> >> -Larry > > I agree. I had wanted for scripts of the program to be able to use the > new string format method that is only in py3k, but I'm currently looking > into other template solutions. > > Brian Vanderburg II There are many good ones around that you can look at: http://www.webwareforpython.org/Papers/Templates/ -Larry From pavlovevidence at gmail.com Tue Aug 26 23:50:42 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 26 Aug 2008 20:50:42 -0700 (PDT) Subject: What's your first choice if you have to write a C module for python? References: Message-ID: <15154823-51ea-4b4b-8401-a33e71964710@p25g2000hsf.googlegroups.com> On Aug 26, 8:19 am, ??? wrote: > What's your first choice when you have write a C/C++ module for Python? 1. Plain C code 2. Implement my own C extension code generator in Python 3. ctypes ... ... Infinity. SWIG Carl Banks From steven at REMOVE.THIS.cybersource.com.au Fri Aug 8 06:25:43 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 08 Aug 2008 10:25:43 GMT Subject: Best practise implementation for equal by value objects References: <135eb396-6daa-4ff4-a722-253ba149889c@27g2000hsf.googlegroups.com> <573362d6-5356-4029-8ee4-f43248263976@p25g2000hsf.googlegroups.com> <71daf8cf-024c-4ab1-b050-7f1f626e89c0@r66g2000hsg.googlegroups.com> Message-ID: On Fri, 08 Aug 2008 00:28:02 -0700, Slaunger wrote: > OK, i am encouraged to carry on my quest with the eval(repr)) for my > 'nice' classes. > I just revisited the documentation for eval and noticed that there are > optional globals > and locals name space variables, that one could specify: > > http://docs.python.org/lib/built-in-funcs.html > > Quite frankly I do not understand how to make use of these parameters, > but it is my feeling > that if I enforce a convention of always specifying the globals/locals > parameter in a specific > manner: > assert eval(repr(x), globals, locals) == x would work independent of how > I have imported the module under test. > > Now, I just need to figure out if this is right and how to specify the > globals and locals if that is not too cumbersome... or maybe I am just > over-engineering... I think it is infeasible for the repr() of an object to know where it was imported from. Including the globals and locals in the call to eval() won't help you, because they can have changed between the time you created the instance and the time you call repr(). Consider: >>> import datetime >>> x = datetime.time(20, 21, 22) >>> x datetime.time(20, 21, 22) >>> eval(repr(x)) == x True So far so good! But now watch this, starting in a fresh session: >>> import datetime as timedate >>> t = timedate.time >>> timedate.tttime = timedate.time >>> del timedate.time >>> assert t is timedate.tttime >>> >>> x1 = t(20, 21, 22) >>> x2 = timedate.tttime(20, 21, 22) >>> assert x1 == x2 What should repr(x1) and repr(x2) be, for your invariant eval(repr(x))==x to hold? It gets better (or worse): >>> alist = [None, t, None] >>> del t, timedate >>> x3 = alist[1](20, 21, 22) >>> assert x1 == x2 == x3 What should the repr() of x1, x2, x3 be now? Bringing this back to the unittests... as I see it, there's an easy way to solve your problem. In the unittest, just do something like the following: # repr(x) looks like "module.class(arg)", # but we actually import it as package.module.submodule.class module = package.module.submodule assert eval(repr(x)) == x I think that is all you need to do. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 15 09:14:08 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2008 13:14:08 GMT Subject: negative numbers are not equal... References: <48A4932F.4010302@gmail.com> <2e66b313-d2b1-4ca1-804f-6af79b252739@j22g2000hsf.googlegroups.com> Message-ID: <00b57c1d$0$14351$c3e8da3@news.astraweb.com> On Thu, 14 Aug 2008 20:44:32 -0700, castironpi wrote: > For > > a= 6 > b= a > > the test > > a is b > > should clearly return true. Since Python promises not to make a copy of a when you execute "b = a", then I think that such behaviour is guaranteed by the language. > Python distinguishes what mathematics does > not, between identity and equality. Clearly 5+4 and 6+3 - evaluate- to > the same, but math doesn't define whether they are the same, and in some > sense the question isn't asked ordinarily, or isn't debated. I want to > infer that math doesn't define the 'is' relation as Python knows it. Mathematicians often *define* equality as identity. That certainly makes sense when dealing with numbers -- what would it mean to say that there are (say) three different instances of the abstract integer 42, all equal yet not identical? I suggest that this simply doesn't make sense -- it is "not even wrong". Equality-as-identity may not hold in all areas of mathematics, but I think it is safe to say it holds for ideal (abstract) numbers, as opposed to implementations of numbers as bit patterns or objects in memory. http://en.wikipedia.org/wiki/Equality_(mathematics) -- Steven From straton at lampsacos.demon.co.uk Fri Aug 29 07:04:20 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 29 Aug 2008 12:04:20 +0100 Subject: class definition syntax In-Reply-To: <41b9bc43-8b48-40d6-bd2d-4578371bb8dc@i24g2000prf.googlegroups.com> References: <41b9bc43-8b48-40d6-bd2d-4578371bb8dc@i24g2000prf.googlegroups.com> Message-ID: harryos wrote: > hi > i have seen some class definitions like > > class MyClass(object): > def __init__(self): > .... > > what does the object keyword inside the braces in MyClass() mean? > Has it got any significance? > > thanks in advance > harry It is a syntax used for 'new type' classes, not so new any more. If you google that phrase, you get many references. Here is a tutorial dating back to 2005. http://www.geocities.com/foetsch/python/new_style_classes.htm From bearophileHUGS at lycos.com Thu Aug 28 14:13:06 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 28 Aug 2008 11:13:06 -0700 (PDT) Subject: Problem with list.insert References: Message-ID: Subhabrata, it's very difficult for me to understand what your short program has to do, or what you say. I think that formatting and code style are important. So I suggest you to give meaningful names to all your variable names, to remove unused variables (like n), to add blank likes here and there to separate logically separated parts of your program, or even better to split it into functions. You can remove some intermediate function, coalescing few logically related operations into a line, you can put spaces around operators like = and after a commas, you can show an usage example in English, so people can understand what the program is supposed to to, you can avoid joining and then splitting strings again, remove useless () around certain things. This is a possible re-write of the first part of your code, it's not exactly equal... def input_words(): input_message = "Print one English sentence for dictionary check: " return raw_input(input_message).lower().split() def load_dictionary(): return set(line.rstrip() for line in open("words.txt")) def dictionary_search(dictionary, words): found = [] not_found = [] for word in words: if word in dictionary: found.append(word) else: not_found.append(word) return found + not_found inwords = input_words() dictionary = load_dictionary() print dictionary_search(dictionary, inwords) It's far from perfect, but you can use it as starting point for a rewrite of your whole program. Bye, bearophile From hubaghdadi at gmail.com Wed Aug 20 06:53:33 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Wed, 20 Aug 2008 03:53:33 -0700 (PDT) Subject: Basic importing question References: Message-ID: On Aug 20, 5:43 am, John Machin wrote: > On Aug 20, 8:08 pm, Hussein B wrote: > > > Hey, > > Suppose I have a Python application consists of many modules (lets say > > it is a Django application). > > If all the modules files are importing sys module, how many times the > > sys module will be compiled and executed? > > Only once (the first time the PVM locates, compiles and executes the > > sys module)? or once for each module importing sys? > > Thanks. > > sys is a built-in module, so the answer is zero times. > > For a non-builtin module foo where there exists: > (1) only a foo.py, it will be compiled into foo.pyc > (2) only a foo.pyc, it will be used > (3) both a foo.py and a foo.pyc, Python compiles the foo.py if the pyc > is out of date or (so I believe [*]) was created by a different > version of Python. > > Subsequent imports will use the in-memory copy (in sys.modules, IIRC > [*]) ... > > [*] == Please save me the bother of checking this in the manual :-) > > HTH, > John Thank you both for your kind help and patience :) Built-in modules are compiled but even if they are so, when importing them (sys for example), Python will run their code in order to create bindings and objects, right? I'm learning Python and I want to learn it well, so that I'm asking a lot :) From ironfroggy at gmail.com Tue Aug 12 12:40:38 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Tue, 12 Aug 2008 12:40:38 -0400 Subject: Thesaurus / ontology / taxonomy Python library In-Reply-To: References: Message-ID: <76fd5acf0808120940y2bbea628we056ec989af341@mail.gmail.com> Sounds like you might want to read up on RDF On Tue, Aug 12, 2008 at 10:41 AM, Benjamin Michiels wrote: > Hi, > > I am curently looking for a library allowing the creation and management of > a thesaurus. Our requirements are the following: > > - creation of our own thesaurus (that is, terms AND relations between > terms), and indexing (and retrieving) documents with terms defined in our > thesaurus, > - "thesauraus management facilities", such as batch editing of content items > (e.g. for all documents indexed by keyword "A" and "B", replace keywords "A" > and "B" by keyword "C"). > - user-friendly interface. This could a be tree-like structure (with - > ideally - several levels of indexing), such as: > Shape - TS: Square > + TS: Triangle - TS: Scalene triangle > > + TS: Equilateral triangle - [...] > > Ideally, this library would be ready-for-Plone3.x-Zope2.10; but after some - > basic - searches, it appeared that such thesaurus management tools are > rather rare, so I was wondering whether there would even exist such a > library in Python... > > What do you think of it and/or is there already a discussion on this topic? > > Thank you in advance, > > Benjamin Michiels > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy From afriere at yahoo.co.uk Mon Aug 18 22:47:10 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 18 Aug 2008 19:47:10 -0700 (PDT) Subject: Python does not get environment variable when using cron. References: <20080818122747.F1BCE1E4003@bag.python.org> Message-ID: <6601e03d-cb45-49f8-a075-2f3960cad1d5@v16g2000prc.googlegroups.com> On Aug 18, 11:17 pm, "Shawn Milochik" wrote: > > The easiest solution (in my opinion) is to write a bash script to > execute your Python script, and use that bash script to add those > environment variables. Agreed. Wrap it in a shell script, easier to read and grow than a oneliner on the crontab. > The most likely file you'll want to run is > .bashrc in your home directory. If you're on a Mac, it's .bash_login > instead. > > Example: > > #/usr/bin/env bash > > source ~/.bashrc > path/my_script.py > I for one don't have $HOSTNAME defined in my .bashrc file. I doubt this is likely to give him much joy. > Something like that should take care of it. If not, get creative -- > add the "env" command to your bash script and have it send the output > to a file: env > cron_env.txt > Again no. The reason os.environ can't find HOSTNAME is that it is NOT defined in the environment, if env can find it os.environ should be able to as well. From bdesth.quelquechose at free.quelquepart.fr Thu Aug 21 16:54:43 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 21 Aug 2008 22:54:43 +0200 Subject: exception handling in complex Python programs In-Reply-To: <48adaa7e$0$4245$6e1ede2f@read.cnntp.org> References: <48ad8a47$0$30999$426a34cc@news.free.fr> <48adaa7e$0$4245$6e1ede2f@read.cnntp.org> Message-ID: <48add647$0$15607$426a74cc@news.free.fr> magloca a ?crit : > Bruno Desthuilliers @ Thursday 21 August 2008 17:31: > >>>> If you mean "the exceptions *explicitely raised* by your code", then >>>> I agree. But with any generic enough code, documenting any possible >>>> exception that could be raised by lower layers, objects passed in as >>>> arguments etc is just plain impossible. Like, if you have a function >>>> that takes a file-like object as arg, you just cannot know in >>>> advance what exceptions this object might raise. >>>> >>> This is one of the main concerns with which I started this c.l.py >>> thread ! I think it's a pity that we have no way of anticipating and >>> constraining the exceptions thrown by our code, >> Java's "checked exception" system has proven to be a total disaster. > > Could you elaborate on that? I'm not disagreeing with you (or agreeing, > for that matter); I'd just really like to know what you mean by > a "total disaster." One of the most (in)famous Java coding pattern is the empty catchall clause. Read Chris Mellon and Richard Levasseur posts in this thread for more details - they already covered the whole point. From wuwei23 at gmail.com Fri Aug 29 02:25:49 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 28 Aug 2008 23:25:49 -0700 (PDT) Subject: Tough Guy Competition References: Message-ID: On Aug 29, 3:45?pm, "W. eWatson" wrote: > Something to do on your weekends. [non-related link clipped] Another thing to do with your weekends would be to -not spam-. From gagsl-py2 at yahoo.com.ar Tue Aug 19 18:40:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 19 Aug 2008 19:40:31 -0300 Subject: Factory for Struct-like classes References: <62fe8607-af85-45ee-9392-c6f046b5941c@r66g2000hsg.googlegroups.com> Message-ID: En Tue, 19 Aug 2008 12:43:27 -0300, eliben escribi?: > On Aug 18, 11:16?am, Gabriel Genellina wrote: >> On 13 ago, 14:46, eliben wrote: >> >> > On Aug 13, 7:30?pm, Christian Heimes wrote: >> > > Try named tuplehttp://code.activestate.com/recipes/500261/ >> >> > 1) I see this is done with exec anyway, so there's no more pythonic >> > way. >> >> It doesn't *have* to be done with exec - I think there are other >> variants using metaclasses instead. >Can you suggest an alternative, without exec ? See these recipes: http://code.activestate.com/recipes/303439/ and 303770 and 303481; read the comments section too. -- Gabriel Genellina From anishchapagain at gmail.com Sat Aug 16 14:05:52 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Sat, 16 Aug 2008 11:05:52 -0700 (PDT) Subject: How to access an Array and a struct within a struct wrapped by Swig ? References: Message-ID: <6c21cc96-eab4-4823-97c6-c94e1d3da1ec@d1g2000hsg.googlegroups.com> Hi, If you have struct defined in .h file then it's ok or can dea easyily with struct written with .i file, in .h file, struct def { int a; char name[10]; }; can be referenced as >>strvar=new_def() //now strvar is your object for struct def and can access a and name as, get and set for individual member see, >>def_a_set(strvar,10) >>def_a_get(strvar) will return 10. or you can define struct as, typedef struct { int sage; }coll; within .h file and access similarly. regard's Anish Chapagain www.mysticnepal.com On Aug 16, 11:38?am, emmanuel.rivo... at gmail.com wrote: > Hello, > > I spent almost a week to be able to embed Python within my C++ game > engine. > I wrote a mini-tutorial of what I was able to do so far here :http://forums.indiegamer.com/showpost.php?p=169352&postcount=9 > > At the end of my tutorial, I wrote : "You can do the same with C++ > classes, and with structures within structures. Swig can parse & wrap > most C/C++ declarations." > > Gloups, I was so wrong..! :-S > > It seems that I can read a struct within my struct, but I cannot write > values to it. > Also, I cannot access the array from within my struct. > > Any help to achieve this would be very welcome. > > Here the problem in detail : > I'm using Python 2.5.2 & Swig 1.3.36. > > The structures : > struct SIn > { > ? ? ? ? int in1, in2; > > }; > > struct SPythoned > { > ? ? ? ? SIn Inner; > ? ? ? ? float Skill[16]; > > }; > > The python code : > ======================= > def TestObject(o): > ? ? ? ? print(type(o)) > ? ? ? ? print(type(o.Skill)) > ? ? ? ? print(o.Skill) > ? ? ? ? print(type(o.Inner)) > ? ? ? ? print(type(o.Inner.in1)) > ? ? ? ? print(o.Inner.in1) > ? ? ? ? print(o.Inner.in2) > > ? ? ? ? o.Inner.in1 = 12 > ? ? ? ? o.Inner.in2 = 17 > > ? ? ? ? print(o.Inner.in1) > ? ? ? ? print(o.Inner.in2) > ======================= > > It gives me this output : > ======================= > > > _20fd1300_p_float > > > 2 > 22 > 2 > 22 > ======================= > > So althought I can read the value, the "o.Inner.inX = Y" are without > effect..! (and checking the value in the object in the C part confirms > this). > > Moreover, if I add these lines : > ? ? ? ? for i in range(16) : > ? ? ? ? ? ? ? ? print(o.Skill[i]) > > I get this error : > Traceback (most recent call last): > ? File "d:\TE 2008\PyTest.py", line 32, in TestObject > ? ? print(o.Skill[i]) > TypeError: 'PySwigObject' object is unsubscriptable > > Any idea how to make this work ..? --------------- From Edwin.Madari at VerizonWireless.com Tue Aug 19 10:53:49 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Tue, 19 Aug 2008 10:53:49 -0400 Subject: who to call a list of method inside the class itself In-Reply-To: Message-ID: <20080819145403.207A71E4006@bag.python.org> maduma at pt.lu wrote: > Hi, > > Is the following code is ok. who to call all method. > It is working but the call to m() without a reference to self seems > strange > > Thanks for your help > > class CustomMethod: > def method1(self): > .... > def method2(self): > .... > def method3(self): > .... > > def getAllMethod(self): > return [self.method1, self.method2, self.method3] > > def applyAll(self): > for m in self.getAllMethod(): > # how to call all methods ? > # is it correct > m() 1. return string names of required methods in getAllMethod return ['method1', 'method2', 'method3'] 2. use gettattr on self and then exetute methods in applyAll def applyAll(self): for method_name in self.getAllMethod(): method = gettattr(self,method_name) method() #execute method now regards. Edwin The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From ramen at lackingtalent.com Wed Aug 20 22:51:09 2008 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 20 Aug 2008 19:51:09 -0700 Subject: Factory for Struct-like classes In-Reply-To: References: Message-ID: <1N4rk.167$_s1.91@newsfe07.iad> Christian Heimes wrote: > eliben wrote: >> Ruby's 'Scruct' class (http://ruby-doc.org/core/classes/Struct.html) >> does this. I suppose it can be done with 'exec', but is there a more >> Pythonic way ? > > Try named tuple http://code.activestate.com/recipes/500261/ > > A named tuple implementation is part of Python 2.6 and 3.0. For older > versions of Python use the recipe from activestate. Whaaa? Named tuples are being added to Python? Neat! Is there any documentation on this? I can't seem to find anything on the web... Thanks, Dave From kem1723 at yahoo.com Tue Aug 26 17:37:03 2008 From: kem1723 at yahoo.com (Kevin McKinley) Date: Tue, 26 Aug 2008 14:37:03 -0700 (PDT) Subject: Adding Icons to my Programs Message-ID: <801533.35218.qm@web83916.mail.sp1.yahoo.com> I've been turn my script into executible programs with Py2exe. Is there a way to change the icon for the main exe file? Thank you, Kevin McKinley From leon.domingo at gmail.com Mon Aug 11 04:49:43 2008 From: leon.domingo at gmail.com (leon.domingo at gmail.com) Date: Mon, 11 Aug 2008 01:49:43 -0700 (PDT) Subject: Eclipse, Python, wxPython and code completion References: <94acefa8-f3ec-4d5a-a7cb-a3bf769d35e9@79g2000hsk.googlegroups.com> Message-ID: <9d29ac73-dbe0-44fc-b3a9-b9f74a6aa38c@34g2000hsh.googlegroups.com> On 11 ago, 04:34, "SPE - Stani's Python Editor" wrote: > On 10 aug, 20:42, leon.domi... at gmail.com wrote: > > > > > Hello, > > > I've installed Eclipse, Python 2.5 and wxPython on Ubuntu 8.04. The > > problem is that I can't get code completion for wx module. I don't > > know if it occurs the same with other libraries outside the python > > "core". > > > If I compile/run my code containing the wx library, I get an > > application running correctly, so it looks that definition works fine. > > Obviously, the obstacle is that I don't know (I don't want to either) > > the name of every method of every wxPython class so it's difficult to > > develop anything within this environment. > > > Thanks a lot > > > Note: I'm a newbie-coming-from-"Billy's"-WindowsXP > > You can try SPE which is written in wxPython itself and has very good > code completion for wxPython. It also includes some wxPython GUI > builders such as wxGlade and XRCed. I improved it a lot for Hardy, > which I use myself: > sudo apt-get install spe > > Stani Thanks, Stani I will check this out From socyl at 987jk.com.invalid Tue Aug 5 13:38:20 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 5 Aug 2008 17:38:20 +0000 (UTC) Subject: How to troubleshoot hanging script? Message-ID: Hi! I have a Pythonoob question. I have a script that hangs indefinitely at random times; the only thing to do at this point is to kill it. I'm looking for suggestions on how to troubleshoot and debug the problem. I'm not even sure of where exactly the script is hanging, though I suspect it is right around when it tries to read from a pipe (generated by popen). (I arrived at this guess by putting print statements all over the place, but I'm not sure this is a very reliable way to pinpoint the error.) So the first thing I'd like to do is find out exactly where the script is hanging. It would be nice if I could just hit Ctrl-C (which sends SIGINT from the terminal) when the script is hanging, to kill it and get a backtrace, but when this script hangs it becomes unresponsive to Ctrl-C! The only way to kill it is with something like % pkill -KILL my_script.py or even % pkill -TERM my_script.py ...or -ABRT or -QUIT. I tried to exploit this by adding this to the script: import signal def term_handler(signum, frame): raise KeyboardInterrupt signal.signal(signal.SIGTERM, term_handler) ...but this did not help at all; in fact, after this addition, the script no longer responded to pkill -TERM. TIA! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From gh at ghaering.de Tue Aug 26 02:20:53 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 26 Aug 2008 08:20:53 +0200 Subject: Non-evil multithreaded WSGI server? Message-ID: In a recent experiment I've done this: from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from wsgiref.simple_server import make_server, demo_app from SocketServer import ThreadingMixIn # Let's make a WSGI server that can use multiple threads. class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Handle requests in a separate thread.""" # Evil! ;-) from wsgiref.simple_server import WSGIServer as MyWSGIServer MyWSGIServer.__bases__ = (ThreadedHTTPServer,) Now I wonder if there's a less evil way that does not involve copy & paste of the WSGIServer code (only couple of lines, but I hate duplication)?! -- Gerhard From gagsl-py2 at yahoo.com.ar Tue Aug 12 19:50:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Aug 2008 20:50:11 -0300 Subject: Problems returning data from embedded Python References: <2008081116580016807-cromulent@justextrememetalcom> <2008081223485416807-cromulent@justextrememetalcom> Message-ID: En Tue, 12 Aug 2008 19:48:54 -0300, Cromulent escribi?: > On 2008-08-12 05:37:53 +0100, "Gabriel Genellina" > said: > >> En Mon, 11 Aug 2008 12:58:00 -0300, Cromulent >> escribi?: >> >>> >> Uh? You have a complete API for working with list objects, the >> functions named PyList_* >> See http://docs.python.org/api/listObjects.html >> There is also an abstract layer that works both with lists and tuples: >> http://docs.python.org/api/sequence.html >> If that's not what you are after, please provide more details... > > Spoke too soon. > > Right, I've rewritten the Python program and it returns a tuple of lists > and one integer. Basically as you saw before, the python program reads a > file in, splits it into elements that were separated by a comma. > > The new program just puts each element into its own list. Here is a line > from the file I am reading in: > > 15-Jul-08,37.70,37.70,36.43,36.88,102600 > > so basically I have 6 lists and one int (which is the total number of > lines read by the program) I then return that tuple to the C program. You don't need the integer - it's the list length, and you can easily ask that value using PyList_Size. So you are now returning *columns* from the file, ok? > After that I call the following: > > error = PyArg_ParseTuple(value, "isffffi", &totalLines, &finopen, > &finclose, &finhigh, &finlow, &finvolume); > > but that will only give me the first element of the list. What I would > like to do is return the total number of lines read separately, then use > that to allocate a C99 style variable sized array and then loop through > the call to PyArg_ParseTuple to populate the array. The problem with > that is that I don't think PyArg_ParseTuple is designed in that way. It > will put the contents of the list in the variable and not split it up so > that I can populate an array. Yes, forget about PyArg_ParseTuple. It's intended to parse function arguments. Use the appropiate convert function for each object type. For integers, use PyInt_AsLong; for floats, PyFloat_AsDouble, and so on. Something like this (untested): // for a column containing float values: Py_ssize_t nitems = PyList_Size(the_python_list_of_floats) // ...allocate the C array... for (Py_ssize_t i=0; i References: Message-ID: Am 03.08.2008, 12:51 Uhr, schrieb Equand : > how about changing the precious self. to . > imagine > > self.update() > > .update() > > simple right? What about: class x: def x(self,ob): ob.doSomethingWith(self) ? Not so simple anymore, isn't it? If you're not trolling, there's hundreds of reasons why the explicit self is as it is, and it's not going to go away, just as a thread that produced immense amounts of response demonstrated around a week ago. Read that, and rethink. --- Heiko. From pierre.dagenais at ncf.ca Sun Aug 3 18:33:26 2008 From: pierre.dagenais at ncf.ca (Pierre Dagenais) Date: Sun, 03 Aug 2008 18:33:26 -0400 Subject: from Tkinter import *,win = Tk() "from Tkinter import *" Message-ID: from Tkinter import * win = Tk() If I type those two lines at the command prompt (in WindowsXP) I get a new window on my screen. Yet if I copy those lines in a file called test.py and then run "python test.py" at the command prompt I am returned to the command prompt and nothing shows up on the screen. Is this normal behavior or is it a bug? Thanks to all who responded to my previous post, it was quite helpfull. From M8R-n7vorv at mailinator.com Mon Aug 11 06:21:53 2008 From: M8R-n7vorv at mailinator.com (M8R-n7vorv at mailinator.com) Date: Mon, 11 Aug 2008 03:21:53 -0700 (PDT) Subject: benchmark References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> <5dc1189d-79c9-40a7-8024-924ba9a889b4@k13g2000hse.googlegroups.com> Message-ID: <89492d6b-0448-4a51-9a38-f6c4f2ef9422@w24g2000prd.googlegroups.com> On Aug 11, 2:09?pm, cokofree... at gmail.com wrote: > On Aug 11, 10:55 am, M8R-n7v... at mailinator.com wrote: > > > > > On Aug 10, 10:10 pm, Kris Kennaway wrote: > > > > jlist wrote: > > > > I think what makes more sense is to compare the code one most > > > > typically writes. In my case, I always use range() and never use psyco. > > > > But I guess for most of my work with Python performance hasn't been > > > > a issue. I haven't got to write any large systems with Python yet, where > > > > performance starts to matter. > > > > Hopefully when you do you will improve your programming practices to not > > > make poor choices - there are few excuses for not using xrange ;) > > > > Kris > > > And can you shed some light on how that relates with one of the zens > > of python ? > > > There should be one-- and preferably only one --obvious way to do it. > > > Dhananjay > > And that is xrange, but if you need a list range is better :P Interesting to read from PEP-3000 : "Python 2.6 will support forward compatibility in the following two ways: * It will support a "Py3k warnings mode" which will warn dynamically (i.e. at runtime) about features that will stop working in Python 3.0, e.g. assuming that range() returns a list." From adrian_p_smith at yahoo.com Tue Aug 26 01:11:20 2008 From: adrian_p_smith at yahoo.com (Adrian Smith) Date: Mon, 25 Aug 2008 22:11:20 -0700 (PDT) Subject: smart quotes Message-ID: <4188c027-3c64-429b-a1e6-a1f3a79060e8@a3g2000prm.googlegroups.com> Can anyone tell me how to get rid of smart quotes in html using Python? I've tried variations on stuff = string.replace(stuff, "\?", "\""), but to no avail, presumably because they're not standard ASCII. From dudeja.rajat at gmail.com Mon Aug 25 07:57:14 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 25 Aug 2008 12:57:14 +0100 Subject: Tkinter - How to create combo box using Tix with the existing Tkinter widgets/ Message-ID: Hi, I'm using Tkinter module to create a GUI application. I found that the combo box is not present in Tkinter module. It comes with Tix module. Could some one give me an example to create a combo box whilst using Tix and Tkinter? I've been using the following to create my tkinter widgets: myRoot = Tk() and in my Gui code, I've been using self.lbAnalysisLib = Listbox(master, \ yscrollcommand = self.vsbAnalysisLib.set,\ height = 1, width = 30) Please suggest how could I call the Tix's combo box from my existing GUI application that heavily uses the Tkinter widgets? Kindly provide me some code examples. Thanks and regards, Rajat From dullrich at sprynet.com Mon Aug 4 16:28:56 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 04 Aug 2008 15:28:56 -0500 Subject: PIL (etc etc etc) on OS X References: <489379A7.5060009@codebykevin.com> <48948BBA.9050706@codebykevin.com> Message-ID: Just as well that the message sent earlier today seems to have been lost... Ok. Read your instructions on libjpeg. Read some of the install.doc. ./configure, fine. make, fine. "make test", fine. So I said "sudo make install" and this happened: 0-1d-4f-fc-28-d:jpeg-6b dullric$ sudo make install Password: /usr/bin/install -c cjpeg /usr/local/bin/cjpeg /usr/bin/install -c djpeg /usr/local/bin/djpeg /usr/bin/install -c jpegtran /usr/local/bin/jpegtran /usr/bin/install -c rdjpgcom /usr/local/bin/rdjpgcom /usr/bin/install -c wrjpgcom /usr/local/bin/wrjpgcom /usr/bin/install -c -m 644 ./cjpeg.1 /usr/local/man/man1/cjpeg.1 /usr/bin/install -c -m 644 ./djpeg.1 /usr/local/man/man1/djpeg.1 /usr/bin/install -c -m 644 ./jpegtran.1 /usr/local/man/man1/jpegtran.1 /usr/bin/install -c -m 644 ./rdjpgcom.1 /usr/local/man/man1/rdjpgcom.1 /usr/bin/install -c -m 644 ./wrjpgcom.1 /usr/local/man/man1/wrjpgcom.1 Surely that means it was installed in /usr/local/bin, right? So I start over with PIL. It says I should "python setup.py build_ext -i". So I do: 0-1d-4f-fc-28-d:Imaging-1.1.6 dullric$ python setup.py build_ext -i running build_ext --- using frameworks at /System/Library/Frameworks -------------------------------------------------------------------- PIL 1.1.6 BUILD SUMMARY -------------------------------------------------------------------- version 1.1.6 platform darwin 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] -------------------------------------------------------------------- --- TKINTER support ok *** JPEG support not available --- ZLIB (PNG/ZIP) support ok --- FREETYPE2 support ok -------------------------------------------------------------------- To add a missing option, make sure you have the required library, and set the corresponding ROOT variable in the setup.py script. So I look in setup.py and I find this: # Library pointers. # # Use None to look for the libraries in well-known library locations. # Use a string to specify a single directory, for both the library and # the include files. Use a tuple to specify separate directories: # (libpath, includepath). Examples: # # JPEG_ROOT = "/home/libraries/jpeg-6b" # TIFF_ROOT = "/opt/tiff/lib", "/opt/tiff/include" # # If you have "lib" and "include" directories under a common parent, # you can use the "libinclude" helper: # # TIFF_ROOT = libinclude("/opt/tiff") FREETYPE_ROOT = None JPEG_ROOT = None #JPEG_ROOT = "/usr/local/bin" I try it both ways, with JPEG_ROOT=None and JPEG_ROOT = "/usr/local/bin" - same result both times, "JPEG support not available". Any thoughts? Later in setup.py it says if find_library_file(self, "jpeg"): feature.jpeg = "jpeg" elif sys.platform == "win32" and find_library_file(self, "libjpeg"): feature.jpeg = "libjpeg" # alternative name Not knowing exactly what "find_library_file" does I couldn't say, but it almost sounds like it's looking for a file named "jpeg". The summary from the jpeg install looks like it didn't install any such file. Maybe "jpeg" should be the name of one of those files that did get installed? This _is_ fun. Eech. DU. -- David C. Ullrich From davidreynon at gmail.com Thu Aug 14 10:54:30 2008 From: davidreynon at gmail.com (korean_dave) Date: Thu, 14 Aug 2008 07:54:30 -0700 (PDT) Subject: for y in range (0,iNumItems)--> not in order? Message-ID: <8514d915-95bf-4e57-a16a-68866e0ad789@l42g2000hsc.googlegroups.com> for y in range(0,iNumItems): print(str(y)) How do i make the output go IN ORDER 0 1 2 3 4 5 6 etc. instead of 0 1 10 11 12 13 14 2 3 4 5 6 7 8 9 From emmanuel.rivoire at gmail.com Sat Aug 16 07:13:31 2008 From: emmanuel.rivoire at gmail.com (emmanuel.rivoire at gmail.com) Date: Sat, 16 Aug 2008 04:13:31 -0700 (PDT) Subject: How to access an Array and a struct within a struct wrapped by Swig ? References: Message-ID: Ok, Swig needs the structure to be declared like this : typedef struct SIn { int in1, in2; } SIn; Else, it doesn't understand it's a structure... :-S Now, I can write to it. I also found out that Swig didn't allow to write to the array : http://www.swig.org/Doc1.3/SWIG.html#SWIG_nn34 ... :-S So I just have to find out how to read the array, and I'll be all good..! From steve at REMOVE-THIS-cybersource.com.au Mon Aug 18 19:01:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2008 23:01:26 GMT Subject: searching through a string and pulling characters References: Message-ID: <00b9fa2b$0$20315$c3e8da3@news.astraweb.com> On Mon, 18 Aug 2008 13:40:13 -0700, Alexnb wrote: > Lets say I have a text file. The contents look like this, only there is > A LOT of the same thing. > > () A registry mark given by underwriters (as at Lloyd's) to ships in > first-class condition. Inferior grades are indicated by A 2 and A 3. () > The first three letters of the alphabet, used for the whole alphabet. () > In church or chapel style; -- said of compositions sung in the old > church style, without instrumental accompaniment; as, a mass a capella, > i. e., a mass purely vocal. > () Astride; with a part on each side; -- used specif. in designating the > position of an army with the wings separated by some line of > demarcation, as a river or road. > > Now, I am talking 1000's of these. I need to do something like this. I > will have a number, and what I want to do is go through this text file, > just like the example. The trick is this, those "()'s" are what I need > to match, so if the number is 245 I need to find the 245th () and then > get the all the text from after it until the next (). If you have an > idea about the best way to do this I would love your help. If you made > it all the way through thanks! ;) If I take your description of the problem literally, then the solution is: text = "() A registry mark given ..." # lots and lots of text blocks = text.split( "()" ) # use a literal "()" as a delimiter answer = blocks[n] # whichever number you want, starting counting at 0 I suspect that the problem is more complicated than you are saying. I guess that in your actual data, the brackets () probably have something inside them. It looks like you are quoting definitions from a dictionary. Alex, a word of advice for you: we really don't like playing guessing games. If you get a reputation for describing your problem inaccurately, incompletely or cryptically, you will find fewer and fewer people willing to answer your questions. I recommend that you spend a few minutes now reading this page and save yourself a lot of grief later: http://www.catb.org/~esr/faqs/smart-questions.html Now, back to your problem. If my guess is right, and the brackets actually have text inside them, then my simple solution above will not work. You will need a more complicated solution using a regular expression or a parser. That solution will depend on whether or not you can get nested brackets "(ab (123 (fee fi fum) 456) cd ef)" or arbitrary single brackets without the matching pair. Your question also sounds suspiciously like homework. I don't do people's homework, but here's something to get you started. It's not a solution, but it can be used as the first step towards a solution. text = "() A registry mark given ..." # lots and lots of text level = 0 blocks = [] for c in text: # process text one character at a time if c == '(': print "Found an opening bracket" level += 1 # one deeper in brackets elif c == ')': level -= 1 if level < 0: print "Found a close bracket without matching open bracket" else: print "Found a closing bracket" else: # any other character # here's where you do the real work if level == 0: print "Not inside a bracket" blocks.append(c) else: print "Inside a bracket" if level > 0: print "Missing close bracket" text_minus_bracketed_words = ''.join(blocks) -- Steven From mal at egenix.com Thu Aug 7 15:27:01 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 07 Aug 2008 21:27:01 +0200 Subject: Fastest way to store ints and floats on disk In-Reply-To: <489B41CE.8080909@shopzeus.com> References: <489B41CE.8080909@shopzeus.com> Message-ID: <489B4C85.5000308@egenix.com> On 2008-08-07 20:41, Laszlo Nagy wrote: > > Hi, > > I'm working on a pivot table. I would like to write it in Python. I > know, I should be doing that in C, but I would like to create a cross > platform version which can deal with smaller databases (not more than a > million facts). > > The data is first imported from a csv file: the user selects which > columns contain dimension and measure data (and which columns to > ignore). In the next step I would like to build up a database that is > efficient enough to be used for making pivot tables. Here is my idea for > the database: > > Original CSV file with column header and values: > > "Color","Year","Make","Price","VMax" > Yellow,2000,Ferrari,100000,254 > Blue,2003,Volvo,50000,210 > > Using the GUI, it is converted to this: > > dimensions = [ > { 'name':'Color', 'colindex:0, 'values':[ 'Red', 'Blue', 'Green', > 'Yellow' ], }, > { 'name':'Year', colindex:1, 'values':[ > 1995,1999,2000,2001,2002,2003,2007 ], }, > { 'name':'Make', colindex:2, 'value':[ 'Ferrari', 'Volvo', 'Ford', > 'Lamborgini' ], }, > ] > measures = [ > { 'name', 'Price', 'colindex':3 }, > { 'name', 'Vmax', 'colindex':4 }, > ] > facts = [ > ( (3,2,0),(100000.0,254.0) ), # ( dimension_value_indexes, > measure_values ) > ( (1,5,1),(50000.0,210.0) ), > .... # Some million rows or less > ] > > > The core of the idea is that, when using a relatively small number of > possible values for each dimension, the facts table becomes > significantly smaller and easier to process. (Processing the facts would > be: iterate over facts, filter out some of them, create statistical > values of the measures, grouped by dimensions.) > > The facts table cannot be kept in memory because it is too big. I need > to store it on disk, be able to read incrementally, and make statistics. > In most cases, the "statistic" will be simple sum of the measures, and > counting the number of facts affected. To be effective, reading the > facts from disk should not involve complex conversions. For this reason, > storing in CSV or XML or any textual format would be bad. I'm thinking > about a binary format, but how can I interface that with Python? > > I already looked at: > > - xdrlib, which throws me DeprecationWarning when I store some integers > - struct which uses format string for each read operation, I'm concerned > about its speed > > What else can I use? >>> import marshal >>> marshal.dump(1, open('test.db', 'wb')) >>> marshal.load(open('test.db', 'rb')) 1 It also very fast at dumping/loading lists, tuples, dictionaries, floats, etc. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Aug 07 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From kyosohma at gmail.com Fri Aug 29 14:41:45 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 29 Aug 2008 11:41:45 -0700 (PDT) Subject: How to delete a last character from a string References: Message-ID: <8c59017c-7e21-41d6-8f27-58c519b38dec@l64g2000hse.googlegroups.com> On Aug 29, 1:28?pm, dudeja.ra... at gmail.com wrote: > Sorry : Earlier mail had a typo in Subject line which might look > in-appropriate to my friends > > Hi, > > I've a list some of whose elements with character \. > I want to delete this last character from the elements that have this > character set at their end, > > I have written a small program, unfortunately this does not work: > > dirListFinal = [] > for item in dirList: > ? ? ? ? ? ?print item > ? ? ? ? ? ?if item.endswith('\\') == True: > ? ? ? ? ? ? ? ?item = item[0:-1] ? ? ? ? # This one I googled and > found to remove the last character / > ? ? ? ? ? ? ? ?dirListFinal.append(item) > ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ?dirListFinal.append(item) > > item.endswith() does not seem to be working. > > Please help > -- > Regrads, > Rajat Try something like this: >>> x = 'test\\' >>> if x.endswith('\\'): x = x[:-1] This works with Python 2.5.2 on Windows XP. Mike From annumiya at yahoo.com Thu Aug 14 12:11:24 2008 From: annumiya at yahoo.com (annu miya) Date: Thu, 14 Aug 2008 09:11:24 -0700 (PDT) Subject: SOAPpy and ArrayOfString Message-ID: <304340.97330.qm@web53409.mail.re2.yahoo.com> Hi, ? In the article below you mention that you were succesful at doing this through perl. Would it be possible to send me the perl code? ? http://mail.python.org/pipermail/python-list/2007-January/423311.html ? Thank You ? Regards ? Sid -------------- next part -------------- An HTML attachment was scrubbed... URL: From mmanns at gmx.net Fri Aug 1 20:35:01 2008 From: mmanns at gmx.net (mmanns at gmx.net) Date: Sat, 2 Aug 2008 02:35:01 +0200 Subject: ANN: pyspread 0.0.8 Message-ID: pyspread 0.0.8 has been released. About: pyspread is a spreadsheet that accepts a pure python expression in each cell. New features: New macro dialog that allows defining python functions, which can be used in the grid. Bug fixes within the copy paste and print code. Highlights: + Numpy high performance arrays for spreadsheet calculation + Full access to python batteries from each cell + No non-python syntax add-ons + 3D grid + Cell access via slicing of numpy array S + X, Y, and Z yield current cell location for relative reference Requires: Python >=2.4, Numpy 1.0.4, and wxPython 2.8.7.1. License: GPL Project page: http://pyspread.sourceforge.net As always, feedback is appreciated. Please also test with wxPython 2.8.8.0. Enjoy Martin From kyosohma at gmail.com Fri Aug 8 09:15:20 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 8 Aug 2008 06:15:20 -0700 (PDT) Subject: Threading and wx..... References: Message-ID: <8ae10033-50e6-4527-a157-09ae206c8954@e39g2000hsf.googlegroups.com> On Aug 8, 2:19?am, SamG wrote: > On Aug 8, 12:01 pm, SamG wrote: > > > > > Hi, > > > Im trying my hand at threading with wx applications. I have written > > the following code... > > > import wx > > from threading import Thread, Lock > > > class createWindow(Thread): > > ? ? def __init__(self): > > ? ? ? ? Thread.__init__(self) > > ? ? ? ? self.lock = Lock() > > ? ? ? ? self.app=None > > > ? ? def run(self): > > ? ? ? ? #self.lock.acquire() > > ? ? ? ? self.app = wx.PySimpleApp() > > ? ? ? ? frame = wx.Frame(None, title="Hello wx") > > ? ? ? ? frame.Show() > > ? ? ? ? #self.lock.release() > > ? ? ? ? self.app.MainLoop() > > > if __name__=='__main__': > > ? ? c = createWindow() > > ? ? c.start() > > ? ? c.join() > > > Now when i run this program i get a window but the application just > > does not respond. Is there something that im missing here. Pls let me > > know. Thanks in advance. > > Oops! Murphy's law works again! And the above code is working fine. You'll probably also find the following wiki article helpful: http://wiki.wxpython.org/LongRunningTasks And there's at least one demo in the wxPython Demo that's a good example of threading. Mike From pmaupin at gmail.com Sun Aug 24 22:41:50 2008 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 24 Aug 2008 19:41:50 -0700 (PDT) Subject: Python String Immutability Broken! References: Message-ID: On Aug 24, 8:49?pm, "Hendrik van Rooyen" wrote: > (a lot of stuff related to using a string with a C library via ctypes) Very entertaining. But let me get this straight: Are you just complaining that if you pass a string to an arbitrary C function using ctypes, that that arbitrary function can modify the string? Because if you are, then I think you share a great deal of responsibility for the death of that string -- sending the poor thing to its grave through some unknown C function. What would you have ctypes do instead? From geekmoth at gmail.com Sat Aug 9 07:31:38 2008 From: geekmoth at gmail.com (Will Rocisky) Date: Sat, 9 Aug 2008 04:31:38 -0700 (PDT) Subject: How to round a floating point to nearest 10? Message-ID: I want my 76.1 to be rounded to decimal 80 and 74.9 to decimal 70. How can I achieve that? From fred.sells at adventistcare.org Sun Aug 24 23:25:03 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Sun, 24 Aug 2008 23:25:03 -0400 Subject: swig double[], under the gun and need help In-Reply-To: <48a5b125$0$21248$426a34cc@news.free.fr> Message-ID: <0A53725C4A497848A7B3A0874B259831011B0A10@acesxch01.ADVENTISTCORP.NET> I'm using python 2.4 under linux (centos 5.1). I need to pass an array of doubles to a c function but am getting an error, shown near the bottom of this post. ---------------------------------------------------- my swig interface file looks like this * File: rug520.i */ %module rug520 %include "typemaps.i" %include "carrays.i" %array_class(double, doubleArray); %{ #define SWIG_FILE_WITH_INIT #include "rug520.h" extern double[] nCmiArray; %} %apply int *OUTPUT { char *sRugHier, char * sRugMax, int * iRugHier, int * iRugMax, double * nCmiValueHier, double * nCmiValueMax, int * iAdlSum, int * iCpsCode, char * sRugsVersion, char * sDllVersion, int * iError }; int RugCalc( char * sMdsRecord, char * sRehabType, char * sModel, int iQuarterlyFlag, double nCmiArray[], char * sRugHier, char * sRugMax, int * iRugHier, int * iRugMax, double * nCmiValueHier, double * nCmiValueMax, int * iAdlSum, int * iCpsCode, char * sRugsVersion, char * sDllVersion, int * iError ); ------------------------------------------------------------------ my test code looks like this: import sys, os, rug520 cmi=[0.0] *59 def getrug(mds): results = rug520.RugCalc(mds, 'mcare', '34', 0, cmi) print 'results', results datafile = open('mdsdata.txt') for d in datafile: if d[0]=='B': getrug(d) ------------------------------------------------------------------------ I get this error message File "testrug520.py", line 11, in ? getrug(d) File "testrug520.py", line 5, in getrug results = rug520.RugCalc(mds, 'mcare', '34', 0, cmi) TypeError: in method 'RugCalc', argument 5 of type 'double []' -------------------------------------------------------------------------- I'm guessing that I am not passing a double array to the c code. I cannot change the c code due to politics. I could write a c "wrapper" if I had to, but would rather stay within python or the swig interface definitions if possible/practical. I'm not much of a c programmer; mostly java and python with a little c++. I've looked in the swig docs and tried google, but either have not found it or just don't understand what they are telling me here. --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From cito at online.de Sun Aug 17 09:34:29 2008 From: cito at online.de (Christoph Zwerschke) Date: Sun, 17 Aug 2008 15:34:29 +0200 Subject: Missing exceptions in PEP 3107 In-Reply-To: <3fb64d27-b128-43c8-8e8d-71eea257d328@m44g2000hsc.googlegroups.com> References: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> <8800beb6-c07b-44af-b9ac-fcb00f35dc3a@f36g2000hsa.googlegroups.com> <3fb64d27-b128-43c8-8e8d-71eea257d328@m44g2000hsc.googlegroups.com> Message-ID: Carl Banks schrieb: > You are free to use it for other things. For example, the following > usage is obvious and sensible (insofar as listing exceptions is > sensible): > > def f(x : int) -> int, raises(TypeError) > > Think of the return value annotation as more of a function outcome > annotation. That's fine, but then this should be mentioned in the PEP3107. Instead it says explicitly that the "->" syntax is for "the type of a function's return value". If it's intended to be used in a more general way like you suggested, then the wording used in the PEP is misleading. (The wording "*the* type is problematic anyway, since a Python function can return different types in different situations.) It's still unclear for me whether annotations on thrown exceptions are included in PEP3107 (as per your suggestion), or are not covered by PEP3107 at all (as Duncan suggests), or whether this question has just not yet been settled. -- Christoph From fredrik at pythonware.com Wed Aug 13 18:49:08 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 00:49:08 +0200 Subject: Can't use DB name with dashes using pymssql ??? In-Reply-To: References: <65c3648d0808131354x333a7e0cica29217a26f4ce42@mail.gmail.com> <65c3648d0808131530w29728a78ib646dde89481e656@mail.gmail.com> Message-ID: Fredrik Lundh wrote: > reading the documentation might help: > > http://pymssql.sourceforge.net/troubleshooting.html#dbid also see the SQL server reference documentation (the section "Rules for Regular Identifiers" describes the valid syntax): http://msdn.microsoft.com/en-us/library/ms175874.aspx From nobody at yahoo.com Mon Aug 25 21:20:41 2008 From: nobody at yahoo.com (Andrew) Date: Tue, 26 Aug 2008 01:20:41 GMT Subject: Return a string result with out breaking loop In-Reply-To: <116e4423-44c5-4f13-ab2d-d8040b550a8e@2g2000hsn.googlegroups.com> References: <116e4423-44c5-4f13-ab2d-d8040b550a8e@2g2000hsn.googlegroups.com> Message-ID: Yes I found many examples similiar to that but Yield still produces that error Sorry if I sound Novice but I have no formal education in programming so understanding something takes me a bit longer than most of you guys :-D Ive included a bit more of the function How ever unimportant it may be def watchos(self, path_to_watch="C:\\"): FILE_LIST_DIRECTORY = 0x0001 try: path_to_watch or "." except: path_to_watch = "." path_to_watch = os.path.abspath(path_to_watch) out1 = "Watching %s at %s" % (path_to_watch, time.asctime()) + "\n\n" while 1: #INSERT MORE CODE HERE results = change_handle for action, files in results: full_filename = os.path.join(path_to_watch, files) theact = ACTIONS.get(action, "Unknown") yield str(full_filename) + " " + str(theact) But I am having a hard time wrapping my head around yield... perhaps if it produced more than the same error no matter what I did. I could try and get a bit further Anyway once again I appreciate the help cheers :-) From emmanuel.rivoire at gmail.com Sat Aug 16 06:38:26 2008 From: emmanuel.rivoire at gmail.com (emmanuel.rivoire at gmail.com) Date: Sat, 16 Aug 2008 03:38:26 -0700 (PDT) Subject: How to access an Array and a struct within a struct wrapped by Swig ? Message-ID: Hello, I spent almost a week to be able to embed Python within my C++ game engine. I wrote a mini-tutorial of what I was able to do so far here : http://forums.indiegamer.com/showpost.php?p=169352&postcount=9 At the end of my tutorial, I wrote : "You can do the same with C++ classes, and with structures within structures. Swig can parse & wrap most C/C++ declarations." Gloups, I was so wrong..! :-S It seems that I can read a struct within my struct, but I cannot write values to it. Also, I cannot access the array from within my struct. Any help to achieve this would be very welcome. Here the problem in detail : I'm using Python 2.5.2 & Swig 1.3.36. The structures : struct SIn { int in1, in2; }; struct SPythoned { SIn Inner; float Skill[16]; }; The python code : ======================= def TestObject(o): print(type(o)) print(type(o.Skill)) print(o.Skill) print(type(o.Inner)) print(type(o.Inner.in1)) print(o.Inner.in1) print(o.Inner.in2) o.Inner.in1 = 12 o.Inner.in2 = 17 print(o.Inner.in1) print(o.Inner.in2) ======================= It gives me this output : ======================= _20fd1300_p_float 2 22 2 22 ======================= So althought I can read the value, the "o.Inner.inX = Y" are without effect..! (and checking the value in the object in the C part confirms this). Moreover, if I add these lines : for i in range(16) : print(o.Skill[i]) I get this error : Traceback (most recent call last): File "d:\TE 2008\PyTest.py", line 32, in TestObject print(o.Skill[i]) TypeError: 'PySwigObject' object is unsubscriptable Any idea how to make this work ..? From sjmachin at lexicon.net Tue Aug 5 19:30:04 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 5 Aug 2008 16:30:04 -0700 (PDT) Subject: Trying to fix Invalid CSV File References: <0427191c-d493-442d-ba26-94802bc6062b@v13g2000pro.googlegroups.com> <078f7aad-3bba-49b4-8978-18ac5bfaa6f7@r15g2000prd.googlegroups.com> <6bade254-5001-4ae2-a000-003b84437a76@w1g2000prk.googlegroups.com> <42134ad4-ae35-4d25-94fc-2504d29003e6@r15g2000prh.googlegroups.com> Message-ID: On Aug 5, 6:56 am, Larry Bates wrote: > Ryan Rosario wrote: > > On Aug 4, 8:30 am, Emile van Sebille wrote: > >> John Machin wrote: > >>> On Aug 4, 6:15 pm, Ryan Rosario wrote: > >>>> On Aug 4, 1:01 am, John Machin wrote: > >>>>> On Aug 4, 5:49 pm, Ryan Rosario wrote: > >>>>>> Thanks Emile! Works almost perfectly, but is there some way I can > >>>>>> adapt this to quote fields that contain a comma in them? > >> > > >>> Emile's snippet is pushing it through the csv reading process, to > >>> demonstrate that his series of replaces works (on your *sole* example, > >>> at least). > >> Exactly -- just print out the results of the passed argument: > > >> rec.replace(',"',",'''").replace('",',"''',").replace('"','""').replace("'''",'"') > > >> '123,"Here is some, text ""and some quoted text"" where the quotes > >> should have been doubled",321' > > >> Where it won't work is if any of the field embedded quotes are next to > >> commas. > > >> I'd run it against the file. Presumably, you've got a consistent field > >> count expectation per record. Any resulting record not matching is > >> suspect and will identify records this approach won't address. > > >> There's probably better ways, but sometimes it's fun to create > >> executable line noise. :) > > >> Emile > > > Thanks for your responses. I think John may be right that I am reading > > it a second time. I will take a look at the CSV reader documentation > > and see if that helps. Then once I run it I can see if I need to worry > > about the comma-next-to-quote issue. > > This is a perfect demonstration of why tab delimited files are so much better > than comma and quote delimited. No, it's a perfect demonstration of what happens when a protocol is not followed. > Virtually all software can handle table > delimited as well as comma and quote delimited, but you would have none of these > problems if you had used tab delimited. The chances of tabs being embedded in > most data is virtually nil. > There may be no tabs in *your* data. There is no guarantee that there are no tabs in a VARCHAR(n) column in somebody else's database. I've seen all of \x00, \t, \n, \r and \x1a (Ctrl-Z (EOF in CP/M, *DOS and Windows text files)). The possibilities include (1) Don't check (2) check if '\t' in field and raise an exception (3) silently remove tabs; what do you recommend? From frank at chagford.com Wed Aug 6 01:16:07 2008 From: frank at chagford.com (Frank Millman) Date: Tue, 5 Aug 2008 22:16:07 -0700 (PDT) Subject: Questions about asyncore References: <5d30aad5-cad7-4e47-aa83-277202c70ae2@z72g2000hsb.googlegroups.com> <85afa6f5-431b-42ee-bd31-de5321b0b0f9@l33g2000pri.googlegroups.com> Message-ID: <38da12d9-ccc8-46d4-9026-43bbaf0fd943@m36g2000hse.googlegroups.com> On Aug 5, 6:18 pm, Josiah Carlson wrote: > > Giampaolo already offered up some information, but I will offer these > two little tidbits: > In your first client, your handle_read doesn't handle the case where > you have received multiple packets at one time. That is, imagine that > in your one .read(8192), you received exactly two messages (the prefix > length and the pickle itself times two). The first pass will pick up > the message and handle the data. But unless the socket becomes > readable again, the second message will never be processed. And even > if the socket becomes readable immediately in the next select() call, > the message will be delayed depending on what other sockets are up > to. The asynchat module handles that case just fine. > > As for push() vs. send(); send() returns the number of bytes sent. If > it sends less than the total block of data (which can be the case with > large blocks of data, small TCP/IP windows over a slow connection, or > small TCP/IP buffers), you need to be aware of it and attempt to > resend the remaining. Again, the asynchat module handles that case > just fine with it's .push() method; when it returns, you know that the > data to be transferred will be transferred as long as the connection > stays alive. Without .push(), you need to implement that behavior > yourself (less boilerplate for every subclass = easier maintenance). > > (I normally don't hop on this list to comment, so please cc me on any > replies) > - Josiah > Valuable insights. Much appreciated. Frank From brenNOSPAMbarn at NObrenSPAMbarn.net Sun Aug 31 02:40:35 2008 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Sun, 31 Aug 2008 06:40:35 GMT Subject: Relative imports and "import X as Y" References: Message-ID: Terry Reedy wrote: > >> So, will relative imports in Python 3.0 allow things like >> "import >> ..relative.importing.path as prettyname"? If not, why not? > > Download the latest beta for your system and give it a try. Thanks for the advice, but I'd really rather not deal with installing the entire thing alongside my existing version, possibly causing conflicts in who knows what ways. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From python.leojay at gmail.com Tue Aug 19 08:08:02 2008 From: python.leojay at gmail.com (Leo Jay) Date: Tue, 19 Aug 2008 20:08:02 +0800 Subject: How to stop iteration with __iter__() ? In-Reply-To: <836a8d0a-ce00-40da-bc7c-f390ead0acfe@w7g2000hsa.googlegroups.com> References: <836a8d0a-ce00-40da-bc7c-f390ead0acfe@w7g2000hsa.googlegroups.com> Message-ID: <4e307e0f0808190508r419b7178j9c120eb196467069@mail.gmail.com> On Tue, Aug 19, 2008 at 7:39 PM, ssecorp wrote: > I want a parse a file of the format: > movieId > customerid, grade, date > customerid, grade, date > customerid, grade, date > etc. > > so I could do with open file as reviews and then for line in reviews. > > but first I want to take out the movie id so I use an iterator. > > then i want to iterate through all the rows, but how can I do: > while movie_iter != None: > > because that doesn't work, itraises an exception, StopItreation, which > according to the documentation it should. But catching an exception > can't be the standard way to stop iterating right? > you can use for loop: for line in movie_iter: ... -- Best Regards, Leo Jay From Edwin.Madari at VerizonWireless.com Thu Aug 14 14:55:01 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Thu, 14 Aug 2008 14:55:01 -0400 Subject: Fixed-length text file to database script In-Reply-To: Message-ID: <20080814185513.22BE91E4015@bag.python.org> #your thought is right. ======================================================= def sizes2fields(sizes): d = [] begin = 0 for i in sizes: if begin: end = begin + i else: end = i d.append((begin, end)) begin += i return tuple(d) def slicestring(s, fields): d = [] for i in fields: d.append(s[i[0]:i[1]]) return tuple(d) sizes = [16,4,8,8,8] s = '123456789012345678901234567890123456789012345678901234567890' print slicestring(s, sizes2fields(sizes)) ========================================================== prints out: ('1234567890123456', '7890', '12345678', '90123456', '78901234') hope it helps. thanks Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of Eric Wertman Sent: Thursday, August 14, 2008 1:59 PM To: python-list at python.org Subject: Re: Fixed-length text file to database script I have a machine (PLC) that is dumping its test results into a fixed- length text file. While it has nothing to do with python, I found that creating a MySQL table with the proper fixed length char() fields and using 'load data infile' was the easiest way to deal with that sort of scenario. The python script is the secondary part, that handles the normalization and proper typing of the first table to the second, permanent storage area. But in this case, the more advanced bits are the database and SQL details, and python is just a very convenient way to build the SQL statements and execute them. I'm really not sure what the best way to deal with fixed length data is in python. I might define a list with the field lengths and use a string slicing to get the items.. as a first thought: myfile = '/somewhere/somefile.txt' sizes = [16,4,8,8,8] fd = open(myfile,r) for line in fd.readlines() : idx1 = 0 for l in sizes : -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From gminick at bzt.bzt Mon Aug 18 05:12:16 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Mon, 18 Aug 2008 09:12:16 +0000 (UTC) Subject: online tutorials? References: <6013d717-7c4b-4f34-8f58-d9a1e7387f5c@k37g2000hsf.googlegroups.com> Message-ID: On Sun, 17 Aug 2008 15:53:38 -0700 (PDT), Gits wrote: > I want to learn how to program in python and would like to know if you > guys know of any free online tutorials. Or is it too complicated to > learn from a site or books? Try this: http://linkmingle.com/list/List-of-Free-Online-Python-Books-freebooksandarticles -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From vedrandekovic at yahoo.com Sat Aug 9 07:34:00 2008 From: vedrandekovic at yahoo.com (vedrandekovic at yahoo.com) Date: Sat, 9 Aug 2008 04:34:00 -0700 (PDT) Subject: .cpp to .pyd References: <8a2eea23-1d72-4653-8a8f-c2bb56bc47f6@l64g2000hse.googlegroups.com> <90512f4b-e000-4343-8d5d-4ab92974607b@d77g2000hsb.googlegroups.com> Message-ID: <9a423122-b979-4674-99cc-73623d7d07cd@m44g2000hsc.googlegroups.com> On 9 kol, 01:27, Carl Banks wrote: > On Aug 8, 1:11?pm, vedrandeko... at yahoo.com wrote: > > > Thanks for quick reply.Maybe I'm crazy but I did what you said and I > > stll get the same error :( ?:( ?:( :(.I have boost version 1.34.1 and > > I'm > > running it on Windows XP SP2. > > While you're at it, please post your setup.py > > Carl Banks Hi, Here is my setup.py script: setup(name="MyApp", ext_modules=[ Extension("hello", ["hellomodule.cpp"], libraries = ["boost_python"], include_dirs = ['D:\\Program Files\\boost\\boost_1_34_1\ \boost'], ) ]) Regards, Veki From gagsl-py2 at yahoo.com.ar Wed Aug 27 00:49:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 27 Aug 2008 01:49:11 -0300 Subject: floating point arithmetic References: <6k_sk.92243$6s4.59352@newsfe14.ams2> Message-ID: En Tue, 26 Aug 2008 18:11:30 -0300, fred8865 escribi?: > I understand that due to different arithmetic used in floating points > they are just approximations. Hence, 180/100=1 in my python interpreter. > How can I tackle this problem of inaccurate floating point numbers? > thank you In the current Python versions (2.2 and up), 180/100 means integer division (because both operands are integer). If you want a floating point result, use 180.0/100 or float(some_variable)/100 Starting with Python 3.0, the / operator will return a floating point result ("true division"). So in that Python version, 180/100 gives 1.8 To enable that behavior on Python 2.x, execute "from __future__ import division": >>> 180/100 1 >>> from __future__ import division >>> 180/100 1.8 In any Python version, 180//100 always means integer division: >>> 180//100 1 -- Gabriel Genellina From fauvoritename333 at gmail.com Fri Aug 15 03:54:22 2008 From: fauvoritename333 at gmail.com (fauvoritename333 at gmail.com) Date: Fri, 15 Aug 2008 00:54:22 -0700 (PDT) Subject: EARN MONEY $1500-$5000 PER MONTH Message-ID: EARN MONEY $1500-$5000 PER MONTH SIMPLE ONLINE SURVEY CREATE UR ACCOUNT AND EARN IMMEDIATLY ********************************************************************* http://www.AWSurveys.com/HomeMain.cfm?RefID=sangeetha777 ********************************************************************* From Edwin.Madari at VerizonWireless.com Mon Aug 18 08:50:30 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Mon, 18 Aug 2008 08:50:30 -0400 Subject: Vmware api In-Reply-To: Message-ID: <20080818125043.077F61E4018@bag.python.org> do the ESX server provide any api's or an interactive session may ? thx. Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of Eric Wertman Sent: Sunday, August 17, 2008 2:43 PM To: python-list at python.org Subject: Re: Vmware api I would also be interested in anything anyone can offer. I spend some time looking around, and took a fair stab at using the wsdl2py that comes with The ZSI package. Ultimately I couldn't get anything to work, and reverted to using perl (yuk). I'm interested mostly in interrogating the ESX servers to get configuration and performance data, from external hosts. Thanks! Eric -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From wuwei23 at gmail.com Thu Aug 7 09:12:04 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 7 Aug 2008 06:12:04 -0700 (PDT) Subject: benchmark References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> <489a8cf8$0$11738$9b4e6d93@newsspool1.arcor-online.net> <00aa8eeb$0$20317$c3e8da3@news.astraweb.com> <7d6b3d0d-deb7-4f4b-99a8-1a5b52c1cf1f@h17g2000prg.googlegroups.com> <66bb77c9-a14b-4722-8302-cfa8700656ba@i20g2000prf.googlegroups.com> Message-ID: <21c0d6dc-49a0-4917-b6ce-4773d41ae24f@n33g2000pri.googlegroups.com> On Aug 7, 8:08 pm, M8R-n7v... at mailinator.com wrote: > Really how silly can it be when you suggest someone is taking a > position and tweaking the benchmarks to prove a point [...] I certainly didn't intend to suggest that you had tweaked -anything- to prove your point. I do, however, think there is little value in slavishly implementing the same algorithm in different languages. To constrain a dynamic language by what can be achieved in a static language seemed like such an -amazingly- artificial constraint to me. That you're a fan of Python makes such a decision even more confusing. It's great that you saw value in Python enough to choose it for actual project work. It's a shame you didn't endeavour to understand it well enough before including it in your benchmark. As for it being "disappointing", the real question is: has it been disappointing for you in actual real-world code? Honestly, performance benchmarks seem to be the dick size comparison of programming languages. From fredrik at pythonware.com Thu Aug 14 02:29:26 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 08:29:26 +0200 Subject: Replace Several Items In-Reply-To: References: <513926b0-64fe-4fdc-bb33-bc4b8ad3ab10@a70g2000hsh.googlegroups.com> Message-ID: John Machin wrote: > Clue: The effbot was the original author of the modern (Python 1.6?) > version of the re module. And the author of the "in" and "replace" implementations in Python 2.5. From bearophileHUGS at lycos.com Fri Aug 1 06:25:00 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 1 Aug 2008 03:25:00 -0700 (PDT) Subject: very large dictionary References: <5c5e6d6e-04ef-4340-963f-d3825875b32c@e39g2000hsf.googlegroups.com> <6fftjvFb7ktoU2@mid.uni-berlin.de> Message-ID: Simon Strobl: > I had a file bigrams.py with a content like below: > bigrams = { > ", djy" : 75 , > ", djz" : 57 , > ", djzoom" : 165 , > ", dk" : 28893 , > ", dk.au" : 854 , > ", dk.b." : 3668 , > ... > } > In another file I said: > from bigrams import bigrams Probably there's a limit in the module size here. You can try to change your data format on disk, creating a text file like this: ", djy" 75 ", djz" 57 ", djzoom" 165 ... Then in a module you can create an empty dict, read the lines of the data with: for line in somefile: part, n = .rsplit(" ", 1) somedict[part.strip('"')] = int(n) Otherwise you may have to use a BigTable, a DB, etc. > If there is no other way to do it, I will have to learn how to use > databases in Python. I would prefer to be able to use the same type of > scripts with data of all sizes, though. I understand, I don't know if there are documented limits for the dicts of the 64-bit Python. Bye, bearophile From fredrik at pythonware.com Thu Aug 14 09:28:27 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 15:28:27 +0200 Subject: From Ruby to Python? In-Reply-To: <170543c70808140557h53711636q94c4e11e20367ace@mail.gmail.com> References: <23d7e1bb0808130545w28fb4c04s205c1de2a39dcb36@mail.gmail.com> <23d7e1bb0808140226r63fed22ev2ad83718b591f398@mail.gmail.com> <170543c70808140557h53711636q94c4e11e20367ace@mail.gmail.com> Message-ID: Michael Mabin wrote: > Ruby does have a little of the Perl spirit of 'There's More Than One Way > to Do It'. And you do need shift to Python's 'There's Only One Way To Do > It'. Careful. "import this" says: "There should be one-- and preferably only one --obvious way to do it." Note the use of "obvious". It's about the language getting out of the way so you can focus on your real problem, not restricting what you can do with it. (I mean, seriously, if you find your job so mind-numbingly boring that you need many ways to code trivial problems just to get some variation, maybe it's time to look for a better position?) From joncle at googlemail.com Wed Aug 27 07:56:22 2008 From: joncle at googlemail.com (Jon Clements) Date: Wed, 27 Aug 2008 04:56:22 -0700 (PDT) Subject: finding out the number of rows in a CSV file References: <3aaa109e-9a7e-4d02-8af5-0161251d7678@t54g2000hsg.googlegroups.com> Message-ID: <2a1792cd-64ae-4c41-8c3e-945ab39ffdb1@i76g2000hsf.googlegroups.com> On Aug 27, 12:48 pm, "Simon Brunning" wrote: > 2008/8/27 Jon Clements : > > >> len(list(csv.reader(open('my.csv')))) > > Not the best of ideas if the row size or number of rows is large! > > Manufacture a list, then discard to get its length -- ouch! > > I do try to avoid premature optimization. ;-) > > -- > Cheers, > Simon B. :) From gagsl-py2 at yahoo.com.ar Tue Aug 12 03:05:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Aug 2008 04:05:10 -0300 Subject: How to iterate a sequence, with skipping the first item? References: Message-ID: En Tue, 12 Aug 2008 03:51:17 -0300, ray escribi?: > A container object provides a method that returns an iterator object. > I need to iterate the sequence with that iterator, but need to skip > the first item. I can only iterate the whole sequence with: > for x in container.iterChildren(): > How to skip the first item? It seems that it's a simple question. > Could somebody help me? Thanks. it = container.iterChildren() it.next() # consume first item for x in it: # process remaining items -- Gabriel Genellina From waldemar.osuch at gmail.com Tue Aug 5 14:15:27 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Tue, 5 Aug 2008 11:15:27 -0700 (PDT) Subject: regex search loops instead of findall References: Message-ID: <78a5c121-9d8e-4f37-935c-4047aefc301d@q5g2000prf.googlegroups.com> On Aug 5, 12:06?pm, brad wrote: > Hi guys... I'm trying to make my Python regex code behave like my C++ > regex code. In order to search large strings for *all* occurrences of > the thing I'm searching for, I loop like this in C++: > > void number_search(const std::string& portion, const boost::regex& Numbers) > ? ?{ > > ? ? ?boost::smatch matches; > ? ? ?std::string::const_iterator Start = portion.begin(); > ? ? ?std::string::const_iterator End = portion.end(); > > ? ? ?while (boost::regex_search(Start, End, matches, Numbers)) > ? ? ? ?{ > ? ? ? ?std::cout << matches.str() << std::endl; > ? ? ? ?Start = matches[0].second; > ? ? ? ?} > ? ?} > > I cannot figure out how to do the same in Python. I've read several Py > regex docs, but none of them go into examples of this, although search > seems that it should be able to loop on position according to the docs. > I've resorted to using find_all in python, but that has limitations > (especially when searching for groups) and seems to be a lot less > efficient than search. Any suggestions or example code I can look at? > > I've read these:http://www.amk.ca/python/howto/regexhttp://docs.python.org/lib/module-re.html > > Thanks. re.finditer may help. http://docs.python.org/lib/node46.html From frankrentef at yahoo.com Tue Aug 26 14:33:17 2008 From: frankrentef at yahoo.com (frankrentef) Date: Tue, 26 Aug 2008 11:33:17 -0700 (PDT) Subject: Newbie needs help References: <077ddd87-e944-44e0-935f-2d5cf1368e14@w39g2000prb.googlegroups.com> Message-ID: <253bdfcd-7c15-4013-a6f5-6c886810fee7@q5g2000prf.googlegroups.com> On Aug 26, 11:46?am, frankrentef wrote: > Greetings all, > > I'm wanting to maintain what values in one file and call them in > another. ?The purpose being to keep a single location where url's, > login's and passwords can be maintained, then called as needed from > another file. > > In file #1 I have... > > import time > import os > import sys > > url = 'http://zoo/' > > adminlogin = 'Zebra' > adminpassword = 'Zebra12$' > > --------------------------------------------- > > In file #2 I have the following... > > from cPAMIE import PAMIE > > #Imports - used to setup / control finding files > import time > import os > import sys > import loginout ? ?#name of the file retaining all url/login info > from log import log > > #Create New Pamie Object > ie=PAMIE() > ie=Visible =1 > t=time > > adminlogin (ie,url) > if ie.findText ('Site Status: Active'): > ? ? log ('PASSED -- ADMIN Module - ADMIN Login & Admin Tab Navigation > Successful') > else: > ? ? log ('WARNING -- ADMIN Module Login & Admin Tab Navigation > FAILED') > time.sleep(2) > > What am I doing incorrectly to not have file two log in when > executed. ?All files are in the same directory. ? Keep it simple... > I'm new at this. > > THNX Yes, the first file is named loginout.py Would the second file need something akin to... loginout.admin (ie,url,adminlogin) From cvrebert at gmail.com Thu Aug 28 00:54:23 2008 From: cvrebert at gmail.com (Chris Rebert) Date: Wed, 27 Aug 2008 21:54:23 -0700 Subject: List of modules available for import inside Python? In-Reply-To: References: Message-ID: <47c890dc0808272154y3ac94bayc4652555ee8d8c61@mail.gmail.com> On Wed, Aug 27, 2008 at 9:21 PM, ssecorp wrote: > Is there a way to view all the modules I have available for import > from within Python? > Like writing in the interpreter: > import.modules > > > Also, is there anything like Cpan for Python? The closest thing would be PyPI (the Python Package Index) [http://pypi.python.org/pypi], and easy_install (a package manager for Python) [http://peak.telecommunity.com/DevCenter/EasyInstall]. - Chris ======== Follow the path of the Iguana... Rebertia: http://rebertia.com Blog: http://blog.rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > From rajanikanth at gmail.com Wed Aug 20 17:21:59 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Wed, 20 Aug 2008 14:21:59 -0700 Subject: Detect a sequence of keystrokes in an os independent way Message-ID: <84bdef3c0808201421tf88ef1dg5e828c00091c4ade@mail.gmail.com> Hi! Can somebody tell me if there is an os independent way to detect a sequence of key strokes. For example, I want to start some other program once the user presses a couple of keys: ex: key a and then key b Thanks, Raj -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From nagle at animats.com Mon Aug 18 00:25:11 2008 From: nagle at animats.com (John Nagle) Date: Sun, 17 Aug 2008 21:25:11 -0700 Subject: Python does not get environment variable when using cron. In-Reply-To: References: Message-ID: <48a8f4fe$0$17182$742ec2ed@news.sonic.net> Stephen Cattaneo wrote: > Hello all, > > I am attempting to execute an automated test (written in Python) via > cron. I have to check the HOSTNAME variable as part of the test, oddly > under cron the HOSTNAME environment variable is not in the os.environ > dictionary. I know that cron runs in a subshell that does not have all > of the normally set environment variables. HOSTNAME is not one of those > variables, it is set even in cron's subshell. Why doesn't python get > this variable? Is this a bug in python2.4? Cron doesn't normally use a shell at all. It just runs the requested program in a subprocess. So there's no shell involved, and you don't get a shell-type user environment. If you have a crontab line like 10 3 * * * /usr/bin/python someprogram.py there's no shell. You can try 10 3 * * * /bin/sh /usr/bin/python someprogram.py which will load a shell, which in turn will load Python. Or, in Python, you can use "socket.gethostname()", which will get you the host name used for networking purposes. John Nagle From cfarrell1980 at googlemail.com Tue Aug 26 04:08:31 2008 From: cfarrell1980 at googlemail.com (frankentux) Date: Tue, 26 Aug 2008 01:08:31 -0700 (PDT) Subject: extract text from ods TableCell using odfpy References: Message-ID: <9aa6930f-c680-41bc-8d6e-99ddd36c35a9@l64g2000hse.googlegroups.com> Ok. Sorted it out, but only after taking a round trip over xml.minidom. Here's the working code: #!/usr/bin/python from odf.opendocument import Spreadsheet from odf.opendocument import load from odf.table import TableRow,TableCell from odf.text import P doc = load("/tmp/match_data.ods") d = doc.spreadsheet rows = d.getElementsByType(TableRow) for row in rows[:2]: cells = row.getElementsByType(TableCell) for cell in cells: tps = cell.getElementsByType(P) if len(tps) > 0: for x in tps: print x.firstChild From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 26 06:33:19 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 26 Aug 2008 12:33:19 +0200 Subject: Overwriting property-> can't set attribute In-Reply-To: References: Message-ID: <48b3dbbe$0$17486$426a74cc@news.free.fr> norseman a ?crit : > Gregor Horvath wrote: >> Hi, >> >> why is this code failing? >> >> class B(object): >> pass >> >> B.testattr = property(lambda s:"hallo") >> b = B() >> b.testattr = "test" >> >> >> Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) >> >> /tmp/python-14202ViU.py in () >> 14 B.testattr = property(lambda s:"hallo") >> 15 b = B() >> ---> 16 b.testattr = "test" >> 17 >> 18 >> >> : can't set attribute >> >> -- >> Greg >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > ==================================== > > b = B() # synonyms Not exactly, no. You probably missed the call operator applied to B. (snip erroneous explanation). From half.italian at gmail.com Fri Aug 22 16:51:52 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Fri, 22 Aug 2008 13:51:52 -0700 (PDT) Subject: Seeking ideas for a cron implementation References: Message-ID: <8f607078-e8da-4438-8769-96d011f1544f@j1g2000prb.googlegroups.com> On Aug 22, 1:30?pm, Karthik Gurusamy wrote: > Hi, > > I'm working on a cron like functionality for my application. > The outer loops runs continuously waking every x seconds (say x=180, > 300, ..). > It needs to know what events in cron has expired and for each event do > the work needed. > > It's basically like unix cron or like a calendar application with some > restrictions. The outer loop may come back a lot later and many events > might have missed their schedule -- but this is okay.. We don't have > to worry about missed events (if there were n misses, we just need to > execute call back once). > > Let's take some examples [Let e denotes an event] > e1: hour=1 ?min=30 ? ? ? ? ? ? ? ? ? ? ? ? ? ? # Run every day once at > 1:30 AM > e2: wday=0, hour=1 ?min=0 ? ? ? ? ? ? ? ? ? # run every Monday at 1 AM > e3: month=10, day=10, hour=10 min=0 ?# run on October 10th, 10 AM > every year > > class Cron_Event (object): > ? ? def __init__ (year=None, month=None, day=None, hour=None ..etc) > ? ? ? # ?do init > > class Cron (object): > ? ? def __init__ (): > ? ? ? ? # do init > ? ? def event_add (e): > ? ? ? ? # add an event > ? ? def execute() > ? ? ? ? # see if any events has "expired" .. call it's callback > ? ? ? ? # I'm looking for ideas on how to manage the events here > > From outer loop > cron = Cron() > # create various events like > e1 = Cron_Event(hour=1) > cron.event_add(e1) > e2 = Cron_Event(wday=0, hour=1) > cron.event_add(e2) > > while True: > ? ? sleep x seconds (or wait until woken up) > ? ? cron.execute() > ? ? # do other work.. x may change here > > If I can restrict to hour and minute, it seems manageable as the > interval between two occurrences is a constant. But allowing days like > every Monday or 1st of every month makes things complicated. Moreover > I would like each constraint in e to take on multiple possibilities > (like every day at 1AM, ?2 AM and 4 AM do this). > > I'm looking for solutions that can leverage datetime.datetime > routines. > My current ideas include for each e, track the next time it will fire > (in seconds since epoch as given by time.time()). Once current time > has passed that time, we execute the event. e.g.>>> datetime.datetime.now() > > datetime.datetime(2008, 8, 22, 13, 19, 54, 5567)>>> time.time() > > 1219436401.741966 ? ?<--- compute event's next firing in a format like > this > > > > The problem seems to be how to compute that future point in time (in > seconds since epoch) ?for a generic Cron_Event. > > Say how do I know the exact time in future ?that will satisfy a > constraint like: > ?month=11, wday=1, hour=3, min=30 ? ?# At 3:30 AM on a Tuesday in > November > > Thanks for your thoughts. > > Karthik I only scanned your message, but maybe datetime.timedelta() will help.. >>> import datetime >>> now = datetime.datetime.now() >>> print now 2008-08-22 13:48:49.335225 >>> day = datetime.timedelta(1) >>> print day 1 day, 0:00:00 >>> print now + day 2008-08-23 13:48:49.335225 ~Sean From darcy at druid.net Wed Aug 13 11:04:44 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 13 Aug 2008 11:04:44 -0400 Subject: You advice please In-Reply-To: References: Message-ID: <20080813110444.7b48ddbc.darcy@druid.net> On Wed, 13 Aug 2008 13:47:58 +0200 "?lvaro G. Vicario" wrote: > But I've never came across a Ruby app. Sure, I know Ruby exists and > people are very enthusiastic about it (though they often mistake it with > Ruby on Rails), but that's all. > > Ruby is popular among bloggers but I'm not sure whether it's popular > among developers. Well, I just attended the Agile 2008 conference and sadly Ruby seemed to be much more popular than Python. I found people who had heard of Python and were thinking of trying it but developers were working in Java, C++ and Ruby. Of course, I didn't talk to every one of the 1500 delegates. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From castironpi at gmail.com Mon Aug 4 13:49:45 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 4 Aug 2008 10:49:45 -0700 (PDT) Subject: Limits of Metaprogramming References: <0c56829a-7ad2-4ff2-b225-7981538e7c7a@j22g2000hsf.googlegroups.com> Message-ID: <07c3d5f8-563c-43bc-8772-5eb60de52c82@8g2000hse.googlegroups.com> On Aug 4, 4:48?am, Wilson wrote: > Hi all, > > My problem is that I don't know if it's possible to edit these states > and then write them back to .py. Firstly, if my editing tool was to > create a new state, I would want to create the class (using type) and > attach it to the imported state module somehow. I can't find > > Thanks, > Paul Yes it's possible, using type, but you can't attach it to the module in any persistent way. The next time you load the module, it's back to the way it was. I think this may be the hang-up in your design: if you think about generating lines of code directly from the user's actions, you might stay on the right track. At that point, you can place them in the .py file. Then you can reimport it, or just execute the new lines directly. If this is your class, class Auto54701: def next( self, input ): if( something ): return value1 return value2 Here's how to work with it at the interactive prompt: >>> s= """class Auto54701: ... def next( self, input ): ... if( something ): ... return value1 ... return value2 ... """ >>> s 'class Auto54701:\n def next( self, input ):\n if( something ): \n ret urn value1\n return value2\n' >>> exec( s ) >>> Auto54701 >>> And by the way, you can't use pickle to store types. There needs to be some fleshed-out code to back them up. Two more alternatives, which I can discuss more later, one where you implement code as data, but it ends up being a lot like Python anyway. It only works if your classes' methods are going to be simple, probably sequential if-s and assignments at most. class Auto54701: def next( self, input ): if( something1 ): return value1 elif( something2 ): return value2 elif( something3 ): return value3 elif( something4 ): return value4 return value5 can be stored in data as [ ( something1, value1 ), ( something2, value2 ), ... ] , and just checked in a loop, that you only have in code once, rather than many times. class GenericAuto: def next( self, input ): for something, value in conditionpairs: if( something ): return value return valuen Two, if all your methods will have uniform signatures and closures, you can store class methods as only their co_code objects: >>> C.g.im_func.func_code.co_code 'd\x00\x00S' And fabricate them dynamically into full live types as needed. From martin at see.sig.for.address.invalid Fri Aug 22 19:23:57 2008 From: martin at see.sig.for.address.invalid (Martin Gregorie) Date: Fri, 22 Aug 2008 23:23:57 +0000 (UTC) Subject: The Importance of Terminology's Quality References: <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: On Fri, 22 Aug 2008 22:56:09 +0000, sln wrote: > On Thu, 21 Aug 2008 09:11:48 -0500, rpw3 at rpw3.org (Rob Warnock) wrote: > >>sln at netherlands.com> wrote: >>*IS* raw machine code, *NOT* assembler!! > [snip] > > I don't see the distinction. > Just dissasemble it and find out. > There's a 1:1 relationship between machine code and assembler. Unless its a macro-assembler, of course! > > Each op is a routine in microcode. > That is machine code. Those op routines use machine cycles. > Not necessarily. An awful lot of CPU cycles were used before microcode was introduced. Mainframes and minis designed before about 1970 didn't use or need it and I'm pretty sure that there was no microcode in the original 8/16 bit microprocessors either (6800, 6809, 6502, 8080, 8086, Z80 and friends). The number of clock cycles per instruction isn't a guide either. The only processors I know that got close to 1 cycle/instruction were all RISC, all used large lumps of microcode and were heavily pipelined. By contrast the ICL 1900 series (3rd generation mainframe, no microcode, no pipeline, 24 bit word) averaged 3 clock cycles per instruction. Motorola 6800 and 6809 (no microcode or pipelines either, 1 byte fetch) average 4 - 5 cycles/instruction. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From tjreedy at udel.edu Fri Aug 22 16:17:16 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 22 Aug 2008 16:17:16 -0400 Subject: How to search the Python manuals Message-ID: A number of questions asked here could easily be answered by a quick search of the Python Manuals. A prime example is about the behavior of default parameter values. A recent questioner ended the thread with "The problem with this particular question is that I found it hard to find a query that would give meaningful answers." The following is intended to show how he might have found an answer to this question and, by extension, how others might answer other questions using the 2.4 to 3.0 manuals. (I do not have 2.6 but presume its manual set works the same as the 3.0 set.) -------------------------------------- For WinXP (I have no idea of how the manuals works elsewhere): Open the Python Manuals shortcut. On the left, click [+] for Language Reference (3.0: The Python language reference). Scan the chapter list to find [+] Compound Statements [statements with a header line and indented suite]. Click [+], find Function definitions and click on that. (In 3.0, one can instead directly click Compound Statements since entire chapters rather than just sections are loaded into the right pane.) Click on the right frame/pane to shift 'focus'. Enter control-F and wait (at least a second, be patient) to open a Find box. Enter 'default' (but not too much, such as 'default argument') and click Next. This brings you to the discussion of default parameter values. Either read or continue clicking Next until you come to the boldfaced line that begins the next paragraph: "Default parameter values are evaluated when the function definition is executed." This is followed by an explanation of why one would usually want 'param = None' + body code rather than 'param = []'. ----------------------------------------- It helps if one reads all of the language reference and the first chapters of the library reference on built-ins at least once. They are constantly being improved as mistakes and ambiguities are found and reported. The global module index (top of the left pane) is useful when you know (or maybe just suspect) the name of a module. Terry Jan Reedy From PaulAlexWilson at gmail.com Mon Aug 4 14:57:04 2008 From: PaulAlexWilson at gmail.com (Wilson) Date: Mon, 4 Aug 2008 11:57:04 -0700 (PDT) Subject: Limits of Metaprogramming References: <0c56829a-7ad2-4ff2-b225-7981538e7c7a@j22g2000hsf.googlegroups.com> <07c3d5f8-563c-43bc-8772-5eb60de52c82@8g2000hse.googlegroups.com> Message-ID: On Aug 4, 6:49?pm, castironpi wrote: > On Aug 4, 4:48?am, Wilson wrote: > > > Hi all, > > > My problem is that I don't know if it's possible to edit these states > > and then write them back to .py. Firstly, if my editing tool was to > > create a new state, I would want to create the class (using type) and > > attach it to the imported state module somehow. I can't find > > > Thanks, > > Paul > > Yes it's possible, using type, but you can't attach it to the module > in any persistent way. ?The next time you load the module, it's back > to the way it was. > > I think this may be the hang-up in your design: if you think about > generating lines of code directly from the user's actions, you might > stay on the right track. ?At that point, you can place them in the .py > file. ?Then you can reimport it, or just execute the new lines > directly. > > If this is your class, > > class Auto54701: > ? def next( self, input ): > ? ? ?if( something ): > ? ? ? ?return value1 > ? ? ?return value2 > > Here's how to work with it at the interactive prompt: > > >>> s= """class Auto54701: > > ... ? def next( self, input ): > ... ? ? ?if( something ): > ... ? ? ? ?return value1 > ... ? ? ?return value2 > ... """>>> s > > 'class Auto54701:\n ?def next( self, input ):\n ? ? if( something ): > \n ? ? ? ret > urn value1\n ? ? return value2\n'>>> exec( s ) > >>> Auto54701 > > > > > > And by the way, you can't use pickle to store types. ?There needs to > be some fleshed-out code to back them up. > > Two more alternatives, which I can discuss more later, one where you > implement code as data, but it ends up being a lot like Python > anyway. ?It only works if your classes' methods are going to be > simple, probably sequential if-s and assignments at most. > > class Auto54701: > ? def next( self, input ): > ? ? ?if( something1 ): > ? ? ? ?return value1 > ? ? ?elif( something2 ): > ? ? ? ?return value2 > ? ? ?elif( something3 ): > ? ? ? ?return value3 > ? ? ?elif( something4 ): > ? ? ? ?return value4 > ? ? return value5 > > can be stored in data as > > ? [ ( something1, value1 ), ( something2, value2 ), ... ] > > , and just checked in a loop, that you only have in code once, rather > than many times. > > class GenericAuto: > ? def next( self, input ): > ? ? for something, value in conditionpairs: > ? ? ? if( something ): > ? ? ? ? return value > ? ? return valuen > > Two, if all your methods will have uniform signatures and closures, > you can store class methods as only their co_code objects: > > >>> C.g.im_func.func_code.co_code > > 'd\x00\x00S' > > And fabricate them dynamically into full live types as needed. Thanks for your comments and advice. This second option intrigues me; could you elaborate further, I don't follow you... Thanks Paul From joncle at googlemail.com Wed Aug 27 07:41:19 2008 From: joncle at googlemail.com (Jon Clements) Date: Wed, 27 Aug 2008 04:41:19 -0700 (PDT) Subject: finding out the number of rows in a CSV file References: Message-ID: <3aaa109e-9a7e-4d02-8af5-0161251d7678@t54g2000hsg.googlegroups.com> On Aug 27, 12:29 pm, "Simon Brunning" wrote: > 2008/8/27 SimonPalmer : > > > anyone know how I would find out how many rows are in a csv file? > > > I can't find a method which does this on csv.reader. > > len(list(csv.reader(open('my.csv')))) > > -- > Cheers, > Simon B. > si... at brunningonline.nethttp://www.brunningonline.net/simon/blog/ Not the best of ideas if the row size or number of rows is large! Manufacture a list, then discard to get its length -- ouch! From gh at gregor-horvath.com Fri Aug 22 04:46:14 2008 From: gh at gregor-horvath.com (Gregor Horvath) Date: Fri, 22 Aug 2008 10:46:14 +0200 Subject: Overwriting property-> can't set attribute In-Reply-To: References: Message-ID: Gregor Horvath schrieb: > > why is this code failing? OK I answer myself :-) Because there is not fset function definied in the property. I have to del the attr before rebinding the attributename to another object. -- Greg From george.sakkis at gmail.com Wed Aug 27 11:00:47 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 27 Aug 2008 08:00:47 -0700 (PDT) Subject: iterparse and unicode References: <75d92503-ae3a-4d62-8ed7-cbfd7e5c96c2@25g2000hsx.googlegroups.com> <48b0eda1$0$12942$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <86d6d90c-fa22-4442-a1d9-486d9dd9e69d@m44g2000hsc.googlegroups.com> On Aug 27, 5:42 am, Fredrik Lundh wrote: > George Sakkis wrote: > >> if you meant to write "encode", you can indeed safely do > >> [s.encode('utf8') for s in strings] as long as all strings are returned > >> by an ET implementation. > > > I was replying to the general assertion that "in 2.x ASCII byte > > strings and unicode strings are compatible", not specifically about > > the strings returned by ET. > > that assertion was made in the context of ET. having to unilaterially > change the topic to "win" an argument is pretty lame. I took Stefan's comment as a general statement, not in the context of ET. Feeling the need to keep "defending" ET at this point is, to borrow your words, pretty lame. > and if you really meant to write "decode", you picked a rather stupid > example to support your complaint about ET not returning Unicode -- your > example does work fine for byte strings (whether they contain pure ASCII > or not), but doesn't work at all for arbitrary Unicode strings, because > decoding things that are already decoded makes very little sense (which > explains why that method was removed in 3.0). The thing is, a user might be happily using ET and call "decode" on the returned byte strings as long as the files happen to be all ASCII, without knowing that ET may also return Unicode. Then after some weeks/ months/years a non-ASCII file comes in and the program breaks. As far as I am concerned, it's a documentation issue, nothing more. George From notnorwegian at yahoo.se Mon Aug 11 09:03:13 2008 From: notnorwegian at yahoo.se (maestro) Date: Mon, 11 Aug 2008 06:03:13 -0700 (PDT) Subject: if len(str(a)) == len(str(r)) and isMult(a, r): faster if isMult is slow? Message-ID: If isMult is slow then: if len(str(a)) == len(str(r)) and isMult(a, r): trues.append((a, r)) will be much faster than: if isMult(a, r) and len(str(a)) == len(str(r)): trues.append((a, r)) right? seems obvious but there is no magic going on that wouldn't make this true right? From george.sakkis at gmail.com Wed Aug 27 19:14:25 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 27 Aug 2008 16:14:25 -0700 (PDT) Subject: Identifying the start of good data in a list References: <94524253-b946-4ffa-ae2e-ae6a555d4e7c@a1g2000hsb.googlegroups.com> <9bf75f04-a4bb-42ec-a80c-66ae4d458fd5@e53g2000hsa.googlegroups.com> <605c4e58-51bd-467c-b69d-37abdf3f472f@25g2000hsx.googlegroups.com> Message-ID: <44641f51-eea2-4180-9651-f7b15a981e5b@z66g2000hsc.googlegroups.com> On Aug 27, 5:48 pm, castironpi wrote: > On Aug 27, 4:34 pm, bearophileH... at lycos.com wrote: > > > > > George Sakkis: > > > > This seems the most efficient so far for arbitrary iterables. > > > This one probably scores well with Psyco ;-) > > > def start_good3(seq, good_ones=4): > > n_good = 0 > > pos = 0 > > for el in seq: > > if el: > > if n_good == good_ones: > > return pos - good_ones > > else: > > n_good += 1 > > elif n_good: > > n_good = 0 > > pos += 1 > > if n_good == good_ones: > > return pos - good_ones > > else: > > return -1 > > > Bye, > > bearophile > > There, that's the regular machine for it. Too much thinking in > objects, and you can't even write a linked list anymore, right? And you're still wondering why do people killfile you or think you're a failed AI project... From sjmachin at lexicon.net Fri Aug 29 18:39:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 29 Aug 2008 15:39:02 -0700 (PDT) Subject: Problem with list.insert References: Message-ID: On Aug 29, 5:10 pm, SUBHABRATA wrote: > Dear group, > Thanx for your idea to use dictionary instead of a list. Your code is > more or less, OK, some problems are there, I'll debug them. Well, I > feel the insert problem is coming because of the Hindi thing. It's nothing to do with the Hindi thing. Quite simply, you are inserting into the list over which you are iterating; this is the "a16" in the first and last lines in the following snippet from your code. The result of doing such a thing (in general, mutating a container that is being iterated over) is not defined and can cause all sorts of problems. It can be avoided by iterating over a copy of the container that you want to change. However I suggest that you seriously look at what you are actually trying to achieve, and rewrite it. for word in a16: #MATCHING WITH GIVEN STRING a17=a2.find(word) if a17>-1: print "The word is found in the Source String" a18=a3.index(word) a19=a3[a18] print a19 #INSERTING IN THE LIST OF TARGET STRING a20=a16.insert(a18,a19) This code has several problems: if a8 in a5: a9=a5.index(a8) a10=a5[a9:] a11=re.search("\xe0.*?\n",a10) a12=a11.group() a13=a12[:-1] found.append(a13) elif a8 not in a5: a14=x not_found.append(a14) else: print "Error" found.extend(not_found) (1) If you ever execute that print statement, it means that the end of the universe is nigh -- throw away the else part and replace "elif a8 not in a5" with "else". (2) The statement "found.extend(not_found)" is emitting a very foul aroma. Your "found" list ends up with the translated words followed by the untranslated words -- this is not very useful and you then have to write some weird code to try to untangle it; just build your desired output as you step through the words to be translated. (3) Your "dictionary" is implemented as a string of the whole dictionary contents -- you are linearly searching a long string for each input word. You should load your dictionary file into a Python dictionary, and load it *once* at the start of your program, not once per input sentence. > And Python2.5 is supporting Hindi quite fluently. Python supports any 8-bit encoding to the extent that the platform's console can display the characters correctly. What is the '\xe0'? The PC-ISCII ATR character? Cheers, John From bearophileHUGS at lycos.com Thu Aug 7 15:33:21 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 7 Aug 2008 12:33:21 -0700 (PDT) Subject: benchmark References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> <489a8cf8$0$11738$9b4e6d93@newsspool1.arcor-online.net> <00aa8eeb$0$20317$c3e8da3@news.astraweb.com> <7d6b3d0d-deb7-4f4b-99a8-1a5b52c1cf1f@h17g2000prg.googlegroups.com> <66bb77c9-a14b-4722-8302-cfa8700656ba@i20g2000prf.googlegroups.com> <21c0d6dc-49a0-4917-b6ce-4773d41ae24f@n33g2000pri.googlegroups.com> Message-ID: <27a45001-7057-4994-bfd9-849bbb353775@k13g2000hse.googlegroups.com> alex23: > Honestly, performance benchmarks seem to be the dick size comparison > of programming languages. I don't agree: - benchmarks can show you what language use for your purpose (because there are many languages, and a scientist has to choose the right tool for the job); - it can show where a language implementation needs improvements (for example the Haskell community has improved one of their compilers several times thank to the Shootout, the D community has not yet done the same because the language is in a too much fast evolving phase still, so performance tunings is premature still); - making some code faster for a benchmark can teach you how to make the code faster in general, how CPUs work, or even a some bits of computer science; - if the benchmarks are well chosen and well used, they can show you what are the faster languages (you may say 'the faster implementations', and that's partially true, but some languages have a semantic that allows better or much better optimizations). A computer is a machine useful for many purposes, programming languages allow some users to make the machine act as they want. So computers and languages give some power, they allow you to do something that you can't do without a computer. A language can give you power because it gives you the ability to write less bug-prone code, or it can give you more pre-built modules that allow you to do more things in less time, or it can give you the power to perform computations in less time, to find a specific solution faster. So Python and C give you different kinds of power, and they are both useful. Other languages like D/Java try to become a compromise, they try to give you as much as possible of both "powers" (and they sometimes succeed, a D/Ocaml program may be almost as fast as C, while being on the whole much simpler/safer to write than C code). Bye, bearophile From roy at panix.com Fri Aug 29 10:15:06 2008 From: roy at panix.com (Roy Smith) Date: Fri, 29 Aug 2008 10:15:06 -0400 Subject: [1,2,3] exactly same as [1,2,3,] ? References: Message-ID: Terry Reedy wrote: > Yes, so you can write something like either your second example or > > l = [ > kjasldfjs, > kjsalfj, > ksjdflasj, > ] > > and insert items without worrying about leaving out the comma (less of a > problem with 'horizontal' list), or delete the last line and not have to > worry about deleting the comma on the line before. Exactly. This is one of those little pieces of syntactic sugar which makes python so nice to work with. The alternative is (in C, for example) abominations like this: const char* l[] = {"foo" , "bar" , "baz" }; and even those are not quite as good because you still have to special-case the first entry. From boblatest at yahoo.com Wed Aug 27 16:16:03 2008 From: boblatest at yahoo.com (Robert Latest) Date: 27 Aug 2008 20:16:03 GMT Subject: [SOLVED] How can this script fail? References: <4129c566-de92-433e-bc3f-f1dcbc255c46@m3g2000hsc.googlegroups.com> Message-ID: <6hlr03Fn28dnU1@mid.uni-berlin.de> Dennis Lee Bieber wrote: >> On 2008-08-27 12:37, boblatest at googlemail.com wrote: >> > Got file in dir >> > Found in path: >> > >> > >> >> This looks strange... the same module in two dirs that only >> differ by case ? >> > Even stranger when you take into account that under Windows, path > names are case-preserving/case-ignored -- so Lib and lib are the SAME > directory (I suspect some environment variable has the directory listed > twice with the change in spelling -- PythonPath perhaps?) Please note that one of the lines is the directory that was found in the "os.walk" loop and the other is the one in sys.path -- I just had them printed out on adjacent lines to point out the difference in case. Anyway, the thing was fixed when I put C:\Python25 into the DOS $PATH environment variable. Still strange though. robert From notvalid2 at sbcglobal.net Sat Aug 23 15:45:24 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Sat, 23 Aug 2008 12:45:24 -0700 Subject: Total No. of "Records" in a File? In-Reply-To: References: <1JXrk.20070$89.12375@nlpi069.nbdc.sbc.com> Message-ID: <2MZrk.11343$vn7.9349@flpi147.ffdc.sbc.com> Fredrik Lundh wrote: > W. eWatson wrote: > >> I have an ordinary text file with a CR at the end of a line, and two >> numbers in each line. Is there some way to determine the number of >> lines (records) in the file before I begin reading it? > > In the general case, no. A file is just a bunch of bytes. If you know > that all lines have exactly the same length, you can of course fetch the > file size and divide by the line size, but that doesn't work for > arbitrary files. > > Why do you need to know the number of lines before reading it, btw? > > > Actually, it was a matter of curiosity, and maybe absent mindedness. I was envisioning a program where I might want to run up and down a file a lot, sometimes deleting a record interactively at the request of the user. However, I wanted to keep him alert to the total number of records remaining. However, in retrospect, I more likely do this with files in a folder. I also want him to be able to skip around in the Win OS folder by saying something like go forward 3 files. I'd like not to have to read all the files between the two points. The whole idea needs some more thinking. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 13 08:50:08 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 13 Aug 2008 14:50:08 +0200 Subject: You advice please In-Reply-To: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> Message-ID: <48a2d874$0$4657$426a74cc@news.free.fr> Hussein B a ?crit : > Hey, > I'm a Java/Java EE developer and I'm playing with Python these days. > I like the Python language so much and I like its communities and the > Django framework. > My friends are about to open a Ruby/Rails shop and they are asking me > to join them. > I don't know what, sure I'm not leaving Java, but they are asking me > to stop learning Python and concentrate on Ruby/Rails. > The sad fact (at least to me), Ruby is getting a lot of attention > these days. > Why Python isn't getting this attention although is a much more mature > language and it is used by many big, big names? RoR peoples are good at marketing. And Ruby's object model is probably less alien - at least at first sight - to the Java crowd than Python's object model is. But still, Python seems to get some serious exposure - at least outside of the Java world - these last monthes. > And do I dare to say it is much more charming? > What do you think of Ruby/Rails? do they worth learning and working > with? Both are certainly worth learning. I can't tell about the "working with" part since I never used any of them for anything serious. > Any way, I'm not leaving Python and I will try to study it every time > I get a chance... > Thanks. From redalastor at gmail.com Fri Aug 22 11:24:44 2008 From: redalastor at gmail.com (Dan) Date: Fri, 22 Aug 2008 11:24:44 -0400 Subject: Regex on a huge text Message-ID: I'm looking on how to apply a regex on a pretty huge input text (a file that's a couple of gigabytes). I found finditer which would return results iteratively which is good but it looks like I still need to send a string which would be bigger than my RAM. Is there a way to apply a regex directly on a file? Any help would be appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From matthieu.brucher at gmail.com Thu Aug 7 03:48:28 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Thu, 7 Aug 2008 09:48:28 +0200 Subject: .cpp to .pyd In-Reply-To: References: Message-ID: > I think that my MS visual studio cannot find "boost python", if > that's the problem then can you tell me how can I solve it. > This is very begginer question,but I can't find answer nowhere, and I > don't have any expirience with Microsoft products. Hi, Put Boost in your include path (options of Visual Studio). Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher From sjmachin at lexicon.net Tue Aug 26 20:52:00 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 26 Aug 2008 17:52:00 -0700 (PDT) Subject: Date Comparison and Manipulation Functions? References: Message-ID: <6cdf0c14-80b6-42c4-8047-8c01fda8b87c@r15g2000prh.googlegroups.com> On Aug 27, 10:21 am, "W. eWatson" wrote: > > I'm using IDLE for Python 2.4, and put pfydate distribution in > C:\Python24\Lib\site-packages\pfydate, as required by the > page. > How to install pyfdate. > > Save pyfdate.py into your PythonNN/Lib/site-packages directory. > I copied it into C:\Python24\Lib\site-packages\pfydate If that means that you ended up with C:\Python24\Lib\site-packages\pfydate\pyfdate.py then you have *not* followed the instructions "Save pyfdate.py into your PythonNN/Lib/site-packages directory". You need to end up with C:\Python24\Lib\site-packages\pyfdate.py If in doubt, get to a command prompt and type dir C:\Python24\Lib\site-packages\pfydate* and tell us what you see. > > Execution in IDLE produced: > --------------------------------- > Traceback (most recent call last): > File > "C:\Sandia_Meteors\Improved_Sentinel\Sentinel_Playground\date_example.py", > line 1, in ? > from pyfdate import * > ImportError: No module named pyfdate > --------------------------------- > Looking in the Path Browser, I don't see pyfdate. I see PIL package and > scipy package. From shyamala1010 at gmail.com Wed Aug 20 18:40:24 2008 From: shyamala1010 at gmail.com (syam) Date: Wed, 20 Aug 2008 15:40:24 -0700 (PDT) Subject: shyam Message-ID: E-mail:shyamala1010 at gmail.com web - http://www.shyamalaindian.blogspot.com/ From fredrik at pythonware.com Thu Aug 14 11:41:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 17:41:13 +0200 Subject: a question about mysqldb In-Reply-To: <9b1bd962-9e03-43bd-8c0b-2c6c1cccc95d@x16g2000prn.googlegroups.com> References: <9b1bd962-9e03-43bd-8c0b-2c6c1cccc95d@x16g2000prn.googlegroups.com> Message-ID: Evan wrote: > a simple problem but I do not know why...:(, could anyone help me? > > MySQLdb nominally uses just the %s placeholder style, in my script, i > got error if you want to use placeholder(%s) for table name: Placeholders are supposed to be used for *values*, not other parts of the SQL statement. To insert table names, column names and stuff like that, use Python-level formatting. try doing: table = "tmp" sql = "select tID,tNote from " + table + " where tID=%s" param = [1] s.dbptr.execute(sql, param) > But sql worked but the I got no query result: > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ > >>> >>> str="select tID,tNote from tmp where %s = %s" > >>> >>> e=["tID",int(1)] the string value "tID" doesn't match an integer with the value 1, so that's expected. From mwojc at NOSPAMp.lodz.pl Tue Aug 12 17:17:49 2008 From: mwojc at NOSPAMp.lodz.pl (mwojc) Date: Tue, 12 Aug 2008 23:17:49 +0200 Subject: __getattr__, __setattr__ and pickle References: <48a1cdce$0$14748$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > mwojc a ?crit : >> Hi! >> My class with implemented __getattr__ and __setattr__ methods cannot be >> pickled because of the Error: >> >> ====================================================================== >> ERROR: testPickle (__main__.TestDeffnet2WithBiases) >> ---------------------------------------------------------------------- >> Traceback (most recent call last): >> File "deffnet.py", line 246, in testPickle >> cPickle.dump(self.denet, file) >> TypeError: 'NoneType' object is not callable >> >> ---------------------------------------------------------------------- >> >> Is there an obvious reason i don't know, which prevents pickling with >> those methods (if i comment them out the pickling test passes)? >> >> I'm using Python 2.4.4 on Gentoo Linux. The mentioned methods goes as >> follows: >> >> def __setattr__(self, name, value): >> if name == 'weights': >> j = 0 >> for net in self.nets: >> w1 = self.wmarks[j] >> w2 = self.wmarks[j+1] >> net.weights = value[w1:w2] >> j += 1 >> else: >> self.__dict__[name] = value >> >> def __getattr__(self, name): >> if name == 'weights': >> j = 0 >> for net in self.nets: >> w1 = self.wmarks[j] >> w2 = self.wmarks[j+1] >> self._weights[w1:w2] = net.weights >> j += 1 >> return self._weights > > __getattr__ should raise an AttributeError when name != 'weight' instead > of (implicitely) returning None. pickle looks for a couple special > method in your object[1], and it looks like it doesn't bother to check > if what it found was really callable. Yes, raising AttributeError helped. Thanks! > > FWIW, you'd be better using a property instead of __getattr__ / > __setattr__ if possible. You're probably right again, in this case it's better to use property. > And while we're at it, you dont need to > manually take care of your index in the for loop - you can use > enumerate(iterable) instead: > > for j, net in enumerate(self.nets): > w1 = self.wmarks[j] > w2 = self.wmarks[j+1] > self._weights[w1:w2] = net.weights > return self._weights > Sometimes i use manual handling of index because i'm convinced that enumeration is a bit slower than this. But i'm not really sure about it... Thanks again. Greetings, -- Marek From python.leojay at gmail.com Fri Aug 22 13:47:23 2008 From: python.leojay at gmail.com (Leo Jay) Date: Sat, 23 Aug 2008 01:47:23 +0800 Subject: How to read and write the same socket in different threads? Message-ID: <4e307e0f0808221047p739effb3pd81bfacfe3126b93@mail.gmail.com> I'd like to read and write the same socket in different threads. one thread is only used to read from the socket, and the other is only used to write to the socket. But I always get a 10022 'Invalid argument' exception. Anyone knows why? I'm using windows xp. my source code is here: http://pastebin.com/m23e633a2 and the stack trace is: C:\WINDOWS\system32\cmd.exe /c python "main.py" Exception in thread Thread-1: Traceback (most recent call last): File "c:\Python25\lib\threading.py", line 486, in __bootstrap_inner self.run() File "c:\Python25\lib\threading.py", line 446, in run self.__target(*self.__args, **self.__kwargs) File "main.py", line 7, in read_socket sock.connect(('127.0.0.1', remoteport)) File "", line 1, in connect error: (10022, 'Invalid argument') Exception in thread Thread-3: Traceback (most recent call last): File "c:\Python25\lib\threading.py", line 486, in __bootstrap_inner self.run() File "c:\Python25\lib\threading.py", line 446, in run self.__target(*self.__args, **self.__kwargs) File "main.py", line 7, in read_socket sock.connect(('127.0.0.1', remoteport)) File "", line 1, in connect error: (10022, 'Invalid argument') If i replace the 'args' in line 39 with '(socket(), remoteport)', which means use a different socket to connect to the remote port, the program works. But if the first element of the tuple is 's', the program doesn't work. Is it possible to read and write the same socket in different threads? Thanks in advance. -- Best Regards, Leo Jay From fredrik at pythonware.com Wed Aug 20 17:46:45 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 20 Aug 2008 23:46:45 +0200 Subject: Negative integers In-Reply-To: References: Message-ID: johnewing wrote: > I am trying to figure out how to test if two numbers are of the same > sign (both positive or both negative). I have tried > > abs(x) / x == abs(y) / y > > but that fails when one of the numbers is 0. I'm sure that there is > an easy way to do this. Any suggestions? (a < 0) == (b < 0) From geonomica at gmail.com Sat Aug 30 08:33:18 2008 From: geonomica at gmail.com (gianluca) Date: Sat, 30 Aug 2008 05:33:18 -0700 (PDT) Subject: __stack_chk_fail_local References: <40a21602-a613-484b-aae4-4643dab9e146@8g2000hse.googlegroups.com> Message-ID: <1217e9d2-b81f-471d-854e-4f39ad9b40f5@x35g2000hsb.googlegroups.com> On 30 Ago, 12:05, "Marco Bizzarri" wrote: > On Fri, Aug 29, 2008 at 7:53 PM, gianluca wrote: > > hy list, > > I've built _libfoo.so and libfoo.py library with swig and I've copied > > in /usr/lib/python2.5/lib-dynload/ but when import the module > > >>>import libfoo > > > I've that message > > > Traceback (most recent call last): > > File "", line 1, in > > ImportError: /usr/lib/python2.5/lib-dynload/_libfoo.so: undefined > > symbol: __stack_chk_fail_local > > > Could anybody help me? > > > gianluca > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Have you tried to use ldd against the _libfoo.so to check if it is > able to get all the libraries it needs? > > Regards > Marco > > -- > Marco Bizzarrihttp://iliveinpisa.blogspot.com/ I've tried with ldd and the library aren't loaded. I don't use my *.i interface so is quite difficult modify it (realy, the libraru is supplied with make). Any suggests? gianluca From musiccomposition at gmail.com Mon Aug 25 21:52:24 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 25 Aug 2008 18:52:24 -0700 (PDT) Subject: Enhanced property decorator References: <9e36cdd4-7d66-4eae-aa60-1782e500abfe@34g2000hsh.googlegroups.com> Message-ID: <25ffaf6d-1bcb-4f6b-8074-a1ca82a1e6a8@d1g2000hsg.googlegroups.com> On Aug 25, 8:45?pm, Daniel wrote: > I've often been frustrated by the inability of the built-in property > descriptor to handle anything other than a read-only property when > used as a decorator. Furthermore, read/write/delete properties take > their doc-string and property definition at a non-intuitive and > awkward place (after the getter/setter/delter functions). The > following are three possible solutions to this problem (inspired by > messagehttp://groups.google.com/group/comp.lang.python/msg/9a56da7ca8ceb7c7). > I don't like the solution in that thread because it uses apply() which > will go away in Python 3. I didn't read the rest of the thread, but I think Python 2.6 may have want you want: class A(object): @property def my_prop(): return self._prop @my_prop.setter def my_prop(prop): self._prop = prop @my_prop.deleter def my_prop(): del self._prop From timid.gentoo at gmail.com Sun Aug 10 16:24:00 2008 From: timid.gentoo at gmail.com (Spitfire) Date: Sun, 10 Aug 2008 16:24:00 -0400 Subject: parsing XSD References: <489ee8e9$0$12948$9b4e6d93@newsspool2.arcor-online.net> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Stefan, Stefan Behnel wrote: | BTW, if you want to write XML handling code that lets you understand what you | are doing, try ElementTree or lxml. lxml also has support for XML Schema, in | case you want to do more than parsing with it. | | Stefan Thanks! - -- _ _ _]{5pitph!r3}[_ _ _ __________________________________________________ ?I'm smart enough to know that I'm dumb.? ~ - Richard P Feynman -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFIn05gKVWYDRRZoskRAm0aAKCk3Sc7amPz16t1fhBaeSMvqJtnEgCffLL2 YHO0ahXp4cAese+zPSrzyH0= =yQIO -----END PGP SIGNATURE----- From PaulAlexWilson at gmail.com Mon Aug 4 08:39:22 2008 From: PaulAlexWilson at gmail.com (Wilson) Date: Mon, 4 Aug 2008 05:39:22 -0700 (PDT) Subject: Limits of Metaprogramming References: <0c56829a-7ad2-4ff2-b225-7981538e7c7a@j22g2000hsf.googlegroups.com> <0b5bd851-0e5c-4aef-bee6-6faa7c82a1e1@l64g2000hse.googlegroups.com> Message-ID: On 4 Aug, 12:55, Jeff wrote: > You could write a class composed of states and then use the pickle > module to serialize it to disk. Thanks Jeff. I guess this is my intermediary format! From danb_83 at yahoo.com Thu Aug 7 00:09:30 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 6 Aug 2008 21:09:30 -0700 (PDT) Subject: random numbers according to user defined distribution ?? References: <00aa4a9a$0$20317$c3e8da3@news.astraweb.com> Message-ID: <41695897-6fec-4de1-ae8d-e8ec31510476@j1g2000prb.googlegroups.com> On Aug 6, 8:26?pm, Steven D'Aprano wrote: > On Wed, 06 Aug 2008 15:02:37 -0700, Alex wrote: > > Hi everybody, > > > I wonder if it is possible in python to produce random numbers according > > to a user defined distribution? Unfortunately the random module does not > > contain the distribution I need :-( > > This is a strange question. Of course you can -- just write a function to > do so! Here's some easy ones to get you started: > ... > > There's no general way to create a random function for an arbitrary > distribution. I don't think there's a general way to *describe* an > arbitrary random distribution. What about the quantile function? From mh at pixar.com Thu Aug 28 21:24:38 2008 From: mh at pixar.com (mh at pixar.com) Date: Fri, 29 Aug 2008 01:24:38 GMT Subject: iterating over two arrays in parallel? Message-ID: I want to interate over two arrays in parallel, something like this: a=[1,2,3] b=[4,5,6] for i,j in a,b: print i,j where i,j would be 1,4, 2,5, 3,6 etc. Is this possible? Many TIA! Mark -- Mark Harrison Pixar Animation Studios From paul.hankin at gmail.com Sat Aug 2 14:58:05 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 2 Aug 2008 11:58:05 -0700 (PDT) Subject: Searching for some kind of data type References: <33d13c77-e710-4951-a559-7ea8b6e15287@26g2000hsk.googlegroups.com> Message-ID: <61fc0a0b-2c87-4e7b-8b9a-5dd04e30226b@z66g2000hsc.googlegroups.com> On Aug 2, 1:12?pm, "Giampaolo Rodola'" wrote: > Hi, > for an FTP server I wrote I'd need to group the FTP commands in one > table that defines the command itself, the syntax string, required > permission, whether it requires authorization, whether it takes > argument and whether there's a need to validate the path from the > argument. > The more obvious way I found to do that is something like this: > > class CommandProperty: > ? ? def __init__(self, perm, auth_needed, arg_needed, check_path, > syntax): > ? ? ? ? self.perm = perm > ? ? ? ? self.auth_needed = auth_needed > ? ? ? ? self.arg_needed = arg_needed > ? ? ? ? self.check_path = check_path > ? ? ? ? self.syntax = syntax > > ftp_cmds = { > ? ? "ABOR" : CommandProperty(perm=None, auth_needed=True, > arg_needed=False, check_path=False, syntax="ABOR (abort transfer)."), > ? ? "APPE" : CommandProperty(perm='a', ?auth_needed=True, > arg_needed=True, ?check_path=True, ?syntax="APPE file-name > (append data to an existent file)."), > ? ? "CDUP" : CommandProperty(perm='e', > auth_needed=True,arg_needed=False, check_path=False, syntax="CDUP (go > to parentdirectory)."), > ? ? ... > ? ? ... > ? ? ... > ? ? } > > ...but I find it somewhat redundant and... "ugly". > I was wondering if there was some kind of data type which could better > fit such purpose or if someone could suggest me some other approach to > do this same thing. Maybe using a dictionary is not the better choice > here. How about something like this? The idea is to summarize the command table, then construct the ftp command dictionary programatically from it. cmd_table = dict( ABOR='-AR- (abort transfer)', APPE='aARP file-name (append data to a file)', CDUP='eA-- (go to parent directory)', ... ) The first block of four characters give the options: permission, whether authentication is needed, whether the argument is required, and whether the path needs checking. Permission is the permission letter or - (for none), A or - for authentication, R or - for argument required, and - or P for path required. Then the help text follows (with the command name omitted since it's redundant). Turning these into CommandProperty's is straightforward (untested code): ftp_commands = {} for cmd, descriptor in cmd_table.iteritems(): options, help = descriptor.split(' ', 1) options = [None if opt == '-' else opt for opt in options] perm, auth, arg, path = options assert perm is None or perm in 'ae...' assert auth is None or auth == 'A' assert arg is None or arg == 'R' assert path is None or path == 'P' ftp_commands[cmd] = CommandProperty(perm=perm, auth_required=auth, arg_required=arg, check_path=path, syntax = '%s %s' % (cmd, help)) -- Paul Hankin From rweir at ertius.org Wed Aug 13 02:21:00 2008 From: rweir at ertius.org (Rob Weir) Date: Wed, 13 Aug 2008 16:21:00 +1000 Subject: Checking a file's time stamp -- followup References: <48A2790A.6080108@it.uu.se> Message-ID: <877ialtoz7.fsf@hypercube.ertius.org> On 13 Aug 2008, Virgil Stokes wrote: > Is it possible to change the time stamp of a file (Win2K platform)? If > yes, how? os.utime, http://docs.python.org/lib/os-file-dir.html. -- -rob From castironpi at gmail.com Fri Aug 22 12:44:42 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 22 Aug 2008 09:44:42 -0700 (PDT) Subject: property() usage - is this as good as it gets? References: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> Message-ID: <421a4af5-0421-4d63-8aa2-b6097fcc83f3@a70g2000hsh.googlegroups.com> On Aug 22, 11:18?am, David Moss wrote: > Hi, > > I want to manage and control access to several important attributes in > a class and override the behaviour of some of them in various > subclasses. > > Below is a stripped version of how I've implemented this in my current > bit of work. > > It works well enough, but I can't help feeling there a cleaner more > readable way of doing this (with less duplication, etc). > > Is this as good as it gets or can this be refined and improved > especially if I was to add in a couple more attributes some fairly > complex over-ride logic? > > #!/usr/bin/env python > > class A(object): > ? ? def __init__(self): > ? ? ? ? self._x = None > ? ? ? ? self._y = None > > ? ? def _set_x(self, value): > ? ? ? ? self._x = value > > ? ? def _get_x(self): > ? ? ? ? return self._x > > ? ? x = property(_get_x, _set_x) > > ? ? def _set_y(self, value): > ? ? ? ? self._y = value > > ? ? def _get_y(self): > ? ? ? ? return self._y > > ? ? y = property(_get_y, _set_y) Within the bounds of Python, that's it. In the cases where you're not executing code on 'get' or 'set', it might be possible to have a default getter/setter, that just sets the value of a variable name. This keeps your interface the same across inheritance and changes. Possible to have it assign a default value too. def _set_z(self, value): self._z = value #def _get_z(self): # return self._z z = property( True, _set_z ) #still gets self._z Unless, you are looking at something 'periodic' or regular. From something I'm working on: def _getbalance( self ): return self._tree.geti( self.where+ self.lookup[ 'balance' ] ) def _getparent( self ): return self._tree.getI( self.where+ self.lookup[ 'parent' ] ) Where 'balance' and 'parent' could both come from something generic: balance= property( tree_lookup( 'balance' ) ) parent= property( tree_lookup( 'parent' ) ) They would have to take care to define 'self' properly and everything. From __peter__ at web.de Mon Aug 25 13:08:05 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 25 Aug 2008 19:08:05 +0200 Subject: Why do all my loggers start auto-disabled? References: <13922a38-da45-4608-9bab-2bc153a07eae@k7g2000hsd.googlegroups.com> Message-ID: jonfroehlich wrote: > I am a relative newbie to Python and its logging infrastructure; > however, I have programmed extensively with Java/C# and log4j and > log4net. That, I suppose, could be the root of my problem :) > > I am trying to setup one logger per module (as this is roughly > analogous to how I've used log4j/log4net). However, I've noticed that > my loggers have the disabled flag set to true (more accurately, 1) > when they are initialized. For each logger, do I have to force > disabled = False? To make this more concrete, here is an example. > > In example.py: > > import logging > import logging.config > > _log = logging.getLogger("prediction.predict") > > def main(): > logging.config.fileConfig('logconfig.conf') > _log.warn("test warning!") > > if __name__ == "__main__": > main() > > Unfortunately, this does not print out "test warning!" and if I put a > breakpoint at the _log.warn("test warning!") line, _log.disabled > equals 1. If I change main to: > > def main(): > logging.config.fileConfig('predict_logconfig.conf') > _log.disabled = False > _log.warn("test warning!") > > It works! So, am I doing something wrong or do I always have to force > my loggers to be enabled? Should I update my configuration file so > that loggers start as enabled? Here is my config file I think you have to put the logger into your config file to avoid that it will be disabled by fileConfig(): > (logconfig.conf): > > [formatters] > keys: detailed,simple > > [handlers] > keys: console,filelog [loggers] keys: root, predict # ... [logger_predict] qualname: prediction.predict handlers: Peter From rajanikanth at gmail.com Thu Aug 28 01:35:02 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Wed, 27 Aug 2008 22:35:02 -0700 Subject: Python on Mac In-Reply-To: <37e1fa620455c7c04b3d8b000e30770e@85.18.140.153> References: <37e1fa620455c7c04b3d8b000e30770e@85.18.140.153> Message-ID: <84bdef3c0808272235o1e5fa1fdu2c49fbba2a5c4f08@mail.gmail.com> Hi! Luca, All you need to do is in the final step of (configure, make and make install), use make altinstall instead of make install. That way, your original python implementation won't be affected. Thanks, Raj On Wed, Aug 27, 2008 at 7:46 AM, wrote: > Hi All. > I'm really new in the python world, so, sorry if my question is particulary > stupid. > I've just installed on my system (Mac OS X 10.4 PPC) the python version > 2.5.2 and all works fine. > My next step is to install the version 3.0 (when available). I've read > somewhere that this version will break the backward compatibility with the > 2.x series. I know that several Mac apps (such as Xcode developement > environment) use python for its internal functionalities. Now, my question > is: what will appen to the Mac apps if I install the version 3.0 of python? > Is it safe to install this version without to compromise the behaviour of > the system? > > Thanks in advance for any answer and, again, sorry if my question is > particulary stupid, I will learn with time. > > Luca. > > -- > Email.it, the professional e-mail, gratis per te: http://www.email.it/f > > Sponsor: > Libera la tua voglia di giocare. Scarica Videogames sul cellulare! > Clicca qui: http://adv.email.it/cgi-bin/foclick.cgi?mid=7753&d=20080827 > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From bedouglas at earthlink.net Fri Aug 29 11:16:12 2008 From: bedouglas at earthlink.net (bruce) Date: Fri, 29 Aug 2008 08:16:12 -0700 Subject: No subject Message-ID: <0a6201c909ea$2cd566b0$0301a8c0@tmesa.com> Hi. I'm using mechanize to parse a page/site that uses the meta http-equiv tag in order to perform a refresh/redirect of the page. I've tried a number of settings, and read different posts on various threads, but seem to be missing something. the test.html page is the page that the url returns, however, i was expecting the test.py app to go ahead and perform the redirect/refresh automatically. does the page (test.html) need to be completely valid html? Any thoughts on what's screwed up here?? thanks ---------------------------------------------------- test.py -------- import re import libxml2dom import urllib import urllib2 import sys, string from mechanize import Browser import mechanize #import tidy import os.path import cookielib from libxml2dom import Node from libxml2dom import NodeList import subprocess import time ######################## # # Parse pricegrabber.com ######################## cj = "p" COOKIEFILE = 'cookies.lwp' #cookielib = 1 urlopen = urllib2.urlopen #cj = urllib2.cookielib.LWPCookieJar() cj = cookielib.LWPCookieJar() Request = urllib2.Request br = Browser() br2 = Browser() if cj != None: print "sss" #install the CookieJar for the default CookieProcessor if os.path.isfile(COOKIEFILE): cj.load(COOKIEFILE) print "foo\n" if cookielib: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) print "foo2\n" user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values1 = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } url="http://schedule.psu.edu/" #======================================= if __name__ == "__main__": # main app txdata = None #---------------------------- ##br.set_cookiejar(cj) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.set_handle_refresh(True) br.addheaders = [('User-Agent', 'Firefox')] #url=str(url)+str("act_main_search.cfm")+"?" #url=url+"Semester=FALL%202008%20%20%20&" #url=url+"CrseLoc=OZ%3A%3AAbington%20Campus&" #url=url+"CECrseLoc=AllOZ%3A%3AAbington%20Campus&" #url=url+"CourseAbbrev=ACCTG&CourseNum=&CrseAlpha=&Search=View+schedule" #url="http://schedule.psu.edu/act_main_search.cfm?Semester=FALL%202008%20%20 %20%20&CrseLoc=OZ%3A%3AAbington%20Campus&CECrseLoc=AllOZ%3A%3AAbington%20Cam pus&CourseAbbrev=ACCTG&CourseNum=&CrseAlpha=" url="http://schedule.psu.edu/act_main_search.cfm?Semester=FALL%202008%20%20% 20%20&CrseLoc=OZ%3A%3AAbington%20Campus&CECrseLoc=AllOZ%3A%3AAbington%20Camp us&CourseAbbrev=ACCTG&CourseNum=&CrseAlpha=&CFID=543143&CFTOKEN=71842529" print "url =",url br.open(url) #cj.save(COOKIEFILE) # resave cookies res = br.response() # this is a copy of response s = res.read() print "slen=",len(s) print s ========================================= test.html Tech Type --------------------------------------------------------- sys.exit() From Graham.Dumpleton at gmail.com Mon Aug 25 02:44:54 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 24 Aug 2008 23:44:54 -0700 (PDT) Subject: How to check in CGI if client disconnected References: <75a68632-1f47-48d7-a890-fe1b92484c2a@w24g2000prd.googlegroups.com> <57942430-2040-4a42-8d3b-f9248aee21be@r35g2000prm.googlegroups.com> Message-ID: On Aug 25, 4:26?pm, Vishal wrote: > Hi, > > ? Thanks for the replies. In my case, the cgi is sending a large file > to the client. In case the the stop button is pressed on the browser > to cancel the download, i want to do some cleanup action. It's all one- > way transfer in this case, so i can't expect the client to send > anything to me. I read somewhere that apache sends the SIGTERM signal > to a cgi when the client disconnects. However, my cgi is not getting > the signal - is there a way to have the cgi catch and handle the > SIGTERM? > > I tried using the signal module > > --- > def sigtermHandler(signum, frame): > ? ? # do some cleanup > > signal.signal(signal.SIGTERM, sigtermHandler) > > --- > > But even this doesn't work. Have you considered simply checking to see if the amount of POST content read matches the inbound Content-Length specified in the CGI environment. If your processing of POST content finds less than what was meant to be sent, then likely that the client browser aborted request before all content could be sent. Graham > Regards, > > -vishal. > On Aug 25, 2:58?am, "Gabriel Genellina" > wrote: > > > En Sun, 24 Aug 2008 17:51:36 -0300, Wojtek Walczak escribi?: > > > > On Sun, 24 Aug 2008 17:21:52 -0300, Gabriel Genellina wrote: > > >>> ? ?I am writing a CGI to serve files to the caller. I was wondering if > > >>> there is any way to tell in my CGI if the client browser is still > > >>> connected. If it is not, i want to execute some special code before > > >>> exiting. > > > >>> ? ?Is there any way to do this? Any help on this is appreciated :) > > > >> I don't think so. A CGI script runs once per request, and exits. The server may find that client disconnected, but that may happen after the script finished. > > > > I am not a web developer, but I think that the only way is to > > > set a timeout on server side. You can't be sure that the client > > > disconnected, but you can stop CGI script if there's no > > > action on client side for too long. > > > Which kind of client action? Every link clicked or form submitted generates a different request that triggers a CGI script; the script starts, reads its parameters, do its task, and exits. There is no "long running process" in CGI - the whole "world" must be recreated on each request (a total waste of resources, sure). > > > If processing takes so much time, it's better to assign it a "ticket" - the user may come back later and see if its "ticket" has been finished, or the system may send an email telling him. > > > -- > > Gabriel Genellina From sjmachin at lexicon.net Wed Aug 6 17:06:30 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 6 Aug 2008 14:06:30 -0700 (PDT) Subject: Parsing of a file References: <760c7cd4-5a23-4e8e-801d-31670afd050b@l42g2000hsc.googlegroups.com> Message-ID: <91b5cd11-1bb6-4715-8964-85afc77862d1@1g2000pre.googlegroups.com> On Aug 7, 6:02 am, Mike Driscoll wrote: > On Aug 6, 1:55 pm, Tommy Grav wrote: > > > > > I have a file with the format > > > Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames > > 5 Set 1 > > Field f31448: Ra=20:24:58.13 Dec=+79:39:43.9 MJD=53370.06811620 Frames > > 5 Set 2 > > Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames > > 5 Set 3 > > Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames > > 5 Set 4 > > Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames > > 5 Set 5 > > Field f30560: Ra=20:27:01.82 Dec=+74:47:50.3 MJD=53370.06860400 Frames > > 5 Set 6 > > Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames > > 5 Set 7 > > Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames > > 5 Set 8 > > Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames > > 5 Set 9 > > Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames > > 5 Set 10 > > > I would like to parse this file by extracting the field id, ra, dec > > and mjd for each line. It is > > not, however, certain that the width of each value of the field id, > > ra, dec or mjd is the same > > in each line. Is there a way to do this such that even if there was a > > line where Ra=****** and > > MJD=******** was swapped it would be parsed correctly? > > > Cheers > > Tommy > > I'm sure Python can handle this. Try the PyParsing module or learn > Python regular expression syntax. > > http://pyparsing.wikispaces.com/ > > You could probably do it very crudely by just iterating over each line > and then using the string's find() method. > Perhaps you and the OP could spend some time becoming familiar with built-in functions and str methods. In particular, str.split is your friend: C:\junk>type tommy_grav.py # Look, Ma, no imports! guff = """\ Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames 5 Set 1 Field f31448: MJD=53370.06811620123 Dec=+79:39:43.9 Ra=20:24:58.13 Frames 5 Set 2 Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames 5 Set 3 Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames 5 Set 4 Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames 5 Set 5 Field f30560: Ra=20:27:01.82 Dec=+74:47:50.3 MJD=53370.06860400 Frames 5 Set 6 Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames 5 Set 7 Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames 5 Set 8 Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames 5 Set 9 Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames 5 Set 10 """ is_angle = { 'ra': True, 'dec': True, 'mjd': False, } def convert_angle(text): deg, min, sec = map(float, text.split(':')) return (sec / 60. + min) / 60. + deg def parse_line(line): t = line.split() assert t[0].lower() == 'field' assert t[1].startswith('f') assert t[1].endswith(':') field_id = t[1].rstrip(':') rdict = {} for f in t[2:]: parts = f.split('=') if len(parts) == 2: key = parts[0].lower() value = parts[1] assert key not in rdict if is_angle[key]: rvalue = convert_angle(value) else: rvalue = float(value) rdict[key] = rvalue return field_id, rdict['ra'], rdict['dec'], rdict['mjd'] for line in guff.splitlines(): line = line.strip() if not line: continue field_id, ra, dec, mjd = parse_line(line) print field_id, ra, dec, mjd C:\junk>tommy_grav.py f29227 20.3962611111 67.5 53370.0679769 f31448 20.4161472222 79.6621944444 53370.0681162 f31226 20.4126388889 78.4458888889 53370.0682386 f31004 20.4181333333 77.2296944444 53370.0683602 f30782 20.4310944444 76.0135 53370.0684821 f30560 20.4505055556 74.7973055556 53370.068604 f30338 20.4756527778 73.5811111111 53370.0687262 f30116 20.5060277778 72.3648888889 53370.0688489 f29894 20.5412611111 71.1486111111 53370.0689707 f29672 20.5810805556 69.9323888889 53370.0690935 Cheers, John From bdesth.quelquechose at free.quelquepart.fr Fri Aug 15 11:05:08 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 15 Aug 2008 17:05:08 +0200 Subject: You advice please In-Reply-To: <2a611c23-16a9-4a9d-8c93-3b24d7b404af@e39g2000hsf.googlegroups.com> References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> <2a611c23-16a9-4a9d-8c93-3b24d7b404af@e39g2000hsf.googlegroups.com> Message-ID: <48a5b718$0$10768$426a74cc@news.free.fr> Hussein B a ?crit : (snip) > But this critisim looks so serious: > http://en.wikipedia.org/wiki/Ruby_programming_language#Criticism Most of what's written here could apply to Python too - all the part which mostly reflects the usual parano?a from bondage&discipline langages addicts wrt/ dynamic languages. The remaining is about implementation issues in ruby 1.8. From alexnbryan at gmail.com Mon Aug 18 19:10:46 2008 From: alexnbryan at gmail.com (Alexnb) Date: Mon, 18 Aug 2008 16:10:46 -0700 (PDT) Subject: searching through a string and pulling characters In-Reply-To: <307cf7b3-311d-4c1e-bb89-c685c0d548c9@n38g2000prl.googlegroups.com> References: <19039594.post@talk.nabble.com> <307cf7b3-311d-4c1e-bb89-c685c0d548c9@n38g2000prl.googlegroups.com> Message-ID: <19041720.post@talk.nabble.com> If by "What happened when you did:" you mean dictionary.com and yourdictionary.com? Nothing, they work but screen scraping isn't medicore at best. They both work fine (yourdictionary is better for screen scraping) but. I want maybe an offline soloution. But the whole reason for the program is that I can type in 20 words at one time, get them defined and formatted and then save all from my app. So far, all is good, I just need an offline soloution, or one from a database. You say a free dictionary program. But how can I get definitions from another program w/o opening it? Anyway, Ideas? John Machin wrote: > > On Aug 19, 8:34 am, Alexnb wrote: > >> The number is based on the word(s) they type into my program, and then it >> fetches the number that word is in the list of words and then will search >> the definitions document and go to the nth def. It probably won't work, >> but >> that is the Idea. > > Consider (1) an existing (free) dictionary application (2) using a > database, if you feel you must write your own application. > >> >> Also, on a side-note, does anyone know a very simple dictionary site, >> that >> isn't dictionary.com or yourdictionary.com. Or, a free dictionary that I >> can >> download to have an offline reference? > > What happened when you did: > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/searching-through-a-string-and-pulling-characters-tp19039594p19041720.html Sent from the Python - python-list mailing list archive at Nabble.com. From dlenski at gmail.com Fri Aug 15 09:56:41 2008 From: dlenski at gmail.com (Dan Lenski) Date: Fri, 15 Aug 2008 13:56:41 GMT Subject: negative numbers are not equal... References: Message-ID: On Thu, 14 Aug 2008 17:18:55 -0300, ariel ledesma wrote: > hello guys > > i just ran into this when comparing negative numbers, they start > returning False from -6 down, but only when comparing with 'is' > > >>> m = -5 > >>> a = -5 > >>> m is a > True > >>> m = -6 > >>> a = -6 > >>> m is a > False > >>> m == a > True > > i read that 'is' compares if they are really the same object, but i > don't that's it because then why does -5 return True? of course i could > only use == to compare, but still, what am i missing here? thanks in > advance They also return False for positive numbers > 256. Try this: >>> print [x for x in range(-10,260) if x is not x+1-1] [-10, -9, -8, -7, -6, 257, 258, 259] There is a good explanation for this: the "is" operator checks for object identity, not equality. Basically "a is m" asks, does the variable name "a" reference the same memory location as the variable name "m"? For integers in the range of -5<=x<=256, Python pre-caches all of these values, and whenever a variable takes on one of those values, it uses the cached value. This is an optimization: it prevents the need to allocate a new Python object for these very very common small integer values. For integer literals outside this range, a new Python object gets created when they are assigned to variables, so a=500 followed by m=500 will create new objects. The "is" operator just shows the effect of this caching. It's unimportant for real code since you never care whether two numeric variables refer to the same object (only important for complex data structures where their storage may overlap)... only whether they are equal or not. Dan Lenski (PS- The small integer pre-caching is described somewhere in the C API docs.) From fredrik at pythonware.com Fri Aug 15 13:58:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 15 Aug 2008 19:58:51 +0200 Subject: negative numbers are not equal... In-Reply-To: References: Message-ID: castironpi wrote: > This case actually misses handleC(). The solution is that the > function that is returning '-10' cannot return -10, it has to return > flagC. This can cause difficulties in cases when you're doing > operations on flags. Worse, if flagC is nested somewhere, say > moduleA.classB.flagC, you still have to work with that, not its value. do you *ever* make any sense at all? From news1234 at free.fr Wed Aug 13 17:22:31 2008 From: news1234 at free.fr (nntpman68) Date: Wed, 13 Aug 2008 23:22:31 +0200 Subject: How to execute commands in internal zones of solaris using python running from the global zone ? In-Reply-To: <48a29165$0$7602$426a34cc@news.free.fr> References: <425e481f-95ce-42a6-aaf6-1f42a3fe7239@w39g2000prb.googlegroups.com> <48a29165$0$7602$426a34cc@news.free.fr> Message-ID: <48a35097$0$17491$426a74cc@news.free.fr> > Hishaam wrote: >> How to execute commands in internal zones of solaris using python >> running from the global zone ? >> >> i tried -- >> 1> os.popen("zlogin ") >> 2> os.popen("zonename") >> >> the 2nd command executes back into the global zone and not into the >> internal zone >> can anyone help? Hmm, I was't reading enough. popen2 can be imported with popen2 the more modern alternative to popen seems to be subprocess.Popen http://docs.python.org/lib/node539.html And here a short example: #!/bin/env python import sys import os import popen2 # default host / command host="zone1" command='uname -n' # host / command via command line # didn't have time to check whether # shifting sys.argv is a common practice if(len(sys.argv) > 1): host=sys.argv[1] if(len(sys.argv) > 2): command=sys.argv[2] # ============== solution 1 ============ # just passing command to command line of ssh / rsh / zlogin pipe_in = os.popen('ssh ' + host + ' ' + command) a = pipe_in.read() print 'Result of solution 1',a # a minor variation of solution 1 would be the next line # in ssh the switch -T disables tty allocation and gets rid of a warning' #pipe_in = os.popen('echo '+command+' | ssh -T' + host) # =========== solution 2 ================= # using popen2 # if you do a little more than one command this might # be prone to dead locks # for more complex cases it's probably better # to use one thread for sending the commands and one thread for # collecting the responses # # if you want to see the warning remove it ;-_ [ z1_stdout , z1_stdin ] = popen2.popen2('ssh -T '+host) z1_stdin.write(command + '\n') z1_stdin.close() a = z1_stdout.read() print "Result of solution 2 is: ",a nntpman68 wrote: >> >> >> Hishaam > > > Very probably you didn't want to start two pipes (two processes on your > host) > > > > Can you ssh or rsh to zone 1? > > Then you want probably something like: > > os.popen('echo zonename | ssh ') > > > If not you could look at pexpect, though I didn't use it myself so far. > just look at the thread 'SSH utility' to get some examples. > you just had to replace 'ssh' with 'zlogin' > > ( http://www.noah.org/wiki/Pexpect ) > > > > Or you could try popen2, http://docs.python.org/lib/module-popen2.html > > Strange thing is though, that popen doesn't seem to exist on my python. > Perhaps it's not a standard library. > No idea. I myself am rather new to python :-( > > > However if you want to try popen2 read also 17.4.2 'Flow Control Issues' > in order to be sure, that your program doesn't deadlock > > > > [ z1_stdin , z1_stdout ] = os.popen2('ssh z1_stdin.write('zonename\n') > z1_stdout.readline() > > > bye N > > > From maric at aristote.info Sat Aug 2 02:28:28 2008 From: maric at aristote.info (Maric Michaud) Date: Sat, 2 Aug 2008 08:28:28 +0200 Subject: simple error i hope In-Reply-To: <1217631110.30810.11.camel@generator> References: <44e9dc820808011308k728e5702wdfcb465c01339156@mail.gmail.com> <1217631110.30810.11.camel@generator> Message-ID: <200808020828.28854.maric@aristote.info> Le Saturday 02 August 2008 00:51:50 Clay Hobbs, vous avez ?crit?: > It is also a good idea to open files with the open() function and not the > file() function. ?They do the exact same thing, and take the exact same > parameters, just open() makes your code a bit more readable (or at least > that's what I think). The main point with open I think is to easy later evolution. While you could override "file" name as well as "open" by a custom funcion, it's a bad idea to override the name of the type because a simple isinstance(file_, file) won't work anymore if you do so. -- _____________ Maric Michaud From fredrik at pythonware.com Sat Aug 30 13:21:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 30 Aug 2008 19:21:58 +0200 Subject: Which is faster? In-Reply-To: References: Message-ID: Lie wrote: >> how does doing something twice not change complexity? yes it maybe >> belongs to the same complexity-class but is still twice as slow no? > > Who is doing something twice? Definitely not sum(). nobody's claiming that -- but as mentioned above, even if sum() had done two passes over the source sequence, it'd still be O(n). From notvalid2 at sbcglobal.net Wed Aug 27 05:10:18 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Wed, 27 Aug 2008 02:10:18 -0700 Subject: Date Comparison and Manipulation Functions? In-Reply-To: References: <6cdf0c14-80b6-42c4-8047-8c01fda8b87c@r15g2000prh.googlegroups.com> Message-ID: <9U8tk.19080$cW3.13729@nlpi064.nbdc.sbc.com> John Machin wrote: > On Aug 27, 11:24 am, "W. eWatson" wrote: >> John Machin wrote: >>> On Aug 27, 10:21 am, "W. eWatson" wrote: >>>> I'm using IDLE for Python 2.4, and put pfydate distribution in >>>> C:\Python24\Lib\site-packages\pfydate, as required by the >>>> page. >>>> How to install pyfdate. >>>> Save pyfdate.py into your PythonNN/Lib/site-packages directory. >>>> I copied it into C:\Python24\Lib\site-packages\pfydate >>> If that means that you ended up with >>> C:\Python24\Lib\site-packages\pfydate\pyfdate.py >>> then you have *not* followed the instructions "Save pyfdate.py into >>> your PythonNN/Lib/site-packages directory". >>> You need to end up with >>> C:\Python24\Lib\site-packages\pyfdate.py >> None of the folders in C:\Python24\Lib\site-packages\ have py as a suffix >> (as seen either by the IDLE path browser or XP). My folder is exactly >> C:\Python24\Lib\site-packages\pfydate in XP and it contains about 12 py files. >> There are exactly three folders under >> C:\Python24\Lib\site-packages\ according to the IDLE path browser. This does >> not agree with XP, which has: >> Numeric >> pfydate >> scipy >> numpy >> PIL > > (1) "pfydate" != "pyfdate" typo > (2) The instructions say to put pyfdate.py [that's *ONE* file, not 12 > files] in the ..../site-packages folder, *not* a sub-folder > Got it. Ah, I see upon closer inspection the other files are just international versions. Thanks. It works. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From kyosohma at gmail.com Thu Aug 7 16:07:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 7 Aug 2008 13:07:13 -0700 (PDT) Subject: os.system question References: <1c5bf$489a4add$4275d90a$15022@FUSE.NET> Message-ID: On Aug 6, 8:07?pm, Kevin Walzer wrote: > ?>>> import os > ?>>> foo = os.system('whoami') > kevin > ?>>> print foo > 0 > ?>>> > > The standard output of the system command 'whoami' is my login name. Yet > the value of the 'foo' object is '0,' not 'kevin.' How can I get the > value of 'kevin' associated with foo? > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com Just an FYI, the os.system, commands, and os.popen* stuff is deprecated in Python 2.4+. The subprocess module is supposed to replace them all. See the docs for more info: http://docs.python.org/lib/module-subprocess.html I think the equivalent is subprocess.Popen with the communicate() method: http://docs.python.org/lib/node532.html HTH Mike From haxier at gmail.com Mon Aug 11 05:26:35 2008 From: haxier at gmail.com (haxier) Date: Mon, 11 Aug 2008 02:26:35 -0700 (PDT) Subject: Digitally sign PDF files Message-ID: <3d9825dc-be85-4fe5-98fa-979090830ea7@34g2000hsh.googlegroups.com> Hi all I'm developing an application with some reports and we're looking for advice. This reports should be openoffice.org .odf files, pdf files, and perhaps microsoft word files (.doc, .docx?) and must be digitally signed. Is out there some kind of libraries to ease this tasks? * Access to the local user certificate store, and read PEM or PKCS12 certificate files. * Read, parse and validate user certificates * Sign documents: as a binary stream, within an specific document (pdf, odt, doc) I've been googling and found very few documentation about this -- except some examples using jython and ironpython. Thanks From bj_666 at gmx.net Thu Aug 21 01:11:13 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Aug 2008 05:11:13 GMT Subject: Get parameters from the URL References: Message-ID: <6h4bnhFishf5U1@mid.uni-berlin.de> On Thu, 21 Aug 2008 10:04:35 +0530, Sohrab Pawar wrote: > I'm a python noob so don't be mean :) I have a URL like > http://mySite.net?userID=398&age=28 I'm trying to create a new python > script that is called when a user click a button "Redirect". When a user > clicks the "Redirect" button, I want to send the user to either of the 2 > pages, depending on the age of the user (sent as a parameter using the > URL). > > What is the best way to > 1. Read the URL and get the parameters (age=28 in this case) 2. Redirect > the the user accordingly > > I have done this kind of thing in a jsp/servlet environment but I have > no idea how to proceed in the Python world. If you really got that string you can use the modules `urlparse` and `cgi` to get the query part: In [48]: url = 'http://mySite.net?userID=398&age=28' In [49]: urlparse.urlparse(url) Out[49]: ('http', 'mySite.net', '', '', 'userID=398&age=28', '') In [50]: cgi.parse_qs(urlparse.urlparse(url)[4]) Out[50]: {'age': ['28'], 'userID': ['398']} But maybe you should read about the `cgi` module and how to use it. Ciao, Marc 'BlackJack' Rintsch From fabio.oikawa at gmail.com Fri Aug 1 11:45:18 2008 From: fabio.oikawa at gmail.com (Fabio Oikawa) Date: Fri, 1 Aug 2008 12:45:18 -0300 Subject: Python Written in C? In-Reply-To: References: <8d3752f20807202258w2a4167e4hd40b56b12c0c74fc@mail.gmail.com> Message-ID: <47e3464c0808010845n70a13b0ai39296c0b626f0f45@mail.gmail.com> 2008/8/1 Tim Rowe > 2008/7/21 Krishnakant Mane : > > > First off all c# is absolute rubbish waist of time. > > What a pity others are joining in this pointless language flame-war. > > Look, I recently had to write a script for manipulating some data; I > struggled to organise it in Python and in C++, but when I tried C# > everything fell naturally into place and I had it done in next to no > time. Other times it has been Python or C++ that has been the most > natural way to express what I'm trying to do. Just because /you/ > don't like C# doesn't mean it's rubbish or a waste of time; personally > I loathe Perl, but I respect the fact that a lot of programmers can > get good results very quickly in it. > > I reckon that the programmer who only knows one language is like a > carpenter trying to make a cabinet with just a chisel. Ok for making > the joints (although a hammer would have been handy to hit it with), > not /really/ as good as a plane for getting large areas smooth, and > the blade keeps jumping out when you try to use it as a screwdriver... > > The one-language programmer isn't really in a position to choose the > right tool for the job, because they only have one tool. Anybody who > says that a language in real use is a waste of time is denying the > reality of those who find it an effective tool. Similarly, anybody who > says that a language -- any language -- is right for all jobs plainly > doesn't understand that language design involves a lot of compromises, > and that the compromises that are appropriate choices for one task are > inappropriate for another. Python is a great tool. So is C#. You /can/ > do the same job with either, but the smart move is to choose the one > that is best adapted to the task in hand. > Great, I agree! The only problem is to be so good in several languages. Generally programmers are proficient in one or two. Cheers, F?bio -------------- next part -------------- An HTML attachment was scrubbed... URL: From Josef.Robert.Novak at gmail.com Wed Aug 13 06:12:48 2008 From: Josef.Robert.Novak at gmail.com (kettle) Date: Wed, 13 Aug 2008 03:12:48 -0700 (PDT) Subject: python tr equivalent (non-ascii) References: <552ee625-5d07-4f37-958f-abe046cdff3d@v1g2000pra.googlegroups.com> Message-ID: On Aug 13, 5:33 pm, Fredrik Lundh wrote: > kettle wrote: > > I was wondering how I ought to be handling character range > > translations in python. > > > What I want to do is translate fullwidth numbers and roman alphabet > > characters into their halfwidth ascii equivalents. > > In perl I can do this pretty easily with tr: > > > tr/\x{ff00}-\x{ff5e}/\x{0020}-\x{007e}/; > > > and I think the string.translate method is what I need to use to > > achieve the equivalent in python. Unfortunately the maktrans method > > doesn't seem to accept character ranges and I'm also having trouble > > with it's interpretation of length. What I came up with was to first > > fudge the ranges: > > > my_test_string = u"???????" > > f_range = "".join([unichr(x) for x in > > range(ord(u"\uff00"),ord(u"\uff5e"))]) > > t_range = "".join([unichr(x) for x in > > range(ord(u"\u0020"),ord(u"\u007e"))]) > > > then use these as input to maketrans: > > my_trans_string = > > my_test_string.translate(string.maketrans(f_range,t_range)) > > Traceback (most recent call last): > > File "", line 1, in ? > > UnicodeEncodeError: 'ascii' codec can't encode characters in position > > 0-93: ordinal not in range(128) > > maketrans only works for byte strings. > > as for translate itself, it has different signatures for byte strings > and unicode strings; in the former case, it takes lookup table > represented as a 256-byte string (e.g. created by maketrans), in the > latter case, it takes a dictionary mapping from ordinals to ordinals or > unicode strings. > > something like > > lut = dict((0xff00 + ch, 0x0020 + ch) for ch in range(0x80)) > > new_string = old_string.translate(lut) > > could work (untested). > > excellent. i didnt realize from the docs that i could do that. thanks From notvalid2 at sbcglobal.net Fri Aug 29 12:32:01 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Fri, 29 Aug 2008 09:32:01 -0700 Subject: Date Comparison and Manipulation Functions? In-Reply-To: <9U8tk.19080$cW3.13729@nlpi064.nbdc.sbc.com> References: <6cdf0c14-80b6-42c4-8047-8c01fda8b87c@r15g2000prh.googlegroups.com> <9U8tk.19080$cW3.13729@nlpi064.nbdc.sbc.com> Message-ID: <8AVtk.8079$np7.5970@flpi149.ffdc.sbc.com> I just tried the following code, and got an unexpected result. from pyfdate import * t = Time() ts = Time(2008, 8, 29,15,20,7) tnew = ts.plus(months=6) print "new date: ", tnew Result: new date: 2009-02-28 15:20:07 I believe that should be April 1, 2009. If I use months = 1 and day =31, I get Sept. 30, 2008 and not Oct. 1, 2008. Is there a way to get around this? -- W. Watson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet From stefan_ml at behnel.de Fri Aug 8 10:38:14 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 08 Aug 2008 16:38:14 +0200 Subject: how to find out if an object is a class? In-Reply-To: References: <871w105qs3.fsf@benfinney.id.au> <489be85f$0$12954$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <489c5a56$0$1077$9b4e6d93@newsspool3.arcor-online.net> Miles wrote: > On Fri, Aug 8, 2008 at 2:31 AM, Stefan Behnel wrote: >> I recently had the reverse case that a (stupidly implemented) extension module >> required a callback function and I wanted to pass a function wrapped in a >> wrapper object. That failed, because it specifically checked for the argument >> being a function, not just a callable object. I had to pull quite a number of >> tricks to reimplement the wrapper class as a function (thank god, it's Python!). > > You really only needed one trick: > > def functionize(callable): > return lambda *args, **kwargs: callable(*args, **kwargs) Congratulations, you found the trivial case. Stefan From dudeja.rajat at gmail.com Mon Aug 25 09:00:31 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 25 Aug 2008 14:00:31 +0100 Subject: Tkinter - How to create combo box using Tix with the existing Tkinter widgets/ In-Reply-To: References: Message-ID: On Mon, Aug 25, 2008 at 12:57 PM, wrote: > Hi, > > I'm using Tkinter module to create a GUI application. I found that the > combo box is not present in Tkinter module. > It comes with Tix module. Could some one give me an example to create > a combo box whilst using Tix and Tkinter? > > I've been using the following to create my tkinter widgets: > myRoot = Tk() > > and in my Gui code, I've been using > self.lbAnalysisLib = Listbox(master, \ > yscrollcommand = self.vsbAnalysisLib.set,\ > height = 1, > width = 30) > > Please suggest how could I call the Tix's combo box from my existing > GUI application that heavily uses the Tkinter widgets? > Kindly provide me some code examples. > > Thanks and regards, > Rajat > Ok...now I found the way to do that. But I'm stuck further. my code is as below: main module ********************** myRoot = Tix.Tk() myAppGUIObject = myAppGUI(myRoot) Gui module **************** class myAppGUI: def __init__(self, master): self.cbAnalysisLib = Tix.ComboBox(master, label = "Analysis Library:") self.cbAnalysisLib.grid(row = 3, column = 1, padx = 30, pady = 30, sticky = W) self.cbAnalysisLib.config(editable = 0) self.cbAnalysisLibVersion = Tix.ComboBox(master, label = "Reference Analysis Library Version:", \ labelside = 'left') self.cbAnalysisLibVersion.grid(row = 5, column = 1, padx = 30, pady = 30, sticky = W) self.cbAnalysisLibVersion.config(editable = 0) The problem is that the labelside option is not working. I'm not able to use even the wraptext option. -- Regrads, Rajat From cromulent at justextrememetal.com Mon Aug 11 11:58:00 2008 From: cromulent at justextrememetal.com (Cromulent) Date: Mon, 11 Aug 2008 16:58:00 +0100 Subject: Problems returning data from embedded Python Message-ID: <2008081116580016807-cromulent@justextrememetalcom> Okay I'm having a few issues with this and I can't seem to get it sorted out (most likely due to my inexperience with Python). Here is my Python code: def fileInput(): data = [] s = raw_input("Please enter the filename to process (enter full path if not in current directory): ") fd = open(s, "r") fd.readline() line = fd.readlines() for record in line: record = record.strip() items = record.split(',') for i in range(1, 5): items[i] = float(items[i]) items[5] = int(items[5]) data.append(items) fd.close() return items It works perfectly and does exactly what I want it to do. The problem comes when I try and convert the data I returned from the Python script and turn it into something useable in C. I have no idea. The C functions that seem most use deal with Tuples, when this is a list and I can't see any specific functions for dealing with lists in the C API. Can anyone give me some pointers in the right direction at all please? I know the C program has received the data correctly, I just need to put it in C types. Thank you. -- "I disapprove of what you say, but I'll defend to the death your right to say it." - Voltaire From bdesth.quelquechose at free.quelquepart.fr Wed Aug 27 12:52:18 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 27 Aug 2008 18:52:18 +0200 Subject: exception handling in complex Python programs In-Reply-To: References: <00bb4e2f$0$20315$c3e8da3@news.astraweb.com> <8cb19b0b-1df8-4c5b-b546-a273c6fbc2e3@j1g2000prb.googlegroups.com> <00bc565e$0$20315$c3e8da3@news.astraweb.com> Message-ID: <48b5a232$0$10445$426a74cc@news.free.fr> Lie a ?crit : > On Aug 21, 12:59 am, Steven D'Aprano cybersource.com.au> wrote: >> On Wed, 20 Aug 2008 09:23:22 -0700, dbpoko... at gmail.com wrote: >>> On Aug 19, 4:12 pm, Steven D'Aprano >> cybersource.com.au> wrote: >>>> On Tue, 19 Aug 2008 11:07:39 -0700, dbpoko... at gmail.com wrote: >>>>> def do_something(filename): >>>>> if not os.access(filename,os.R_OK): >>>>> return err(...) >>>>> f = open(filename) >>>>> ... >>>> You're running on a multitasking modern machine, right? What happens >>>> when some other process deletes filename, or changes its permissions, >>>> in the time after you check for access but before you actually open it? >>> This is a good point - if you want to use the correct way of opening >>> files, and >>> you don't want to worry about tracking down exception types, then we can >>> probably >>> agree that the following is the simplest, easiest-to-remember way: >>> def do_something(filename): >>> try: >>> f = open(filename) >>> except: >>> >> No, we don't agree that that is the correct way of opening files. Simple >> it might be, but correct it is not. >> >> If you're using Python 2.6 or greater, then you should be using a with >> block to handle file opening. >> >> And regardless of which version of Python, you shouldn't use a bare >> except. It will mask exceptions you *don't* want to catch, including >> programming errors, typos and keyboard interrupts. >> >>> Opening files is a special case where EAFP is the only correct solution >>> (AFAIK). I still liberally sprinkle LBYL-style "assert isinstance(...)" >> Oh goodie. Another programmer who goes out of his way to make it hard for >> other programmers, by destroying duck-typing. >> >> BTW, assertions aren't meant for checking data, because assertions can be >> turned off. Outside of test frameworks (e.g. unit tests), assertions are >> meant for verifying program logic: >> >> def foo(x): >> # This is bad, because it can be turned off at runtime, >> # destroying your argument checking. >> assert isinstance(x, int) >> # And it raises the wrong sort of exception. >> >> # This is better (but not as good as duck-typing). >> if not isinstance(x, int): >> raise TypeError('x not an int') >> # And it raises the right sort of error. >> >> y = some_function(x) >> # y should now be between -1 and 1. >> assert -1 < y < 1 >> do_something_with(y) >> >>> and other similar assertions in routines. The point is that EAFP >>> conflicts with the interest of reporting errors as soon as possible >> Not necessarily. Tell me how this conflicts with reporting errors as soon >> as possible: >> >> def do_something(filename): >> try: >> f = open(filename) >> except IOError, e: >> report_exception(e) # use a GUI, log to a file, whatever... >> >> How could you report the exception any earlier than immediately? > > I'm sure different people would have different view on what > immediately means. The LBYL supporters define immediately as > immediately after a definite potential problem is detected (by ifs or > assertion), while the EAFP supporters define immediately as > immediately after a problem arises. No side is right or wrong, both > have weakness and strength, but python-style programs are encouraged > to use EAFP-style exception handling whenever feasible, but with the > spirit of the Zen: "Special cases aren't special enough to break the > rules, although practicality beats purity", if LBYL makes things much > easier in that case, and doing EAFP would just convolute the code, > then practicality beats purity. > Hear hear... From bedouglas at earthlink.net Sun Aug 17 17:35:34 2008 From: bedouglas at earthlink.net (bruce) Date: Sun, 17 Aug 2008 14:35:34 -0700 Subject: list/tuple/dict question In-Reply-To: Message-ID: <005b01c900b1$2f1693f0$0301a8c0@tmesa.com> Hi Fredrik... so, this still doesn't get me an array called 'cat', or 'dog' or do i somehow use stuff to add/extract the vals...??? thanks -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Fredrik Lundh Sent: Sunday, August 17, 2008 2:27 PM To: python-list at python.org Subject: Re: list/tuple/dict question bruce wrote: > a dict doesn't seem to work, as it is essentially a series of key/values, > which isn't exactly what i want... so what do you think a variable namespace is? as usual, Python works best if you use it to write Python program, and in Python, the right way to store a collection of name/value pairs is to use a dictionary: stuff = {} foo = [] foo.append('cat') foo.append('dog') stuff[foo[1]] = [] -- http://mail.python.org/mailman/listinfo/python-list From kyosohma at gmail.com Fri Aug 8 13:49:11 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 8 Aug 2008 10:49:11 -0700 (PDT) Subject: small issue with Idle References: <2c192ba3-bc94-4f55-9d59-0fe14b8069a0@z6g2000pre.googlegroups.com> Message-ID: On Aug 8, 9:41?am, v4vijayakumar wrote: > When you press 'home' button cursor goes before >>> prompt. This is > little uncomfortable. > > I am using Idle 1.2.2. (python 2.5.2.) There's a free version of Wing IDE that has an IDLE-like interface that doesn't have this issue...or you could just use the command line version of IDLE. Mike From Levon.Ghazaryan at gmail.com Mon Aug 25 16:54:59 2008 From: Levon.Ghazaryan at gmail.com (~levon) Date: Mon, 25 Aug 2008 13:54:59 -0700 (PDT) Subject: signal and threading References: <78b957b0-3a29-45ba-9c7e-d8934c900127@i76g2000hsf.googlegroups.com> Message-ID: this seems to be the solution: http://code.activestate.com/recipes/496735/ On Aug 25, 3:37?pm, "~levon" wrote: > Hello group, > > in following example, a signal handler is registered and a thread > started. if I call self.doSomethin() directly > the code works as I would expect. as i send a SIGINT shutdown is > called and the script terminates. > > as soon as I call doSomething() in a thread the the SIGINT handler is > never called again and > i have to terminate the script with a SIGTERM or SIGKILL. > > well, i would expect the handler to be called in both cases, am i > missing something? > > by the way. calling os.kill(os.getpid(), signal.SIGINT) works as I > would expect, what > don't is kill -s SIGINT pid # where pid is the actual process id > > the code: > > class Runner(object): > ? ? def __init__(self): > ? ? ? ? print os.getpid() > ? ? ? ? self.shd = False > ? ? ? ? signal.signal(signal.SIGINT, self.shutdown) > ? ? ? ? threading.Thread(target=self.doSomething).start() > ? ? ? ? # the following works fine: > ? ? ? ? #os.kill(os.getpid(), signal.SIGINT) > > ? ? def doSomething(self): > ? ? ? ? while not self.shd: > ? ? ? ? ? ? pass > > ? ? def shutdown(self, signo, frm): > ? ? ? ? self.shd = True > > if __name__ == '__main__': > ? ? Runner() > > ~levon From marco.bizzarri at gmail.com Sat Aug 30 13:28:53 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 30 Aug 2008 19:28:53 +0200 Subject: Advice on the style to use in imports In-Reply-To: References: <3f0d61c40808300512x1dcd5061t19ad7323b7ef15e9@mail.gmail.com> Message-ID: <3f0d61c40808301028teb64a72ibcd65f9b946de915@mail.gmail.com> Hi bearophile On Sat, Aug 30, 2008 at 4:04 PM, wrote: > > from somemodule import somename > > is often acceptable IHMO, but there are some things to consider: > - you and the person that reads your code have to remember where > somename comes from. So you can do it for well known names like izip > or imap, but if you import lots of names from lots of modules, things > may become too much complex. So often it can be better to import just > the modules, and use somemodule.somename. Yes, that's true; but when I see that I need so many symbols from another module, I take that as an hint that either my module is doing too many things, and it should be splitted, or it is tightly coupled to that module... actually, being forced to write all the imports in that way was a tool into inspecting the dependencies in our project. > - somemodule.somename is longer to write and to read, and if it's > repeated many times it may worsen the program readability, making > lines of code and expressions too much long and heavy. So you have to > use your brain (this means that you may have to avoid standard > solutions). Note that you can use a compromise, shortening the module > name like this: > import somemodule as sm > Then you can use: > sm.somename it is not a problem to have special cases, as long as they are "special"; I'm looking for more or less accepted solutions; of course any project has some area where it is better to follow readability over standards; I'm just trying to understand the standards, then I will deviate from them. I feel like I'm learning to drive: first I learn the rules, then I learn the exceptions ;) > - somemodule.somename requires an extra lookup, so in long tight loops The slowdown was what in the first place made me import all the names directly; but I'm not afraid too much from that, right now. > (if you don't use Psyco) it slows down the code. This can be solved > locally, assigning a local name into a function/method (or even in > their argument list, but that's a hack to be used only once in a > while): > localname = somemodule.somename > > Bye, > bearophile > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks again for sharing your thoughts with me, bearophile. -- Marco Bizzarri http://iliveinpisa.blogspot.com/ http://notenotturne.blogspot.com/ From Edwin.Madari at VerizonWireless.com Wed Aug 13 22:28:18 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Wed, 13 Aug 2008 22:28:18 -0400 Subject: Random Problems In-Reply-To: Message-ID: <20080814022928.D699B1E4005@bag.python.org> use songs.extend( asongs ) #append is for single item - where ever it might be. >>> l1 = range(5) >>> l2 = range(5,10) >>> l1 [0, 1, 2, 3, 4] >>> l2 [5, 6, 7, 8, 9] >>> l1.extend(l2) >>> l1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> good luck. Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of Cousin Stanley Sent: Wednesday, August 13, 2008 10:19 PM To: python-list at python.org Subject: Re: Random Problems > Well the othe day I was making a program to make a list > of all the songs in certian directorys but I got a problem, > only one of the directorys was added to the list. > .... > Here's some code .... that illustrates yours .... import glob songs = glob.glob( '/path/to/somewhere/*.mp3' ) asongs = glob.glob( 'path/to/somewhere/else/*.mp3' ) songs.append( asongs ) # repeat a few times appending lists from other dirs > all goes well but pick awalys is from the first directory > but songs awalys includes all the files I want it to. songs.append( asongs ) is appending the entire asongs list as a single item to the end of the songs list, not adding each individual song as an entry .... For example .... >>> l1 = range( 0 , 5 ) >>> l2 = range( 5 , 10 ) >>> l3 = range( 11 , 15 ) >>> >>> l1 [0, 1, 2, 3, 4] >>> >>> l2 [5, 6, 7, 8, 9] >>> >>> l3 [11, 12, 13, 14] >>> >>> l1.append( l2 ) >>> >>> l1 [0, 1, 2, 3, 4, [5, 6, 7, 8, 9]] >>> >>> l1.append( l3 ) >>> >>> l1 [0, 1, 2, 3, 4, [5, 6, 7, 8, 9], [11, 12, 13, 14]] So, if you have a lot of entries in the original songs list you're only adding a few entries to it in the form of another list and most likely you didn't run enough random.choice tests to flush out a pick that turned out to be one of the entire asong lists that you added .... You might try something like the following where each tune gets added individually to the song pool .... un-tested .... # ------------------------------------------------------------------- import random import glob base_dir = 'c:/Documents and Settings/Admin/My Documents' list_subdirs = [ 'LimeWire/Saved/*.mp3' , 'Downloads/*/*.mp3' , 'Downloads/*/*/*.mp3' , 'Downloads/*/*/*/*.mp3 ] song_pool = [ ] for this_dir in list_subdirs : list_songs = glob.glob( "'%s/%s'" % ( base_dir , this_dir ) if list_songs : for this_song in list_songs : song_pool.append( this_song ) npicks = 41 print for n in range( npicks ) : this_pick = random.choice( song_pool ) print ' ' , this_pick # ------------------------------------------------------------------- -- Stanley C. Kitching Human Being Phoenix, Arizona -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From cbabcock at kolonelpanic.org Sat Aug 30 23:59:04 2008 From: cbabcock at kolonelpanic.org (Chris Babcock) Date: Sat, 30 Aug 2008 20:59:04 -0700 Subject: Mako --> Genshi Message-ID: <20080830205904.725f1bef@mail.asciiking.com> Is there a cheap way to convert Myghty/Mako templates to Kid/Genshi? There's some code written for Pylons that I want to incorporate into a TurboGears 2 project and Genshi templates are more likely to behave themselves with the tools I'm used to. Chris From frank at chagford.com Sat Aug 30 01:25:28 2008 From: frank at chagford.com (Frank Millman) Date: Fri, 29 Aug 2008 22:25:28 -0700 (PDT) Subject: Ensure only single application instance. References: Message-ID: On Aug 29, 11:25?pm, Uberman wrote: > On Fri, Aug 29, 2008 at 6:51 AM, Heston James wrote: > > Good afternoon all. > > > I have an application/script which is launched by crontab on a regular > > basis. I need an effective and accurate way to ensure that only one instance > > of the script is running at any one time. > The following is taken from the getmail FAQ - ------------------------------------------ If you need to prevent two instances of getmail from running simultaneously, use any standard Unix method of providing a mutex for this purpose. One example would be to run getmail under a program like setlock (part of the daemontools package). Change your script or crontab file to invoke getmail like this: /path/to/setlock -n /path/to/lockfile /path/to/getmail [getmail options] There are other programs that provide functionality similar to setlock. ------------------------------------------ HTH Frank Millman From fredrik at pythonware.com Sun Aug 17 16:56:20 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 17 Aug 2008 22:56:20 +0200 Subject: python-mode errors In-Reply-To: References: Message-ID: Rustom Mody wrote: > When I start python mode I get the error: > > idle error: # -Wrong number of arguments : # set-match-data> 2" > > The Python mode version is 4.78 > > Is this a known problem? there are plenty of google hits for that message, and they all seem to agree that the problem is caused by using ELC files generated for a newer emacs with an older version. try loading the EL file to see if the problem goes away. From dudeja.rajat at gmail.com Sat Aug 30 09:51:40 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 30 Aug 2008 14:51:40 +0100 Subject: How to delete elements from Tix Combo Box? In-Reply-To: References: Message-ID: On Sat, Aug 30, 2008 at 2:32 PM, Fredrik Lundh wrote: > dudeja.rajat at gmail.com wrote: > >> I'm using a Tix combo box (I call it combo2), the contents of which >> are loaded depeding on the selection in another Tix combo box(I call >> it combo1) >> I have used the commands: >> >> self.cbAnalysisLibVersion.insert(END, results) >> >> to insert elements to the combo box. >> >> I'm looking for some similar option to delete elements from the combo >> box. I mean, as soon as I change selection in >> combo1 the previous elements in the combo2 should get cleared up( or >> deleted) and | shall be able to the above insert command to add new >> elements to the combo2 ( depending upon selection in combo1) >> >> Please suggest how can I clear up the ( delete the entries) in combo2. > > no time to test this, but iirc, the combobox content is held in an ordinary > listbox widget, so you should be able to use the subwidget method to fetch > that widget, and then use ordinary listbox methods to change the content. > Something like this: > > lb = w.subwidget("listbox") > lb.delete(0, END) # delete all items > > > > -- > http://mail.python.org/mailman/listinfo/python-list > Fredrik, Thanks so much. That worked. Following this, I can now see that my combo2 has no previous elements and contains only the elements relevant to selection in combo1. Now, as soon as I select something in combo 2 and go back to change selection in combo1 the combo2 must get its history cleared up (i.e the previous selection in combo2's entry subwidget) I used the command before I delete the entires : self.combo2.config(history = False) But this does not seem to be working; Here is my code snippet: **************** Inside the callback function of combo1: for libName, libResults in self.__libVerDict.items(): if libName == selectedLibName: #Get the list of labelled results resultsVer = self.__libVerDict[libName] self.combo2.config(state = NORMAL) self.combo2.config(history = False) #Delete the previous entries from the listbox #subwidget of combo box subLB = self.combo2.subwidget("listbox") subLB.delete(0, END) #Add the results to the combo box for results in resultsVer: self.combo2.insert(END, results) -- Regards, Rajat From invalid at invalid.invalid Sun Aug 10 14:13:31 2008 From: invalid at invalid.invalid (WP) Date: Sun, 10 Aug 2008 20:13:31 +0200 Subject: My very first python program, need help In-Reply-To: References: <6g8a56FenevdU1@mid.individual.net> Message-ID: <6g8pecFerglbU1@mid.individual.net> Wojtek Walczak wrote: [snip] Thanks for all your help. I've incorporated your suggestions and moved on to my next program. See new thread. :) - Eric (WP) From castironpi at gmail.com Mon Aug 4 15:15:01 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 4 Aug 2008 12:15:01 -0700 (PDT) Subject: custom allocation and custom type Message-ID: Hi all, I am trying to create a custom tuple type. I want it to live in a custom memory region, which will be a memory-mapped file. Its contents cannot be PyObject*. They have to be offsets into mapped memory. GetItem( i ) would return: (PyObject *)( t->ob_item[ i ]+ mmap_base_addr ); In the constructor, each item x would be stored as: BYTE* x_offset= x- mmap_base_addr; t->ob_item[ 0 ]= x_offset; For starters, only ints, strings, and other tuples will be members. I'll work out the list type and user-defined classes at a later time. Each will be required to be already existing in the mmap; that is, be of custom types too. I had partial success with strings and ints just memcpy-ing the entire PyObject structure. They are easier because they are immutable, and don't contain references. That's why tuple is my next step: it's immutable, but can contain references. I want to back up a step and ask some questions about ints first. What worries are there in memcpy-ing a PyIntObject? Would it be better to compile my own MmapIntObject? I do Py_INCREF on the object I return, to ensure it lives on, but I am getting an occasional crash on exit. What did I miss? Do I need to readjust the ob_type pointer every time I load the module (and lock for exclusive access)? Does Python try to free the memory when it exits? For the tuples, is there any way I can reuse the tuple code? The constructor uses a custom pool for speed which I'd probably eliminate, for the time. Slices would have to be MmapTupleObject instances too. Should I also create MmapTupleIterObject? PyObject_GC_New and PyObject_GC_NewVar are confusing. I can't follow them to the actual call to 'malloc', since they themselves lead around Python's custom memory pool. What steps do I need to be sure to take in my own? I'm having trouble building PerstTupleObject.c (persistent tuple object) to try it out. I'm using MinGW on WinXP. I added #include "persttupleobject.h" to the top of "persttupleobject.c" already, but it's a duplicate otherwise, with the name replaced. --- C>c:/programs/mingw/bin/g++ persttupleobject.c -c -Ic:/programs/ python25/include persttupleobject.c:650: warning: 'PyPerstTuple_Type' defined locally after being referenced with dllimport linkage C>c:/programs/mingw/bin/g++ -shared persttupleobject.o -o persttupleobject.pyd -L c:/programs/python25/libs -lpython25 persttupleobject.o(.text+0xce):persttupleobject.c: undefined reference to `_imp_ _PyPerstTuple_Type' persttupleobject.o(.text+0x15c):persttupleobject.c: undefined reference to `_PyG C_generation0' [snip] --- I get some of the same errors when compiling tupleobject.c from the Python-2.5.2 distribution: C>c:/programs/mingw/bin/g++ tupleobject.c -c -Ic:/programs/python25/ include tupleobject.c:649: warning: 'PyTuple_Type' defined locally after being reference d with dllimport linkage C>c:/programs/mingw/bin/g++ -shared tupleobject.o -o tupleobject.pyd - Lc:/progra ms/python25/libs -lpython25 c:/programs/python25/libs/libpython25.a(dcbbs00622.o)(.text+0x0): multiple defin ition of `PyTuple_Type' tupleobject.o(.data+0x140):tupleobject.c: first defined here tupleobject.o(.text+0x15c):tupleobject.c: undefined reference to `_PyGC_generati on0' [snip] --- Thanks in advance. From sjmachin at lexicon.net Wed Aug 27 04:03:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 27 Aug 2008 01:03:34 -0700 (PDT) Subject: Date Comparison and Manipulation Functions? References: <6cdf0c14-80b6-42c4-8047-8c01fda8b87c@r15g2000prh.googlegroups.com> Message-ID: On Aug 27, 11:24?am, "W. eWatson" wrote: > John Machin wrote: > > On Aug 27, 10:21 am, "W. eWatson" wrote: > >> I'm using IDLE for Python 2.4, and put pfydate distribution in > >> C:\Python24\Lib\site-packages\pfydate, as required by the > >> page. > >> How to install pyfdate. > > >> ? ? ?Save pyfdate.py into your PythonNN/Lib/site-packages directory. > >> I copied it into C:\Python24\Lib\site-packages\pfydate > > > If that means that you ended up with > > ? ?C:\Python24\Lib\site-packages\pfydate\pyfdate.py > > then you have *not* followed the instructions "Save pyfdate.py into > > your PythonNN/Lib/site-packages directory". > > You need to end up with > > ? ?C:\Python24\Lib\site-packages\pyfdate.py > > None of the folders in C:\Python24\Lib\site-packages\ have py as a suffix > (as seen either by the IDLE path browser or XP). My folder is exactly > C:\Python24\Lib\site-packages\pfydate in XP and it contains about 12 py files. > There are exactly three folders under > C:\Python24\Lib\site-packages\ according to the IDLE path browser. This does > not agree with XP, which has: > Numeric > pfydate > scipy > numpy > PIL (1) "pfydate" != "pyfdate" (2) The instructions say to put pyfdate.py [that's *ONE* file, not 12 files] in the ..../site-packages folder, *not* a sub-folder From joan.pallares at gmail.com Mon Aug 18 18:02:38 2008 From: joan.pallares at gmail.com (=?ISO-8859-1?Q?Joan_Pallar=E8s?=) Date: Tue, 19 Aug 2008 00:02:38 +0200 Subject: Python encoding Message-ID: I have problems encoding some team names. Python can't work with: ?, ?, ?..... I tried to create unicode in this two ways: self.nombreLocal = unicode(nombreLocal) self.nombreLocal = unicode(nombreLocal, 'iso-8859-1') But there is always one character that can't be encoded!! unicode doesn`t encode everything? How can I make the program to try several encoding till one work? Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From hubaghdadi at gmail.com Wed Aug 13 08:46:03 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Wed, 13 Aug 2008 05:46:03 -0700 (PDT) Subject: You advice please References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> <48a2d62b$0$3732$426a74cc@news.free.fr> Message-ID: On Aug 13, 7:40 am, Bruno Desthuilliers wrote: > ?lvaro G. Vicario a ?crit : > > > > > Hussein B escribi?: > >> The sad fact (at least to me), Ruby is getting a lot of attention > >> these days. > >> Why Python isn't getting this attention although is a much more mature > >> language and it is used by many big, big names? > >> And do I dare to say it is much more charming? > > > The opinion of a PHP developer who's playing with Python as well: > > > I've come across Python almost everywhere. Many programs I use (or I've > > evaluated) are written in Python or use it for scripting: source control > > software (Subversion, Bazaar, Mercurial), IDEs (Komodo Edit), popular > > web applications (Zope, Trac)... If you're looking for a script for > > admin tasks your search results will probably contain something in > > Python. If you want to build a Firefox extension you'll find a *.py file > > sitting around. > > > But I've never came across a Ruby app. Sure, I know Ruby exists and > > people are very enthusiastic about it (though they often mistake it with > > Ruby on Rails), but that's all. > > Redmine is a nice alternative to Trac. And Twitter is certainly a > well-known app too. (Yes, RoR apps in both cases...). > > > Ruby is popular among bloggers but I'm not sure whether it's popular > > among developers. > > Almost as much as Python, I'd say. But both languages fight for the same > niches in languages/techno ecosystem, and Python, being older, tend to > get more visibility. But Twitter is suffering from sever scaling problems, I read it maybe will be reimplemented in Java ... From kay.schluehr at gmx.net Wed Aug 13 16:49:41 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 13 Aug 2008 13:49:41 -0700 (PDT) Subject: ANN: P4D 1.2 References: <3bc040e5-738b-4176-a023-2b5e2fa0eca3@79g2000hsk.googlegroups.com> Message-ID: <2d07561f-5b1b-4506-b2a4-51c49223bc78@z72g2000hsb.googlegroups.com> On 12 Aug., 12:54, Kay Schluehr wrote: > On 12 Aug., 10:50, Uwe Grauer wrote: > > > > > Kay Schluehr wrote: > > > P4D = E4X style embedded DSL for Python but without E and X. > > > > The main feature of P4D 1.2 are *Bytelets*. While the primary purpose > > > of P4D 1.1 was the support textual data which can be considered as > > > isomorphic to XML the new release is focussed on binary data. Bytelets > > > are P4D objects that are assembled from hexcode which is reified as a > > > Hex object. Bytelets can also be serialized as Hex objects which makes > > > them apt for low level communication. Bytelets can be used to parse > > > hexcode into other Bytelets of the same structure and Bytelets can be > > > cloned like object prototypes which makes it easy to produce sequences > > > of variations of one Bytelet ( usually you do not derive from a > > > Bytelet but modify a prototype ). > > > > For more information see: > > > >http://pypi.python.org/pypi/P4D > > >http://www.fiber-space.de > > >http://www.fiber-space.de/EasyExtend/doc/p4d/bytelets.html > > > That's a really bad name for the project as there is P4D (Python for > > Delphi) already. > > Maybe try to find a different naming to help distinguish your project > > from other meanings. > > > Uwe > > Hmm... using three letter acronyms is a mess. Sorry for this > interference! > > Actually "P4D" is not used innocently in the implementation code. It's > also a file extension, a prompt, an XML namespace prefix, a class name > etc. not just a project name and I'm not going to change all this. > > I also don't think this is too critical when context has been > established but since the package is also distributed as "P4D" I'm > going to rename it into "P4D Langlet 1.3" in the next release and > adapt the URLs somewhat. I hope this helps avoiding confusion. > > Kay Done. I removed the "P4D" project from PyPI and launched "P4D Langlet" instead ( although in the version 1.2.2 not in 1.3 as mentioned above). Kay From mccredie at gmail.com Sat Aug 9 17:14:32 2008 From: mccredie at gmail.com (Matimus) Date: Sat, 9 Aug 2008 14:14:32 -0700 (PDT) Subject: Missing exceptions in PEP 3107 References: Message-ID: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> On Aug 9, 9:08?am, Christoph Zwerschke wrote: > I'm just reading PEP 3107 (function annotations) and wonder why > exceptions are not mentioned there. I think it would be helpful if one > could specify which exceptions can be raised by a function, similarly to > how it is possible in C++ using the "throw" clause. The syntax would be > something like this: > > def foo(a: expr, b: expr = 5) raises expr -> expr: > > The expr in that "raises" clause should be a list of Exceptions. > > Having the list of possible exceptions as annotation alone would be > already helpful. Of course it could be also discussed whether Python > should check that the function really raises only these exceptions (as > in C++), or we could even have checked exceptions (as in Java, but this > seems to be a controversial issue). > > Has this already been discussed, or is it in a different PEP? > > -- Christoph Keep in mind that annotations are just a way of associating some information with the parameters or a function. There is a special parameter called `return` to help associate information with the return value. Whether that information is used to describe the types of the function parameters, how they are used, or something completely different is up to the application that uses them. When you say: > The expr in that "raises" clause should be a list of Exceptions. You are clearly confusing the annotation feature with a possible application of the annotation feature. Annotation could be used for many different applications besides type safety. Annotation simply creates a dictionary. The name `return` was chosen for the return value because it _is_ a keyword and therefore could not conflict with the name of any of the parameters. Using "raises" would mean that we would have to introduce the name "raises" as a new keyword. It would be better just to use they existing keyword "raise". With all of that being said, a package or application that uses annotation could simply use the data-structure associated with "return" to also contain exception information. That might not seem intuitive, but keep in mind that the value associated with "return" in the associations dictionary is going to be a special case anyway. def foo(a: "a info", b: "b info") -> "return info", "exception info": return "hello world" Matt From sharon.kim96 at gmail.com Mon Aug 25 10:15:56 2008 From: sharon.kim96 at gmail.com (sharon k) Date: Mon, 25 Aug 2008 22:15:56 +0800 Subject: newbie question Message-ID: hi all, i am new to python. i fetch a webpage with urllib, extract a few numbers in a format as follow; 10,884 24,068 my question is how to remove the comma between the number, since i have to add them up later. sorry for my bad english. -------------- next part -------------- An HTML attachment was scrubbed... URL: From soid.exe at gmail.com Sat Aug 23 07:15:25 2008 From: soid.exe at gmail.com (Grigory Temchenko) Date: Sat, 23 Aug 2008 04:15:25 -0700 (PDT) Subject: How to know a top directory? Message-ID: <0f3ab42d-8fc8-4c23-b255-4be7235ee4ca@s20g2000prd.googlegroups.com> Hey there, Help me please. How to know a top directory? I mean I have path "/this/ is/path" and I wanna get "/this/is". Also I want to use it as platform independent. If I want to pass "c: \that\path" then I need to get "c:\that". Does anyone have ideas? From williamhpurcell at gmail.com Thu Aug 14 09:07:40 2008 From: williamhpurcell at gmail.com (William Purcell) Date: Thu, 14 Aug 2008 08:07:40 -0500 Subject: reading plist files Message-ID: Hi, I'm trying to write a bookmark synchronizer from Firefox/Foxmarks to Safari. The Firefox side of things will be fairly easy and I thought the Safari side would be too. Right now I am simply attempting to read my Bookmarks.plist file using plistlib.py. Here is my attempt to read the file along with the traceback that I get... ------------------------------------------------------------------------------------------------------------------------------------------- In [1]: import plistlib In [2]: plistlib.Plist.fromFile('Bookmarks.plist') fileobj ---> --------------------------------------------------------------------------- Traceback (most recent call last) /home/william/williamFAT/utilities/mac_projs/ in () /usr/lib/python2.5/plistlib.py in fromFile(cls, pathOrFile) 339 def fromFile(cls, pathOrFile): 340 """Deprecated. Use the readPlist() function instead.""" --> 341 rootObject = readPlist(pathOrFile) 342 plist = cls() 343 plist.update(rootObject) /usr/lib/python2.5/plistlib.py in readPlist(pathOrFile) 75 didOpen = 1 76 p = PlistParser() ---> 77 rootObject = p.parse(pathOrFile) 78 if didOpen: 79 pathOrFile.close() /usr/lib/python2.5/plistlib.py in parse(self, fileobj) 401 parser.CharacterDataHandler = self.handleData 402 print 'fileobj --->',fileobj --> 403 parser.ParseFile(fileobj) 404 return self.root 405 : not well-formed (invalid token): line 1, column 8 ------------------------------------------------------------------------------------------------------------------------------------------- Also, I can read other plist files fine such as SignaturesByAccount.plist and AddressBookMe.plist. I am trying to do this in Ubuntu with Python2.5. The xml version might also be useful... In [4]: xml.__version__ Out[4]: '0.8.4' Thanks, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From george.sakkis at gmail.com Fri Aug 22 09:52:42 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 22 Aug 2008 06:52:42 -0700 (PDT) Subject: codecs, csv issues Message-ID: <8aafd67e-6633-4371-a880-805d07089400@k37g2000hsf.googlegroups.com> I'm trying to use codecs.open() and I see two issues when I pass encoding='utf8': 1) Newlines are hardcoded to LINEFEED (ascii 10) instead of the platform-specific byte(s). import codecs f = codecs.open('tmp.txt', 'w', encoding='utf8') s = u'\u0391\u03b8\u03ae\u03bd\u03b1' print >> f, s print >> f, s f.close() This doesn't happen for the default encoding (=None). 2) csv.writer doesn't seem to work as expected when being passed a codecs object; it treats it as if encoding is ascii: import codecs, csv f = codecs.open('tmp.txt', 'w', encoding='utf8') s = u'\u0391\u03b8\u03ae\u03bd\u03b1' # this works fine print >> f, s # this doesn't csv.writer(f).writerow([s]) f.close() Traceback (most recent call last): ... csv.writer(f).writerow([s]) UnicodeEncodeError: 'ascii' codec can't encode character u'\u0391' in position 0: ordinal not in range(128) Is this the expected behavior or are these bugs ? George From cjw at ncf.ca Sun Aug 17 14:27:57 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sun, 17 Aug 2008 14:27:57 -0400 Subject: like a "for loop" for a string In-Reply-To: References: Message-ID: Alexnb wrote: > Okay, so lets say you have a list: > > funList = [1,2,3,4,5] > > and you do: > > for x in funList: > print x > > this will print 1-5 > But I am wondering is there a way to something like this: > > funString = "string string string non-string non-string string" > and > for "string" in funString: > print something > > I know you can't do that; but, is there a way do do something similar that > gets the same result? Your funString has six elements, funList has five. How do you want the result to appear on the page? It is possible that the % operator could help you. Colin W. From steve at REMOVE-THIS-cybersource.com.au Sat Aug 2 23:46:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 03 Aug 2008 03:46:33 GMT Subject: Profiling weirdness: Timer.timeit(), fibonacci and memoization References: <59994541-2fb7-450c-ac14-9922d87b6aa1@m45g2000hsb.googlegroups.com> Message-ID: <00a52572$0$20316$c3e8da3@news.astraweb.com> On Sat, 02 Aug 2008 06:02:02 -0700, ssecorp wrote: > I am not clear about the results here. > > > from timeit import Timer > import Decorators > > def fib(n): > a, b = 1, 0 > while n: > a, b, n = b, a+b, n-1 > return b [...] > s = 100 > > t1 = Timer('fib(s)', 'from __main__ import fib, s') > t2 = Timer('fibmem(s)', 'from __main__ import fibmem, s') > t1.repeat(number=1) > t2.repeat(number=1) > print t1.timeit() > print t2.timeit() > > > 35.3092010297 > 1.6516613145 > > So memoization is 20+ times faster than the idiomatic way? Or am I > missing something here? Memoization *can be* faster, not *is* -- memoization requires work, and if it is more work to look something up than to calculate it, then it will be a pessimation instead of an optimization. That's probably less of an issue with high-level languages like Python, but in low level languages you would need to start thinking about processor caches and all sorts of complications. But I digress... in Python, yes, I would expect a significant speedup with memoization. That's why people use it. > Ok for fun I added memoization to the idiomatic one: [...] > didn't think it would make a difference there but it certainly did. > > 1.59592657726 > 1.60179436213 Just curious, but why don't you show the results of the call to repeat()? It makes me uncomfortable to see somebody showing only half their output. But yes, with memoization, the lookup to find the Fibonacci number should decrease the time it takes to calculate the Fibonacci number. I'm not sure why you are surprised. Regardless of which Fibonacci algorithm you are using, the Timer object is essentially timing one million lookups, minus 100 calculations of the Fibonacci number. The 999,900 cache lookups will dominate the time, far outweighing the 100 calculations, regardless of which method of calculation you choose. That's why the results are almost identical. -- Steven From tjreedy at udel.edu Tue Aug 5 15:16:36 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 05 Aug 2008 15:16:36 -0400 Subject: Link Checking Issues - Sub domains In-Reply-To: <1e36d085-1b73-4576-ba16-dd5fa5e86519@x35g2000hsb.googlegroups.com> References: <1e36d085-1b73-4576-ba16-dd5fa5e86519@x35g2000hsb.googlegroups.com> Message-ID: rpupkin77 wrote: > Hi, > > I have written this script to run as a cron that will loop through a > text file with a list of urls. It works fine for most of the links, > however there are a number of urls which are subdomains (they are > government sites) such as http://basename.airforce.mil, these links > are always throwing 400 errors even though the site exists. Have you looked at urllib/urllib2 (urllib.request in 3.0) for checking links? If 'http://basename.airforce.mil' works typed into your browser, this from the doc for urllib.request.Request might be relevant: "headers should be a dictionary, and will be treated as if add_header() was called with each key and value as arguments. This is often used to ?spoof? the User-Agent header, which is used by a browser to identify itself ? some HTTP servers only allow requests coming from common browsers as opposed to scripts. For example, Mozilla Firefox may identify itself as "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11", while urllib?s default user agent string is "Python-urllib/2.6" (on Python 2.6)." From grflanagan at gmail.com Thu Aug 14 13:50:20 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Thu, 14 Aug 2008 19:50:20 +0200 Subject: Formatting input text file In-Reply-To: <70e8a7c3-b16e-4f3a-960a-bf83f89563f0@d77g2000hsb.googlegroups.com> References: <70e8a7c3-b16e-4f3a-960a-bf83f89563f0@d77g2000hsb.googlegroups.com> Message-ID: victor.herasme at gmail.com wrote: > Hi, > > it's me again with tons of questions. I hava an input file structured > like this: > > X XYData-1 > > 1. 3.08333 > 2. 9.05526 > 3. 3.13581 > ....... > > X XYData-2 > > 1. 4.08322 > 2. 4.02526 > 3. 3.95891 > ............... > > i want to format it so i only get the second column, in order to place > it in a mxn matrix. Let's say i want this: > > number1 number2 number3 > number4 number5 number6 > def iter_data(fileobj, numcols=3): i = 0 keys = [str(j) for j in range(1, numcols+1)] for line in fileobj: if not line.strip(): continue parts = line.split() if len(parts) != 2: continue key, val = parts[0].strip()[:-1], parts[1].strip() if key in keys: i = (i % numcols) + 1 while key > str(i): yield None i = (i % numcols) + 1 yield val elif i and val.startswith('XYData-'): # reset index for a new data row, also padding previous row while i < numcols: yield None i += 1 def iter_coords(numcols): row = 0 while True: yield divmod(row, numcols) row += 1 from itertools import izip from StringIO import StringIO data = ''' X XYData-1 1. 3.08333 2. 9.05526 3. 3.13581 X XYData-2 2. 4.02526 3. 3.95891 X XYData-3 1. 4.08322 2. 3.95891 X XYData-4 1. 3.08333 3. 3.13581 X XYData-5 1. 3.08333 2. 9.05526 4. 3.13581 5. 3.13581 ''' print buf = StringIO(data) k = 0 for item in iter_data(buf, 5): if k % 5 == 0: print print '| %s%s' % (item, ' ' * (8-len(str(item)))), k += 1 print buf = StringIO(data) for item in izip(iter_coords(5), iter_data(buf, 5)): print item print buf = StringIO(data) d = dict(izip(iter_coords(5), iter_data(buf, 5))) print d ++++++++++++++++++++++++++++++++++++++++++++++ | 3.08333 | 9.05526 | 3.13581 | None | None | None | 4.02526 | 3.95891 | None | None | 4.08322 | 3.95891 | None | None | None | 3.08333 | None | 3.13581 | None | None | 3.08333 | 9.05526 | None | 3.13581 | 3.13581 ((0, 0), '3.08333') ((0, 1), '9.05526') ((0, 2), '3.13581') ((0, 3), None) ((0, 4), None) ((1, 0), None) ((1, 1), '4.02526') ((1, 2), '3.95891') ((1, 3), None) ((1, 4), None) ((2, 0), '4.08322') ((2, 1), '3.95891') ((2, 2), None) ((2, 3), None) ((2, 4), None) ((3, 0), '3.08333') ((3, 1), None) ((3, 2), '3.13581') ((3, 3), None) ((3, 4), None) ((4, 0), '3.08333') ((4, 1), '9.05526') ((4, 2), None) ((4, 3), '3.13581') ((4, 4), '3.13581') {(1, 3): None, (3, 0): '3.08333', (2, 1): '3.95891', (0, 3): None, (4, 0): '3.08333', (1, 2): '3.95891', (3, 3): None, (4, 4): '3.13581', (2, 2): None, (4, 1): '9.05526', (1, 1): '4.02526', (3, 2): '3.13581', (0, 0): '3.08333', (0, 4): None, (1, 4): None, (2, 3): None, (4, 2): None, (1, 0): None, (0, 1): '9.05526', (3, 1): None, (2, 4): None, (2, 0): '4.08322', (4, 3): '3.13581', (3, 4): None, (0, 2): '3.13581'} From sln at netherlands.com Fri Aug 22 19:36:07 2008 From: sln at netherlands.com (sln at netherlands.com) Date: Fri, 22 Aug 2008 23:36:07 GMT Subject: The Importance of Terminology's Quality References: <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: On Fri, 22 Aug 2008 23:23:57 +0000 (UTC), Martin Gregorie wrote: >On Fri, 22 Aug 2008 22:56:09 +0000, sln wrote: > >> On Thu, 21 Aug 2008 09:11:48 -0500, rpw3 at rpw3.org (Rob Warnock) wrote: >> >>>sln at netherlands.com> wrote: >>>*IS* raw machine code, *NOT* assembler!! >> [snip] >> >> I don't see the distinction. >> Just dissasemble it and find out. >> >There's a 1:1 relationship between machine code and assembler. >Unless its a macro-assembler, of course! > >> >> Each op is a routine in microcode. >> That is machine code. Those op routines use machine cycles. >> >Not necessarily. An awful lot of CPU cycles were used before microcode >was introduced. Mainframes and minis designed before about 1970 didn't >use or need it and I'm pretty sure that there was no microcode in the >original 8/16 bit microprocessors either (6800, 6809, 6502, 8080, 8086, >Z80 and friends). > >The number of clock cycles per instruction isn't a guide either. The only >processors I know that got close to 1 cycle/instruction were all RISC, >all used large lumps of microcode and were heavily pipelined. > >By contrast the ICL 1900 series (3rd generation mainframe, no microcode, >no pipeline, 24 bit word) averaged 3 clock cycles per instruction. >Motorola 6800 and 6809 (no microcode or pipelines either, 1 byte fetch) >average 4 - 5 cycles/instruction. Surely you have caved to intelligence. And there is nothing beyond op. What has the friggin world come to!!! sln From grante at visi.com Tue Aug 12 16:33:52 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 12 Aug 2008 15:33:52 -0500 Subject: Pyserial not getting response every time, input/output errors References: Message-ID: On 2008-08-12, Carsten Haese wrote: > Rainy wrote: >> Hello! >> >> I'm having some trouble with pyserial package, I'm sending commands >> and reading responses from a custom pcb, and sometimes I get a proper >> response, at other times I get nothing, and sometimes I get about half >> of the response string with beginning cut off. About half the time an >> empty string is returned, the other ~half time good response, and more >> rarely I get partial response. >> >> When I try to use the same Serial instance to send/receive a few >> times, I end up getting an input/output error. >> >> Here are some examples: >> >>>>> ser = serial.Serial('/dev/ttyAM1', 115200, timeout=0.1) > > One possible point of failure is that you're not supplying any > parameters for the data format (byte size, parity, stop bits) and flow > control. The Serial object will assume defaults, and those defaults may > or may not be correct. None of those things are capable of creating an input/output error -- you'll just get goofy data values (or no answer from the device at the other end of cable). An input/output error usually means that there are issues with the underlying bus or there are hardware failures. > Try to find out what data format and flow control you should > be using and set explicit Serial parameters accordingly. -- Grant Edwards grante Yow! ... If I had heart at failure right now, visi.com I couldn't be a more fortunate man!! From dbpokorny at gmail.com Wed Aug 20 12:23:22 2008 From: dbpokorny at gmail.com (dbpokorny at gmail.com) Date: Wed, 20 Aug 2008 09:23:22 -0700 (PDT) Subject: exception handling in complex Python programs References: <00bb4e2f$0$20315$c3e8da3@news.astraweb.com> Message-ID: <8cb19b0b-1df8-4c5b-b546-a273c6fbc2e3@j1g2000prb.googlegroups.com> On Aug 19, 4:12?pm, Steven D'Aprano wrote: > On Tue, 19 Aug 2008 11:07:39 -0700, dbpoko... at gmail.com wrote: > > ? def do_something(filename): > > ? ? if not os.access(filename,os.R_OK): > > ? ? ? return err(...) > > ? ? f = open(filename) > > ? ? ... > > You're running on a multitasking modern machine, right? What happens when > some other process deletes filename, or changes its permissions, in the > time after you check for access but before you actually open it? This is a good point - if you want to use the correct way of opening files, and you don't want to worry about tracking down exception types, then we can probably agree that the following is the simplest, easiest-to-remember way: def do_something(filename): try: f = open(filename) except: ... Opening files is a special case where EAFP is the only correct solution (AFAIK). I still liberally sprinkle LBYL-style "assert isinstance(...)" and other similar assertions in routines. The point is that EAFP conflicts with the interest of reporting errors as soon as possible (on which much has been written see, for instance Ch. 8 - Defensive Programming in Code Complete), but LBYL conflicts with correctness when objects can be shared. Also, look at the man page for access. I have found at least two (one on my Linux box, another online) that essentially say "never use it." I completely forgot about this in my last post... David From bearophileHUGS at lycos.com Wed Aug 6 22:04:21 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 6 Aug 2008 19:04:21 -0700 (PDT) Subject: Parsing of a file References: Message-ID: <63a07a1e-ca5b-4430-baac-e31691ea8c0c@m45g2000hsb.googlegroups.com> Paul McGuire: > This code creates a single dict for the input lines, keyed by id. > Each value contains elements labeled 'id', 'ra', and 'mjd'. ... > d = dict( > (rec.split()[1][:-1], > dict([('id',rec.split()[1][:-1])] + > [map(str.lower,f.split('=')) > for f in rec.split()[2:5]] ) ) > for rec in data > ) ... Please, don't try to shove the program in one line, use PyParsing :o) Bye, bearophile From nytrokiss at gmail.com Fri Aug 22 17:12:56 2008 From: nytrokiss at gmail.com (James Matthews) Date: Fri, 22 Aug 2008 14:12:56 -0700 Subject: Python one-liner?? In-Reply-To: References: Message-ID: <8a6b8e350808221412u1e131595k72b9fbcc283c3cb2@mail.gmail.com> What i use them for is to test for packages. e.g python -c "import django" On Fri, Aug 22, 2008 at 2:03 PM, Matimus wrote: > > Do we have python one-liner like perl one-liner 'perl -e'?? > > > The answer is python -c... > > but python -h is useful too. > > Matt > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Tue Aug 19 08:14:44 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Aug 2008 14:14:44 +0200 Subject: WindowsXP/ CTypes - How to convert ctypes array to a string? In-Reply-To: References: Message-ID: dudeja.rajat at gmail.com wrote: > I also add the letter 'v' same as you suggested. However, I'm looking > to store this into some variable ( that variable could be be a string, > tuple or anything, Im not sure which is the suited one) the expression gives you a string object; you'll store it in a variable in the same way as you'd store any other expression result in Python. version = "v%d.%d.%d.%d" % tuple(version) but when you find yourself getting stuck on things like this, it might a good idea to take a step back and read the tutorial again: http://docs.python.org/tut/tut.html pay special attention to the parts that discuss how variables work in Python. if you prefer some other entry level tutorial, the following is said to be really good: http://www.ibiblio.org/g2swap/byteofpython/read/ From maebert at uos.de Mon Aug 25 10:32:41 2008 From: maebert at uos.de (Manuel Ebert) Date: Mon, 25 Aug 2008 16:32:41 +0200 Subject: newbie question In-Reply-To: References: Message-ID: <3BCE7A93-6908-4ABD-AD78-8349FD998EB8@uos.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi sharon, as I understand, you want to remove certain characters of a string. Try: number = int(fetched_number.replace(',', '')) this will first remove any , characters and then convert the string into an integer. Best, Manuel On Aug 25, 2008, at 4:15 PM, sharon k wrote: > hi all, > > i am new to python. > > i fetch a webpage with urllib, extract a few numbers in a format as > follow; > > 10,884 > 24,068 > > my question is how to remove the comma between the number, since i > have to add them up later. > > sorry for my bad english. > -- > http://mail.python.org/mailman/listinfo/python-list -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIssKJcZ70OCIgLecRAkxTAJ4wWKxmlAS8hdQZK0Eoj7pAxwx41wCaA/eI NY9GZKX6+PNIYIGaaghNvZg= =JN2/ -----END PGP SIGNATURE----- From gagsl-py2 at yahoo.com.ar Tue Aug 12 02:17:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Aug 2008 03:17:07 -0300 Subject: WinCvs Macros References: Message-ID: En Thu, 07 Aug 2008 06:22:31 -0300, Ren ChunYi escribi?: > Does anyone here have some doc like WinCVS API? I'm reading WinCvs > integrated Macros, but someplace make me puzzle. Better ask those questions in the WinCVS mailing list (or Yahoo group: http://tech.groups.yahoo.com/group/cvsgui ) -- Gabriel Genellina From mypetslug at gmail.com Wed Aug 20 16:48:10 2008 From: mypetslug at gmail.com (mypetslug at gmail.com) Date: Wed, 20 Aug 2008 13:48:10 -0700 (PDT) Subject: py2exe importing a package not in library.zip Message-ID: Hi, I'm sorry if this has been asked before, but I can't seem to find an answer to this anywhere and so far, trial and error hasn't gotten me far either. Using python 2.4, I've created a testing application. When the app starts up, I do a [code]from tests import *[/code] and it looks at the /tests directory and loads up all the tests it finds at that time. This works fine when interpreting the python code directly. The problem I'm having is trying to create an executable for distribution. What I'd like to be able to do is to include everything in the library.zip *except* the tests directory and then as I (or whoever) creates more and more tests, have the ability to simply drop them into the directory and the next time the app starts, it'll pick them up. However, if I don't include the tests in library.zip, then when I hit the [code]from tests import *[/code], it complains "AttributeError: 'module' object has no attribute 'test1'" when it gets to the first test. And If I do include the tests in the library.zip, it works with the tests that I have now, but then I still can't add any new ones without the attribute error unless I regenerate the exe every time. Basically, it seems like it comes down to importing a package outside the library.zip. So, is there any way to do this with py2exe? Or even another exe creating application? Thanks, MyPetSlug From rpm9deleteme at earthlink.net Mon Aug 4 18:39:26 2008 From: rpm9deleteme at earthlink.net (RPM1) Date: Mon, 04 Aug 2008 18:39:26 -0400 Subject: Wrapping C with Python References: Message-ID: brad wrote: > RPM1 wrote: > ... >> Basically you just compile your C code as a regular C code dll. >> ctypes then allows you to access the functions in the dll very easily. > > Does that work with C++ code too or just C? I believe it does work with C++ although I have not done that. Here's a simple example: http://wolfprojects.altervista.org/dllforpyinc.php I bet if you google around you'll find what you need. Remember there is documentation for ctypes in the Python documentation that comes with Python. Patrick From mail at microcorp.co.za Tue Aug 26 16:32:48 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 26 Aug 2008 22:32:48 +0200 Subject: Python String Immutability Broken! Message-ID: <004501c907bb$0c98f780$0d00a8c0@hendrik> "Simon Brunning": >You can indeed use ctypes to modify the value of a string - see >. You can use it to crash the OS, too. > >My advice - don't. Thanks for the link. Any advice on what to do or use as an I/O structure for dissemination? Ken Seehart: 8<----------- using ctypes to make 1+14 = 10 ------------------ >I love ctypes. So cool. It's not supposed to be safe. And here I thought I was weird? > Life is either a daring adventure or nothing. Security does not > exist in nature, nor do the children of men as a whole experience > it. Avoiding danger is no safer in the long run than exposure. > *Helen Keller * > /US blind & deaf educator (1880 - 1968)/ > >Of course I would not hire anyone who believes this quote, other than >Helen Keller, if she were still with us. Why not? ? as I see it, the Keller quote states the literal truth of the matter ? we all live under an illusion of security ? but then that might just be because I am South African, and the country is run by cattle thieves. >It is quite possible to write a small program that works using abused >strings. But my life better not depend on it. Among other things, if >you use the abused string as a key anywhere, you will not get correct >results. Trying to change the length of the string will cause >disasters. Lengthening a string will corrupt memory, and shortening the >string will not shorten it but rather embed '\0' in it. Understood. ? remember I am using it as a kind of array of ?pseudoports? - memory representations of what goes on on wires on the outside. So only a real madman would try to impute the kind of cross bit correlation needed to use the bunch of bits as a key. The length would be fixed, governed by the existence of real hardware on the outside. Ken Seehart again: >Yes, there is a better way. Use a character array instead of a string. The original reason I used a string directly instead of array.array was to try to skip the serialisation step when disseminating the information via sockets. As you can appreciate, this is all ?hot stuff? as it represents said wire states, and is of interest system wide. So lets explore this further ? lets say I use two arrays ? one to represent the stuff that must be output, and one to represent the latest inputs read. Then, I think, first prize would be the ability to ?publish? that information as a shared memory block, that can be accessed by other python processes. Then it will be possible to a priori ?chop up the ownership? of the various bits, so that a process can simply monitor the bits of interest to it, setting or clearing the bits of the outputs it is responsible for. In this way the work could be divided amongst many processes. Then, on a periodic basis, the I/O would be done, much like one would do it in an embedded system using an interrupt driven ticker routine. That would be really cool. Does anybody know how to get such memory sharing done in Python? (Linux only) - Hendrik From dullrich at sprynet.com Sat Aug 2 12:16:32 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Sat, 02 Aug 2008 11:16:32 -0500 Subject: PIL (etc etc etc) on OS X References: <489379A7.5060009@codebykevin.com> Message-ID: >From the other reply it seems I may not need to worry about any of this. Otoh I've had issues with pythonmac versus OSX versions, etc, in the past. Just in case, also in the spirit of that curious idea that learning things is good: First, it occurred to me that I've got wxPython installed and it includes jpeg support. I don't suppose that means that wxPython has already put a libjpeg somewhere and I just need to tell PIL where it is? Regardless, about your suggestions below (again, any assertions here are really questions): Presumably jibjpeg needs to be unzipped into its own directory, or configure/make etc wouldn't be able to figure out what I want to make. Presumably that happens automatically when I unzip it. Then after I do the configure/make/sudo make install will libjpeg automatically be in some standard place? If not, what's a good choice of standard place to put it, and how do I put it there? (If I start here then it will unzip to there, and then after I make it there it will be installed in this third place, which is where I want it.) Thanks. Sorry to be so dumb - yes, it's perfectly reasonable for eff to assume that people using PIL are programmers. With a "new thing" in, say, Python I'd just try something and then figure out what to try next to make it work - I don't want to take that approach here lest I re-make part of Darwin or something. Once many years ago I learned a new thing: Attempting to run a sufficiently invalid DOS exe could cause physical damage to a hard drive... that wasn't the only thing I learned that day. (Probably won't get back to this til Monday, btw, in case you say something and I don't seem interested.) DU. In article <489379A7.5060009 at codebykevin.com>, Kevin Walzer wrote: > David C. Ullrich wrote: > > Decided to try to install PIL on my Mac (OS X.5). > > OK, sounds good. > > > > I know nothing about installing programs on Linux, > > nothing about building C programs, nothing about > > installing libraries, nothing about "fink", nothing > > about anything. Please insert question marks after > > every sentence: > > For the record, OS X isn't Linux--it's a variant of BSD Unix. Similar, > but no identical, to Linux. > > > > > I saw a "BUILDME" with instructions "for lazy programmers". > > I did that. It seems that everything worked except a > > jpg library is missing. > > OK. > > > > > I read that I need to install libjpeg. I read that on OS X > > this is "usually" done using fink. Great: > > > > (i) The idea of installing fink scares me, for no reason > > I could name. There's no way that's going to confuse the > > rest of Darwin, right? > > You don't really need Fink just to install libjpeg. You do need the > developer tools (Xcode) installed, otherwise you can't build any > software at all. > > Libjpeg can be downloaded from http://www.ijg.org/. Download it, > untar/unzip it. Fire up terminal, cd to the libjpeg directory, and type > these commands: > > configure > make > sudo make install > > That should get libjpeg built and installed. > > > > > (ii) When I look at the fink website I see a list of > > supported libraries, not including libjpeg. > > So don't worry about Fink. > > > > > I hate messing with things that I don't understand at _all_... > > Well, that's understandable, but this is your chance to learn something > new. > > > > Thanks for any advice or comments. > > > > DU. > > > --Kevin -- David C. Ullrich From timr at probo.com Thu Aug 28 02:59:08 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 28 Aug 2008 06:59:08 GMT Subject: struct.Struct random access References: Message-ID: castironpi wrote: > >I'd like to seriously nominate this idea and get a considered opinion >on it. > >struct.Struct lets you encode Python objects into structured memory. >It accepts a format string, and optionally a buffer and offset to/from >which to read/write the structure. What do you think of random access >to the results? To avoid Marc's concern about meaningless anonymous >record entries, model the constructor after 'namedtuple' type. > >(unproduced) >>>> packer= struct.Struct( 'IIIf255p', 'i1 i2 i3 afloat name' ) >>>> packer.pack_into( buf, off, 10, 20, 30, 0.5, 'abc' ) >>>> packer.unpack_from( buf, off, 'i3' ) >30 >>>> packer.unpack_from( buf, off ) >( 10, 20, 30, 0.5, 'abc' ) >>>> packer.pack_into( buf, off, 'i1', 12 ) What data type would you expect "buf" to be? Your design requires it to be both an input and an output parameter. Today's "struct" converts into and out of a string, and strings are immutable. So, to continue with that standard, you would have to pass a string into "pack_into" and have the modified result returned as an output: buf = packer.pack_into( None, 0, 10, 20, 30, 0.5, 'abc' ) buf = packer.pack_into( buf, 0, 'i1', 12 ) In the end, I'm not sure you are really saving anything. >Even in sequential access speed benefits, by avoiding the construction >of n-1 objects. This is a fairly major change, because it requires a "struct.Struct" object to maintain state, something that the "struct" module currently does not do. In my personal opinion, this is a rather large and confusing change, for very little benefit. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From paul at boddie.org.uk Sun Aug 17 15:46:44 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 17 Aug 2008 12:46:44 -0700 (PDT) Subject: dynamic attribute syntax References: Message-ID: On 17 Aug, 21:29, castironpi wrote: > > What are the changes, pros and cons, involved in something like: > > obj:att for a dynamic access, and obj.att for static? A previous proposal and discussion can be found here: http://www.python.org/dev/peps/pep-0363/ Paul From tjreedy at udel.edu Mon Aug 11 17:56:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 11 Aug 2008 17:56:21 -0400 Subject: eval or execute, is this the (most) correct way ? In-Reply-To: <48A07B27.5060308@gmail.com> References: <00b06501$0$14351$c3e8da3@news.astraweb.com> <48A07B27.5060308@gmail.com> Message-ID: Stef Mientki wrote: > Steven D'Aprano wrote: >> The best solution is not to re-invent the wheel: "import code" is the >> way to emulate Python's interactive interpreter. > sorry, but that confuses me even more, "The code module provides facilities to implement read-eval-print loops in Python. Two classes and convenience functions are included which can be used to build applications which provide an interactive interpreter prompt." IDLE uses it to do just that. File idelib/pyshell.py imports InteractiveInterpreter. A quarter of the file is the definition of class ModifiedInterpreter(InteractiveInterpreter): > I don;t have a file / module, > just a workspace and one or more lines of code in memory. The code module has many options. "InteractiveConsole.push(line) Push a line of source text to the interpreter. " Anyway, your first post indicated that those 'lines of code in memory' originate from console input, which, I believe, is the default input source for the classes. You will need to experiment to see just how they work. >> Doing a search of the file code.py, I don't find the string "eval" at >> all. My guess is that your approach is probably not the best way. It would use 'exec' on statements, even if they happen to be expression statements. Exec is not going away. It is a built-in function in 3.0. Terry Jan Reedy From brencam at gmail.com Wed Aug 27 03:12:23 2008 From: brencam at gmail.com (BrendanC) Date: Wed, 27 Aug 2008 00:12:23 -0700 (PDT) Subject: Inspecting the Instance Vars in a class/object - How? Message-ID: <1efcc029-17cc-4d5e-b70b-2a2e25dfd214@k36g2000pri.googlegroups.com> I'm trying to understand reflection/introspection in Python. How can I identify the the type of attribute (e.g. instance var) in a class? The following returns all the class attributes (methods and instance vars). However I'm interested in identifying the type of value for each case - (e.g. I'd like to identify the instance variables separately). (The Inspect module has an ismethod method, but not an isinstancevariable method). e.g. In the following example I'd like to extract the class vars strvar and intNum and ignore the methods/other attribute types. What is the best way to do this? class test: # Dummy Class for reflection testing strVar = '1234' intNum = 0 def nullmethod(): pass def addmethod(self,v1, v2): v = v1 + v2 return v if __name__ == "__main__": mytest = test() for key in dir(mytest): value = getattr(object, key) print 'Key: %s ; Value %s ' % (str(key) ,str(value)) From norseman at hughes.net Thu Aug 14 19:54:30 2008 From: norseman at hughes.net (norseman) Date: Thu, 14 Aug 2008 16:54:30 -0700 Subject: The Importance of Terminology's Quality In-Reply-To: <48a4b2ba$0$20923$607ed4bc@cv.net> References: <48617847$0$5021$607ed4bc@cv.net> <486ae06b$0$5011$607ed4bc@cv.net> <4883bc90$0$7327$607ed4bc@cv.net> <48a4b2ba$0$20923$607ed4bc@cv.net> Message-ID: <48A4C5B6.1070109@hughes.net> John W Kennedy wrote: > Robert Maas, http://tinyurl.com/uh3t wrote: >> John W Kennedy wrote: >> JWK> Into the 60s, indeed, there were still machines being made >> JWK> that had no instruction comparable to the mainframe BASx/BALx >> JWK> family, or to Intel's CALL. You had to do a subprogram call by >> JWK> first overwriting the last instruction of what you were >> JWK> calling with a branch instruction that would return back to >> JWK> you. >> HUMMmmmmm! Brings back memories. The Monroe-bot 9, Olivetti, Sperry-Rand and the rest. I came in on the IBM-360 original series in the mid-60'. Subroutine docs were important. You needed to know from which register the sub was going to use/store the return address. (As well as which registers it used for what both incoming and out going.) it's been so long I forget the actual mnemonics. something like: . . load R12,rtn89 (alt) jump sub32 sub32: sub32: rtn89: stor R12,safe . . . . . . jump R12 rtrv R12,safe jump R12 Programs were simple then. Card, paper tape, mag tape IN and card, paper tape, mag tape and hardcopy paper OUT. The monitor was the guy who looked at the flashing lights on the metal panel. And to change a program on the 1401 usually required the soldering iron, patch cables and a patch board! And a new deck of cards containing the next program. Don't use a used deck 'cause then the reader will eat the cards. :) I helped Chevron East convert from 1401 to 360. Long ago, far away and with no intention of returning to those long long hours in 'the room'. LSI??? Ha-Ha. Anyone remember the word transistor?. Power supply was tubes. However, core was 3-axis iron core. That I miss. 17 flip switches set 1-16 & flip 17 to load first half word set 1-16 & flip 17 to load 2nd half word 1st boot word ready . . core boot loaded mag master 1 and read next sequence which ... only took 45 min. to boot if first effort succeeded. Otherwise... it was going to be a long day.... The "Good 'Ole Days"? Point of view. Code was tight and comradely was what kept us going. The long hours and being shunned by company people as gargoyles down there or some such - I can do without. ...(snip) Steve norseman at hughes.net OH- If the sub might be called other than as if in-line, an area of memory was given to safe and it would be incremented/decremented upon use. safe was just an address. safe dw 40 or whatever From mensanator at aol.com Sat Aug 9 11:07:26 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 9 Aug 2008 08:07:26 -0700 (PDT) Subject: list question... unique values in all possible unique spots References: Message-ID: <57fcf019-1afd-4c48-b329-42a0ffc4c5ac@x35g2000hsb.googlegroups.com> On Aug 9, 8:05?am, ToshiBoy wrote: > I'm wondering how to do this the most elegant way: I found this quiz > in some magazine. I've already solved it on paper, but want to write a > python program to solve it. It comes down to being able to represent > range(1,27) through a number of formulas. How do I write a loop that > will loop through this list, so that: 1. every number only occurs > once, and 2. I get every possibility of order within the list? I guess > it'd be somewhat similar to Sudoku, where you have the numbers from > 1-9 in any possible order. Here it's 1-26. Python 2.6 has a permutation function: IDLE 2.6b1 >>> import itertools >>> for i in itertools.permutations(range(4)): print i (0, 1, 2, 3) (0, 1, 3, 2) (0, 2, 1, 3) (0, 2, 3, 1) (0, 3, 1, 2) (0, 3, 2, 1) (1, 0, 2, 3) (1, 0, 3, 2) (1, 2, 0, 3) (1, 2, 3, 0) (1, 3, 0, 2) (1, 3, 2, 0) (2, 0, 1, 3) (2, 0, 3, 1) (2, 1, 0, 3) (2, 1, 3, 0) (2, 3, 0, 1) (2, 3, 1, 0) (3, 0, 1, 2) (3, 0, 2, 1) (3, 1, 0, 2) (3, 1, 2, 0) (3, 2, 0, 1) (3, 2, 1, 0) Bur bear in mind that permutations of size n are n!. So the permutaions of range(1,27) is 26! which is >>> print gmpy.fac(26) 403291461126605635584000000 That's 403 octillion. Are you sure you want to do this? From jura.grozni at gmail.com Sat Aug 9 11:52:28 2008 From: jura.grozni at gmail.com (azrael) Date: Sat, 9 Aug 2008 08:52:28 -0700 (PDT) Subject: Ascii to binary conversion References: <9a2f9777-8261-4365-a741-a3edab83266a@n38g2000prl.googlegroups.com> Message-ID: You see, I don't like reading some tutorials. I pick myself a problem and look for ways to slove it. I am using Python for about 2 years, but mostly for image processing. As you say, ord is oposite to chr. I learn by example. thnx guys, this looks great On 9 kol, 16:47, Larry Bates wrote: > azrael wrote: > > looks nice. is there an oposite function of ord() so I could also > > bring a binary number also back to ascii. > > > the speed matters if you plan to exchange about 10 M ascii chars and > > don't wont to wait a year for the results. :) > > > On 9 kol, 15:39, John Machin wrote: > >> On Aug 9, 11:18 pm, azrael wrote: > > >>> Hy folks, > >>> I googled, and searched, and can not bealive that I have not found a > >>> built in way to convert the easy and elegant python way a function to > >>> easily convert simple ascii data to binary and back. > >>> I've written some my own but they were pretty slow using binascii > >>> linbrary with hexifly and unhexifly functions conbined with a > >>> lookuptable of binary and hex values. > >>> Any idea how to easily write a function that recieves a character or > >>> string and returns a binary number like: > >>> ascii("1") is converted to bin("00110001") > >> Here's one way: > > >>>>> def a2b(a): > >> ... ? ?ai = ord(a) > >> ... ? ?return ''.join('01'[(ai >> x) & 1] for x in xrange(7, -1, -1)) > >> ... > > >>>>> a2b('1') > >> '00110001' > >>>>> a2b('2') > >> '00110010' > >>>>> a2b(chr(0)) > >> '00000000' > >>>>> a2b(chr(255)) > >> '11111111' > > >> BUT ... why are you doing this so much that the speed matters??? > > Opposite of ord() is chr(). ?These functions have been available in every > language I've used for the last 30 years. ?I would suggest that you might want > to spend a little time reading a good Python book and to work through the > tutorial. ?It will be worth your investment of time. > > -Larry From inquiry at officeexpander.com Sat Aug 16 13:03:47 2008 From: inquiry at officeexpander.com (Office Expander) Date: Sat, 16 Aug 2008 13:03:47 -0400 Subject: Plot pkg - Multiple Y axes? Message-ID: <9D73D2B0-A506-4097-A087-92C6E48A8D3E@officeexpander.com> Hello, You can make Multiple Y Axes plots in Excel using Multy_Y or EZplot. There is a demo version at www.OfficeExpander.com Cheers! ______________________________________ Hello, I'm searching for a plotting package that will allow multiple y axes of different scales. For example I'd like to overlay 4 or 5 time series with each series having a separate axis. Does anyone know of such a package? Thank you, Frank From castironpi at gmail.com Fri Aug 22 18:42:02 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 22 Aug 2008 15:42:02 -0700 (PDT) Subject: In-place memory manager, mmap (was: Fastest way to store ints and floats on disk) Message-ID: <1cf85075-17a1-4a1d-8ea5-bf5104541528@s50g2000hsb.googlegroups.com> Hi, I've got an "in-place" memory manager that uses a disk-backed memory- mapped buffer. Among its possibilities are: storing variable-length strings and structures for persistence and interprocess communication with mmap. It allocates segments of a generic buffer by length and returns an offset to the reserved block, which can then be used with struct to pack values to store. The data structure is adapted from the GNU PAVL binary tree. Allocated blocks can be cast to ctypes.Structure instances using some monkey patching, which is optional. Want to open-source it. Any interest? From bedouglas at earthlink.net Tue Aug 26 17:22:43 2008 From: bedouglas at earthlink.net (bruce) Date: Tue, 26 Aug 2008 14:22:43 -0700 Subject: libxml2dom - parsing maligned html In-Reply-To: <78db1ed5-49d5-47ab-893d-925fedb96357@p10g2000prf.googlegroups.com> Message-ID: <008e01c907c1$e1b0c230$0301a8c0@tmesa.com> hi paul... so you're the guy behind the libxml2dom ehh..!! glad to say hey! so this really is an issue with libxml2dom. ok, good, at least i know where the issue is. and yeah, i know the real issue is the fact that the html isn't valid!! shouldn't have multiple "html" trees... from what i can tell, this isn't really solved via tidy/beautifulsoup either, as a multiple html tree structure probably won't be looked at as being invalid fom a token perspective. ok, i can somehow live with this, i can accommodate it. but tell me, when the parse module/class for libxml2dom does its thing, why does it not go forward on the tree when it comes to a , if there's more text in the string to process??? oh, also, regarding screen parsing/crawling, i've seen a number of sites that have discussed using a web testing app, like selinium, and driving a browser process, in order to really capture all the required data. any thoughts on the pros/cons of this kind of approach to scraping data... thanks -bruce -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Paul Boddie Sent: Tuesday, August 26, 2008 8:48 AM To: python-list at python.org Subject: Re: libxml2dom - parsing maligned html On 26 Aug, 17:28, "bruce" wrote: > so it's as if the parseString only reads the initial "html" tree. i've > reviewed as much as i can find regarding libxml2dom to try to figure out how > i can get it to read/parse/handle both html trees/nodes. Maybe there's some possibility to have libxml2 read directly from a file descriptor and to stop after parsing the first document, leaving the descriptor open; currently, this isn't supported by libxml2dom, however. Another possibility is to feed text to libxml2 until it can return a well-formed document, which I do as part of the libxml2dom.xmpp module, but I don't really support this feature in the public API. Again, improvements to libxml2dom may happen if I find the time to do them. Paul -- http://mail.python.org/mailman/listinfo/python-list From srinuakula89 at yahoo.com Tue Aug 19 09:15:54 2008 From: srinuakula89 at yahoo.com (srinu) Date: Tue, 19 Aug 2008 06:15:54 -0700 (PDT) Subject: View this blogspot Message-ID: <79fbc483-87aa-424a-91ca-9d975c1e0c28@j1g2000prb.googlegroups.com> http://indianmasalavideos4u.blogspot.com/ From deets at nospam.web.de Tue Aug 26 09:09:16 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Aug 2008 15:09:16 +0200 Subject: property() usage - is this as good as it gets? References: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> <48b3bedd$0$4472$426a34cc@news.free.fr> <794a023d-be80-4849-b508-e448b90cc3b4@a3g2000prm.googlegroups.com> Message-ID: <6hidktFlt0voU2@mid.uni-berlin.de> > P.S. How did my post manage to ignite a mini flame war?! Because of the high resident troll quota in replies - which is created by just one rather annoying member of this community... Diez From ggpolo at gmail.com Thu Aug 28 15:17:16 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 28 Aug 2008 16:17:16 -0300 Subject: ImageTk.Photoimage not displayed In-Reply-To: References: Message-ID: On Thu, Aug 28, 2008 at 4:07 PM, harryos wrote: > hi > i am trying to display an image on a canvas in a gui made with Tkinter > widgets > > > class PhotoDisplay: > def __init__(self,parent): > self.mainframe = Frame(parent,background="grey") > ..... > #added a subframe to hold canvas and button > .... > self.canvFrame=Frame(self.mainframe,...) > .... > self.mycanvas=Canvas(self.canvFrame,...) > ... > > def okbuttonClick(self): > self.mycanvas.delete(ALL) > myimagename=...#get an imagefilename from somewhere.. > self.showSelectedImage(myimagename) > > def showSelectedImage(self,imageName): > myimg=ImageTk.PhotoImage(file=imageName) > imgtag=self.mycanvas.create_image(70,100,image=myimg) > self.mycanvas.update_idletasks() > > > when i click the button ,the image is displayed for a fraction of a > second on the canvas and disappears.I couldn't figure out why this is > happening.I am quite new to Tkinter and still going thru Fredrik > Lundh's intro to tkinter..can someone tell me if i am doing sthing > wrong here? You have to keep a reference to these images you are creating, otherwise as soon as those methods finishes they are gone. > thanks in advance > harry > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From b-cousson at ti.com Wed Aug 13 11:32:00 2008 From: b-cousson at ti.com (Cousson, Benoit) Date: Wed, 13 Aug 2008 17:32:00 +0200 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: <76fd5acf0808121415h41cc580bj85d96e648c54ab4b@mail.gmail.com> References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> <76fd5acf0808120651u259e5d8dt32a8d49bb5d77add@mail.gmail.com> <200808122240.22517.maric@aristote.info> <76fd5acf0808121415h41cc580bj85d96e648c54ab4b@mail.gmail.com> Message-ID: <74583B8642AB8841B30447520659FCA92CC054B5@dnce01.ent.ti.com> > Defining it as a nested class saves you one line > of code, but IMHO makes the result just a bit more cluttered, while > reducing the elegance of reusing the metaclass. The whole point of nested class is to avoid polluting the namespace with classes that are only used locally. So the argument about the elegance of reusing is not very valid in that case. I agree that they are other ways using module to avoid namespace pollution, but in some case it is easier to use nested class instead and keep everything in the same file. In my case, I'm trying to use a similar approach as XIST's one, meaning using Python class to model hierarchical data. So clearly nested class is a very nice and easy understandable way to do that. > Here are only a few examples of threads giving good reasons against > class nesting. I've never seen any good arguments for it. There are > dozens of good reasons we don't encourage it and won't actively > support it. > > http://mail.python.org/pipermail/python-dev/2005-March/052454.html > http://mail.python.org/pipermail/python-dev/2002-November/029872.html >From what I quickly read in these email threads, except for the pickling issue and the fact that Guido does not like nested classes, I do not see strong argument against it either. Regards, Benoit From lists at cheimes.de Thu Aug 14 16:42:24 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 14 Aug 2008 22:42:24 +0200 Subject: negative numbers are not equal... In-Reply-To: <48A4932F.4010302@gmail.com> References: <48A4932F.4010302@gmail.com> Message-ID: ariel ledesma wrote: > i read that 'is' compares if they are really the same object, but i > don't that's it because then why does -5 return True? > of course i could only use == to compare, but still, what am i missing > here? Rule of thumb: Never use 'is' with any kind of string or numeric object. 'is' is not a comparison operator. It checks for object identity. You are getting the result because Python optimized small integers. See http://svn.python.org/projects/python/trunk/Objects/intobject.c Integers between -5 and +256 are singletons as are some other objects like strings with one element or empty tuples. You must not rely on the optimization. Christian From stefan_ml at behnel.de Tue Aug 19 14:32:13 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 19 Aug 2008 20:32:13 +0200 Subject: HTML Tables In-Reply-To: References: Message-ID: <48ab11ad$0$11730$9b4e6d93@newsspool1.arcor-online.net> Amie wrote: > Thanks for your help so far. Ok here's a scenario: I have to create a > site that displays 34 html tables. > In each of these tables the following information has to be displayed: > logo (image), site name, date, time. > Remember: in all of these 34 tables. the information displayed on each > of these tables is retrieved from the database. I did write a mysql > query, I just don't know how to link it with the for loop that has to > display all these tables. If anyone can, can you roughly show me how > to go about doing this. This might get you going: http://codespeak.net/lxml/lxmlhtml.html#creating-html-with-the-e-factory Try something like this: tables = [] for row in rows_returned_by_the_query: tables.append( E.TABLE( ... ) ) html_body = E.BODY( *tables ) Stefan From elessar at nienna.org Fri Aug 1 08:28:09 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 01 Aug 2008 06:28:09 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <9f4b1c12-d010-45f6-91ee-d490e2f850dc@79g2000hsk.googlegroups.com> Message-ID: <48930159.2020306@nienna.org> Antoon Pardon wrote: > On 2008-08-01, Erik Max Francis wrote: >> Antoon Pardon wrote: >> >>> I now have the following question for people who argue that "if x" >>> is more polymorphic. I could subclass list, so that instances >>> of this new sequence would always behave as true, even if they are >>> empty. I could then rewrite my loop as follows: >>> >>> while 1: >>> extra = produce() >>> if not extra: >>> break >>> for el in extra: >>> adjust_with(el) >>> calculate() >>> >>> Is this second loop now more polymorphic as the first? >> It's more confusing since you've changed the standard behavior of a >> standard type, which doesn't really have anything to do with >> polymorphism. It's more confusing, if that's a benefit. > > So you accept my point that "if x" can be less polymorphic > and in fact can be more confusing than a more specific test. > I think your example is more related to a trap with polymorphism in general rather than an argument against 'is x' specifically. Any time you override a method, you have an opportunity to change the behavior in unexpected ways. Especially in languages like Python that don't do type checking. For example, you write a __cmp__ method like this: class ReallyBadPractice(object): def __cmp__(self, other): return -cmp(self, other) Of course any code that does comparisons on this class is going to behave unexpectedly! -Matt From invalid at invalid.invalid Sun Aug 10 09:52:37 2008 From: invalid at invalid.invalid (WP) Date: Sun, 10 Aug 2008 15:52:37 +0200 Subject: My very first python program, need help Message-ID: <6g8a56FenevdU1@mid.individual.net> Hello, below is my very first python program. I have some questions regarding it and would like comments in general. I won't be able to get my hands on a good python book until tomorrow at the earliest. The program takes a string and sums all numbers inside it. I'm testing with the following string: "123xx,22! p1" which should yield a sum of 123 + 22 + 1 = 146. My solution to this exercise was to write a function that takes a string and splits it into a list of numbers and then I will sum up the numbers in the list. In fact, I wrote two versions of this function: One uses a for loop to replace all characters that is not a digit and not a space with a space. That should leave me with the numbers intact and with only spaces separating these numbers. Then I call split to get a list of numbers (here I discovered I must not use a sep equal to ' ' or the returned list would contain empty strings as well). This is calculate_sum_1() and look at the comment in the code to see what worries me there. The second one uses regular expressions and the problem I have with that is that I get a list of containing not just the numbers but empty strings as well. I'm working around that in my loop that sums the numbers but it would be better to not have these empty string in the list in the first place. Here's the code: import re def calculate_sum_1(str): for c in str: if c.isdigit() == False and c != ' ': # That we assign to the variable we're looping over worries me... str = str.replace(c, ' ') mylist = str.split() print "(for loop version) mylist after replace() and split() = ", mylist sum = 0 for item in mylist: sum += long(item) return sum def calculate_sum_2(str): #print "In replace_nondigits_2(), str = ", str p = re.compile('[^0-9]') mylist = p.split(str) print "(regex version) mylist after calling split(): ", mylist sum = 0 for item in mylist: if item.isdigit(): sum += long(item) return sum str = "123xx,22! p1" # Sum = 123 + 22 + 1 = 146 print "str = ", str print "calculate_sum_1(str): %d" % calculate_sum_1(str) print "calculate_sum_2(str): %d" % calculate_sum_2(str) The output when run is: str = 123xx,22! p1 (for loop version) mylist after replace() and split() = ['123', '22', '1'] calculate_sum_1(str): 146 (regex version) mylist after calling split(): ['123', '', '', '22', '', '', '1'] calculate_sum_2(str): 146 Hope I made some sense and thanks for reading! - Eric (WP) From tino at wildenhain.de Sun Aug 31 09:23:36 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sun, 31 Aug 2008 15:23:36 +0200 Subject: Writing to ms excel In-Reply-To: References: <09tjb4p32lfbk4nji4sqjg5mk0e99gub2v@4ax.com> <00c9fe68$0$20302$c3e8da3@news.astraweb.com> Message-ID: <48BA9B58.5030006@wildenhain.de> Marin Brkic wrote: >... > I remember an older coleague who said; "open, free and whatever > licence type ... software is free, only up to some amount of $$/per > hour". After that you just want things to work, and if they don't > work, there are people who are paid $/per hour to make it work. Well I hear that too but its obviously the biggest lie in IT. You can't make MS Office to work. There is no way to do so. Even asking MS the question why something does not work costs a lot of money and you don't get a solution. Example: try to put group templates on a WEBDAV "share". So in the OS world you can actually spend that money on someone indeed giving you a solution. Btw, SUN has a plugin for MS office to read/write odf. (Which works instead of the solution from MS itself). Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From tslocum at gmail.com Mon Aug 4 01:14:27 2008 From: tslocum at gmail.com (Trevor Slocum) Date: Sun, 3 Aug 2008 22:14:27 -0700 Subject: Peer-to-Peer Chat Program Message-ID: <98ad656a0808032214w23b51020j29d97fac1249d14a@mail.gmail.com> Python seemed like the right choice for writing a peer-to-peer application, as the support for sockets is adequate and the cross-platform ability is nominal. That's why I searched around for P2P frameworks in Python, and didn't have much luck. The framework that I did find was designed specifically for file transfers, rather than simple message carriers, and implemented a complex multicast system. So, with Python in one hand and Google in the other, I set out to write my own P2P app in Python, with zero previous P2P experience. I had to start off by looking up how P2P works, then figure out how to get messages across the network, and then how to bootstrap each node, without centralizing the network. I decided to make it connectionless because they were simple messages. The current implementation is that a peer creates a message and forwards it to all of its known peers, and then the other peers do the same. This is for simplicity, as it causes quite a bit of needless rebound from each of the other peers sending a message which has already been received. In order to reduce this, each message is tagged with a unique ID which is verified against upon each arrival. Once that worked well, I needed to get peers to know each other. My current solution is a provider script running on a single server which is auto-pinged every minute by each peer, and any new peers receive a list of known peers from it. This can easily be expanded to many more servers in case any go offline. Even if zero providers are online, users can manually add nodes from the console and the framework will automatically build a known peer list from them. Like I said, I didn't know anything about P2P before this, and I'm sure much of what I've done so far can be improved upon. That's why I'm posting here. I'd like to make an open request to anyone who would like to assist me in the application development to reduce the resource usage and improve the overall network efficiency. Even simple "Ah, I saw you were doing this in your code, I recommend you do this..." would be of great help. If you are interested, you may view the Google Code page at http://code.google.com/p/kaishi/ or checkout the SVN repository directly using http://kaishi.googlecode.com/svn/trunk/ I have proper hosting and can set up a specific website for collaboration on project ideas and such if support is carried after this message. I thank anyone who has taken their time to read this. -- Trevor "tj9991" Slocum -------------- next part -------------- An HTML attachment was scrubbed... URL: From eliben at gmail.com Fri Aug 15 10:45:00 2008 From: eliben at gmail.com (eliben) Date: Fri, 15 Aug 2008 07:45:00 -0700 (PDT) Subject: Parsing and Editing Source References: Message-ID: <1f8af357-67ee-462a-9211-c6ac4933e302@d1g2000hsg.googlegroups.com> On Aug 15, 4:21?pm, "Paul Wilson" wrote: > Hi all, > > I'd like to be able to do the following to a python source file > programmatically: > ?* Read in a source file > ?* Add/Remove/Edit Classes, methods, functions > ?* Add/Remove/Edit Decorators > ?* List the Classes > ?* List the imported modules > ?* List the functions > ?* List methods of classes > > And then save out the result back to the original file (or elsewhere). > > I've begun by using the tokenize module to generate a token-tuple list > and am building datastructures around it that enable the above > methods. I'm find that I'm getting a little caught up in the details > and thought I'd step back and ask if there's a more elegant way to > approach this, or if anyone knows a library that could assist. > > So far, I've got code that generates a line number to token-tuple list > dictionary, and am working on a datastructure describing where the > classes begin and end, indexed by their name, such that they can be > later modified. > > Any thoughts? > Thanks, > Paul Consider using the 'compiler' module which will lend you more help than 'tokenize'. For example, the following demo lists all the method names in a file: import compiler class MethodFinder: """ Print the names of all the methods Each visit method takes two arguments, the node and its current scope. The scope is the name of the current class or None. """ def visitClass(self, node, scope=None): self.visit(node.code, node.name) def visitFunction(self, node, scope=None): if scope is not None: print "%s.%s" % (scope, node.name) self.visit(node.code, None) def main(files): mf = MethodFinder() for file in files: f = open(file) buf = f.read() f.close() ast = compiler.parse(buf) compiler.walk(ast, mf) if __name__ == "__main__": import pprint import sys main(sys.argv) From tjreedy at udel.edu Fri Aug 15 18:59:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 15 Aug 2008 18:59:43 -0400 Subject: Missing exceptions in PEP 3107 In-Reply-To: References: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> <8800beb6-c07b-44af-b9ac-fcb00f35dc3a@f36g2000hsa.googlegroups.com> Message-ID: Christoph Zwerschke wrote: > That's not quite true: PEP 3017 describes a mechanism for annotating > function parameters *and return values*, and my point was why it does > not provide a mechanism for annotating thrown exceptions, since I see > info on thrown exceptions in the same category as info on return values. I would agree... but... The problem is that code that uses a function hardly cares whether an exception that replaces the normal return is raised explicitly, by a syntax operation (and these are not yet completely documented, though perhaps they should be), or by a function called within the function. tjr From matthias.blaesing at rwth-aachen.de Fri Aug 29 06:46:05 2008 From: matthias.blaesing at rwth-aachen.de (Matthias =?iso-8859-1?q?Bl=E4sing?=) Date: 29 Aug 2008 10:46:05 GMT Subject: Iterating two arrays at once References: Message-ID: Am Fri, 29 Aug 2008 03:35:51 -0700 schrieb mathieu:> > A = [1,2,3] > B = [4,5,6] > for a,b in A,B: # does not work ! > print a,b > > It should print: > > 1,4 > 2,5 > 3,6 Hey, zip is your friend: for a,b in zip(A,B): print a,b does what you want. If you deal with big lists, you can use izip from itertools, which returns a generator. from itertools import izip for a,b in izip(A,B): print a,b HTH Matthias From Michael.Coll-Barth at VerizonWireless.com Wed Aug 13 11:51:09 2008 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Wed, 13 Aug 2008 11:51:09 -0400 Subject: You advice please In-Reply-To: References: <20080813110444.7b48ddbc.darcy@druid.net><76fd5acf0808130811y7d7d6584m721096295a72af98@mail.gmail.com><48A2FBAC.3000103@wiggly.org> Message-ID: <20080813155223.66AF21E4008@bag.python.org> > -----Original Message----- > From: Calvin Spealman > > God forbid I try to make a joke. No kidding! As a lurker newbie, I don't mind one bit. Actually, I have yet to meet a person that codes in Ruby that doesn't also do Python. I have met many Python coders that have never even looked at Ruby. Your joke may have more truth in it than you realized. And upper management reads the *V*logs and believe the hype. We should be prepared to counter the argument. The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From PaulAlexWilson at gmail.com Fri Aug 8 10:19:26 2008 From: PaulAlexWilson at gmail.com (Wilson) Date: Fri, 8 Aug 2008 07:19:26 -0700 (PDT) Subject: Limits of Metaprogramming References: <0c56829a-7ad2-4ff2-b225-7981538e7c7a@j22g2000hsf.googlegroups.com> <64c69a68-aa00-4f59-a84e-52f5cfa14913@z66g2000hsc.googlegroups.com> <04bd26b2-20b4-45fc-b080-a470c1511cb0@34g2000hsh.googlegroups.com> Message-ID: <70426441-ee9f-46f5-8525-57a5d1452039@e39g2000hsf.googlegroups.com> On 8 Aug, 13:30, Iain King wrote: > On Aug 4, 5:13 pm, Tomasz Rola wrote: > > > On Mon, 4 Aug 2008, Wilson wrote: > > > " Every sufficiently large application has a poor/incomplete > > > implementation ofLISPembedded within it ". > > > Yep, this is either exact or very close copy of what I have read. > > It's Greenspun's Tenth Rule of Programming: > > "Any sufficiently complicated C or Fortran program contains an ad-hoc, > informally-specified bug-ridden slow implementation of half of Common > Lisp." > > Iain Thanks for that. Makes my attempt look pathetic! :) From rocksportrocker at googlemail.com Tue Aug 5 07:06:56 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Tue, 5 Aug 2008 04:06:56 -0700 (PDT) Subject: Wrapping C with Python References: Message-ID: <2e7cd08c-d28f-4fca-a480-37b639260ed2@l64g2000hse.googlegroups.com> On 4 Aug., 15:14, brad wrote: > RPM1 wrote: > > ... > > > Basically you just compile your C code as a regular C code dll. ?ctypes > > then allows you to access the functions in the dll very easily. > > Does that work with C++ code too or just C? It works if the interface of the DLL is C-style, that is you declare your functions with 'extern "C" { .... }' around them. Inside your modules implementation you can use C++ without any problems. What works fine too, is f2py from numpy. It targets at wrapping Fortran code, but is able to wrap C code too, see http://www.scipy.org/Cookbook/f2py_and_NumPy?action=show Greetings, Uwe Greetings, Uwe From castironpi at gmail.com Sun Aug 24 00:23:19 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 23 Aug 2008 21:23:19 -0700 (PDT) Subject: two's complement bytes References: <9a2a633c-b1ad-47a8-ae49-168b9fa62f90@x16g2000prn.googlegroups.com> Message-ID: <9786092a-a378-40ed-b930-268eb6c4d1a3@26g2000hsk.googlegroups.com> On Aug 23, 10:51?pm, "Adam W." wrote: > I'm dabbling with AVR's for a project I have and that means I have to > use C (ageist my will). ?Because my AVR will be tethered to my laptop, > I am writing most of my logic in python, in the hopes of using at > little C as possible. > > In my quest I came across a need to pass a pair of sign extended two's > complement bytes. ?After painfully reading the wikipedia article on > what two's complement was, I then thought of how I would handle this > in python. ?I don't really recall ever having to work in binary with > python, so I really am clueless on what to do. > > I can feed python either two hex bytes or binary, but how do I convert > it into an int, and more importantly how do I make sure it handles the > sign properly? Try this out. Does it come close to what you want? import struct struct.pack( 'i', ~10 ) ~struct.unpack( 'i', _ )[ 0 ] >>> import struct >>> struct.pack( 'i', ~10 ) '\xf5\xff\xff\xff' >>> ~struct.unpack( 'i', _ )[ 0 ] 10 >>> From rajat.dudeja at aeroflex.com Wed Aug 13 10:58:39 2008 From: rajat.dudeja at aeroflex.com (Dudeja, Rajat) Date: Wed, 13 Aug 2008 10:58:39 -0400 Subject: Looking out a module for Subversion In-Reply-To: References: <48A14FB6.4020009@sellerengine.com> <27cbc0fa0808120250t5d41af68u1d72b66f46ad0995@mail.gmail.com> Message-ID: Hi Fabio > Download eclipse 3.3 from http://download.eclipse.org/eclipse/downloads/drops/R-3.3.2-200802211800 /index.php (you can download only the > "Platform Runtime Binary" in that link) and then follow the instructions to install Pydev at http://fabioz.com/pydev/manual_101_install.html I see that this link for Pydev provides a commercial version of pydev (so this points the evaluation version of it) . Is there any open source version of it? cheers, Rajat Notice: This e-mail is intended solely for use of the individual or entity to which it is addressed and may contain information that is proprietary, privileged, company confidential and/or exempt from disclosure under applicable law. If the reader is not the intended recipient or agent responsible for delivering the message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If this communication has been transmitted from a U.S. location it may also contain data subject to the International Traffic in Arms Regulations or U.S. Export Administration Regulations and cannot be disseminated, distributed or copied to foreign nationals, residing in the U.S. or abroad, without the prior approval of the U.S. Department of State or appropriate export licensing authority. If you have received this communication in error, please notify the sender by reply e-mail or collect telephone call and delete or destroy all copies of this e-mail message, any physical copies made of this e-mail message and/or any file attachment(s). -------------- next part -------------- An HTML attachment was scrubbed... URL: From ireborin at gmail.com Fri Aug 15 12:31:16 2008 From: ireborin at gmail.com (Ivan Reborin) Date: Fri, 15 Aug 2008 18:31:16 +0200 Subject: wxPython beginners problem Message-ID: Hello all, I'm new to python, new as newbies get, so please, don't take wrongly if this seems like a stupid or overly simple question. I'm going through examples in a book I have ("Beginning python", by Hetland Marcus) and I just started doing wxPython examples. But every sample I try, for example: import wx app = wx.App() win = wx.Frame(None, title="Simple editor") loadButton = wx.Button(win, label='Open') saveButton = wx.Button(win, label='Save') win.Show app.MainLoop() closes too fast. After running in python IDLE just the line === restart === shows up. How can I keep the window to "stay alive" so I see what I get ? I'm on a winxp platform using python 2.5.2. if that matters. Please, any help, constructive advice and ideas are very much appreciated. Best regards Ivan Reborin From jasper at peak.org Mon Aug 18 04:32:12 2008 From: jasper at peak.org (Jasper) Date: Mon, 18 Aug 2008 01:32:12 -0700 (PDT) Subject: Bizarre method keyword-arg bug. Message-ID: I'm stumped. I'm calling a method that has keyword args, but not setting them, and yet one of them starts off with data?! The class definition begins like so: class BattleIntentionAction( BattleAction ): def __init__( self, factionName, location, tactic='hold', targetFacName='', terrainArgs=[], garrisonIds=[] ): self.terrainArgs = terrainArgs print terrainArgs The constructor is called somewhere else, like so: act = BattleIntentionAction( facName, self.location ) During this object's construction, terrainArgs is set to a list with values corresponding to a previously created BattleIntentionAction! Even more bizarre, the terrainArgs param is a testing formality, and doesn't actually get used anywhere in my code -- the corresponding attribute is always modified after object creation. Furthermore, this doesn't happen with the other keyword args... Obviously, I'm glossing over a ton of code here, but I'm having a tough time isolating this problem, as it seems to be very dependent on events leading up to it. It feels like the sort of memory stomping bug I remember seeing from days of yore when I hacked C++. :-( I frankly don't understand how "terrainArgs" can have a value if nothing is passed for it on the calling invocation, short of some obscure compiler bug (this is Python 2.4.3). Am I being naive? Is there some way I could be bringing this about myself? I can easily work around this weirdness by having the caller set terrainArgs explicitly, but I can't shake the sensation that this "fix" just masks some deeper flaw in my code. Arg! -Jasper From mail at timgolden.me.uk Thu Aug 28 03:53:52 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 28 Aug 2008 08:53:52 +0100 Subject: calling NetShareEnum win32api with ctypes In-Reply-To: <4f48843b-545b-4c29-91b1-f10de7a563e4@c65g2000hsa.googlegroups.com> References: <4f48843b-545b-4c29-91b1-f10de7a563e4@c65g2000hsa.googlegroups.com> Message-ID: <48B65990.8060809@timgolden.me.uk> taghi wrote: > I want to call NetShareEnum, a function from netapi32.dll Not a straightforward answer but... are you aware that this particular call is already wrapped by the pywin32 packages: https://sourceforge.net/projects/pywin32/ http://timgolden.me.uk/pywin32-docs/win32net__NetShareEnum_meth.html TJG PS Is it me or is SourceForge's latest redesign actually less useful than its last one? From ironfroggy at gmail.com Tue Aug 12 13:33:19 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Tue, 12 Aug 2008 13:33:19 -0400 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: <74583B8642AB8841B30447520659FCA92CBAF3B3@dnce01.ent.ti.com> References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> <200808121311.06892.maric@aristote.info> <74583B8642AB8841B30447520659FCA92CBAF3B3@dnce01.ent.ti.com> Message-ID: <76fd5acf0808121033q42aafd3dned27ab58f1618343@mail.gmail.com> Please re-evaluate your "need" for nesting classes in the first place. On Tue, Aug 12, 2008 at 1:06 PM, Cousson, Benoit wrote: >> This is a language limitation. >> This is because nested scope is implemented for python function only since >> 2.3 >> allow late binding of free variables. the scope in class statment is not a >> closure, so there is only two possible scope in it : local and global. > > That was my understanding as well, but I think it is a pity to have that limitation. Don't you think that the same improvement that was done for method nested scope could be done as well for nested class? > > I can easily fix my current issue by doing the binding after the class declaration. > My concern is more about the lack of symmetry of that approach; meaning that if both classes are in the global scope, one can access the others, whereas if they are in the body of another class they cannot. > > This is OK: > > class A(object): > pass > > class B(object): > foo=A > > > I have to add the binding after the declaration in the case of nested: > > class C(object): > class A(object): > pass > > class B(object): > foo=None > B.foo = A > > That extra step is a little bit painful and should not be necessary for my point of view. > > >> > I'm wondering as well if the new nonlocal statement will fix that in >> py3k? >> > >> >> nonlocal doesn't adress this issue an I doubt python 3.0 fix it at all. >> >> You have the same problem with generator expressions, which bind lately >> outer >> loop variables : > > Good to know, I was not aware of that. > > Thanks, > Benoit > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy From weiguo6 at gmail.com Thu Aug 7 03:19:37 2008 From: weiguo6 at gmail.com (weiguo6 at gmail.com) Date: 7 Aug 2008 08:19:37 +0100 Subject: Horses Message-ID: <200808070720.CTU36540@manxnetsf02.manx.net> Where have all the horses gone? From Nikolaus at rath.org Fri Aug 1 02:04:13 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Fri, 01 Aug 2008 08:04:13 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> <87r69a85ek.fsf@nokile.rath.org> <87fxpq7x41.fsf@nokile.rath.org> Message-ID: <874p658e5e.fsf@nokile.rath.org> Miles writes: > On Thu, Jul 31, 2008 at 1:59 PM, Nikolaus Rath wrote: >> If it is just a matter of different rendering, what's the reason for >> doing it like that? Wouldn't it be more consistent and straightforward >> to denote builtin types as classes as well? > > Yes, and in Python 3, it will be so: > [..] > http://svn.python.org/view?rev=23331&view=rev That makes matters absolutely clear. Thanks a lot. No more questions from my side ;-). Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From sthembilengidi at gmail.com Mon Aug 18 06:16:11 2008 From: sthembilengidi at gmail.com (Amie) Date: Mon, 18 Aug 2008 03:16:11 -0700 (PDT) Subject: HTML Tables Message-ID: <6d0d25a5-4866-44e9-adb7-8772119d1b92@e39g2000hsf.googlegroups.com> Afternoon all. Just want to know how to create html tables using a for loop. I need to display 34 html tables, so I figured a for loop will do. Please show me an example of how to do that. Also how do I display the results of an sql query onto the html tables? Thanks in advance From williambattersea at gmail.com Wed Aug 13 23:16:12 2008 From: williambattersea at gmail.com (Prof. William Battersea) Date: Wed, 13 Aug 2008 23:16:12 -0400 Subject: Using Timer or Scheduler in a Class Message-ID: <97d780f10808132016s3b453765m82bf1784b1f2afb2@mail.gmail.com> I'd like a class method to fire every n seconds. I tried this: class Timed: def.__init__(self): self.t = Timer(3, self.dothing) def.start(self): self.t.start() def.dothing(self): print "Doing Thing" s = new Timed() s.start() And: class Scheduled: def.__init__(self): self.s = sched.scheduler(time.time, time.sleep) self.s.enter(3, 1, self.sync, ()) def.start(self): self.t.start() def.dothing(self): print "Syncing" s = new Scheduled() s.start() Both run once and end. I'm obviously missing something here. Thanks, Justin From pavlovevidence at gmail.com Sat Aug 30 00:24:28 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 29 Aug 2008 21:24:28 -0700 (PDT) Subject: When to use try and except? References: <8a2dd955-6641-493d-b7eb-3e29c14686a5@26g2000hsk.googlegroups.com> <914fde08-5084-455f-ac68-bef7e06cc3dc@i76g2000hsf.googlegroups.com> Message-ID: <00c7058c-2b26-42bf-8f5b-2bebe31b2130@k7g2000hsd.googlegroups.com> On Aug 29, 2:33?pm, "Chris Rebert" wrote: > On Fri, Aug 29, 2008 at 10:56 AM, cnb wrote: > > On Aug 29, 7:40 pm, Daniel wrote: > >> On Aug 29, 11:23 am, cnb wrote: > > >> > If I get zero division error it is obv a poor solution to do try and > >> > except since it can be solved with an if-clause. > > >> > However if a program runs out of memory I should just let it crash > >> > right? Because if not then I'd have to write exceptions everywhere to > >> > prevent that right? > > >> > So when would I actually use try-except? > > >> > If there can be several exceptions and I just want to catch 1 or 2? > >> > Like > >> > try: > >> > ? ? blahaba > >> > except SomeError: > >> > ? ? do something > > >> I'm not sure whay you're trying to do, but I think catching a > >> ZeroDivisionError exception is a good use of try-except. > > >> I'm also not sure that I would say you just let a program crash if it > >> runs out of memory. ?I would think that from the user perspective, you > >> would want to check memory conditions and come up with an exception > >> indicating that some memory threshold has been reached. ?When that > >> exception is raised you should indicate that to the user and exit > >> gracefully. > > > A ZeroDivisionError is better avoided wth an if-clause, don't you > > think? It is a predictable exception... > > Basically, there's a general principle (EAFP: Easier to ask > forgiveness than permission) in Python to just "try" something and > then catch the exception if something goes wrong. This is in contrast > to e.g. C where you're supposed to "Look before you leap" (LBYL) and > check for possible error conditions before performing the operation. I wouldn't say that the possibility of EAFP in Python makes it obsolute to use LBYL. (Error checking seems to be too broad a subject to apply the One Obvious Way maxim to.) C isn't always LBYL anyway; sometimes it's DFTCFE "Don't forget to check for errors". I tend to use EAFP to check if something "wrong" happened (a missing file, invalid input, etc.), and LBYL for expected conditions that can occur with valid input, even when that condition could be tested with a try...except. For instance, I'd write something like this: if x is not None: y = x.calculate_value() else: y = default_value Main reason I do this is to document that None is an expected and valid value for x, and not incidative of a problem. But it's purely a matter of style and neither way is wrong. Carl Banks From brian.lee.hawthorne at gmail.com Tue Aug 12 23:19:10 2008 From: brian.lee.hawthorne at gmail.com (Brian Hawthorne) Date: Tue, 12 Aug 2008 20:19:10 -0700 Subject: Wackness Message-ID: <796269930808122019q697a3657h59b4e95510a9823f@mail.gmail.com> p1 = property(lambda self: self.__x) class Foo (object): p1 = p1 p2 = property(lambda self: self.__x) def __init__(self): self.__x = 10 f = Foo() print f.p2 print f.p1 #------------------------------------------------------- Expecting to see: 10 10 ? Think again! Ouch, just got bit. But I guess the name mangling has to occur at compile (to bytecode) time? Cheers, Brian Hawthorne From martin at v.loewis.de Sun Aug 10 10:05:55 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 10 Aug 2008 16:05:55 +0200 Subject: download limit In-Reply-To: References: Message-ID: <489EF5C3.4040101@v.loewis.de> > I have a multithreaded script that mainly creates several wget > processes to download files. I would like to check/see and eventually > limit the bandwidth of the pool of processes. One way to do this is to > change the number of wget instances, but it's a workaround. > > What do you recommend to do the following in python: > 1) know the bitrate at the script scale > 2) control, and limit or not this bitrate I recommend to not use wget, but implement the network access directly in Python. Then you can easily measure that bitrate, and also limit it. (by having some threads sleep). Once you fork out new processes, you lose, unless there is an operating system bandwidth limitation framework available which works on groups of processes. Solaris project objects may provide such a thing, but apart from that, I don't think it's available in any operating system that you might be using. Regards, Martin From notvalid2 at sbcglobal.net Sat Aug 23 19:11:37 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Sat, 23 Aug 2008 16:11:37 -0700 Subject: Filling in Degrees in a Circle (Astronomy) In-Reply-To: References: Message-ID: tom wrote: > W. eWatson wrote: >> The other night I surveyed a site for astronomical use by measuring >> the altitude (0-90 degrees above the horizon) and az (azimuth, 0 >> degrees north clockwise around the site to 360 degrees, almost north >> again) of obstacles, trees. My purpose was to feed this profile of >> obstacles (trees) to an astronomy program that would then account for >> not sighting objects below the trees. >> >> When I got around to entering them into the program by a file, I found >> it required the alt at 360 azimuth points in order from 0 to 360 (same >> as 0). Instead I have about 25 points, and expected the program to be >> able to do simple linear interpolation between those. >> >> Is there some simple operational device in Python that would allow me >> to create an array (vector) of 360 points from my data by >> interpolating between azimuth points when necessary? All my data I >> rounded to the nearest integer. Maybe there's an interpolation operator? >> >> As an example, supposed I had made 3 observations: (0,0) (180,45) and >> (360,0). I would want some thing like (note the slope of the line from >> 0 to 179 is 45/180 or 0.25): >> alt: 0, 0.25, 0.50, 0.75, ... 44.75, 45.0 >> az : 0, 1, 2, 3, 180 >> >> Of course, I don't need the az. >> > > > If I understand you right, I think using interpolation as provided by > scipy would do what you need. > > Here's an example: > > from scipy.interpolate.interpolate import interp1d > > angles = [0, 22, 47.5, 180, 247.01, 360] > altitudes = [18, 18, 26, 3, 5, 18] > > desired_angles = range(0, 361) > > skyline = interp1d(angles, altitudes, kind="linear") > vals = skyline(desired_angles) > > # that is, vals will be the interpolated altitudes at each of the > # desired angles. > > if 1: # plot this out with matplotlib > import pylab as mx > mx.figure() > mx.plot(angles, altitudes, 'x') > mx.plot(desired_angles, vals) > mx.show() I decided this morning and roll up my sleeves and write the program. I plan to take a deeper plunge in the next month than my so far erratic look over the last 18 or more months It's working. The above looks like it's on the right track. Is scipy some collection of astro programs? mx is a graphics character plot? I just hauled it into IDLE and tried executing it. from scipy.interpolate.interpolate import interp1d ImportError: No module named scipy.interpolate.interpolate Apparently, something is missing. I posted a recent msg a bit higher that will probably go unnoticed, so I'll repeat most of it. How do I get my py code into some executable form so that Win users who don't have python can execute it? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From harrrrpo at gmail.com Sun Aug 24 07:43:57 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Sun, 24 Aug 2008 14:43:57 +0300 Subject: Imports awareness in Imported modules problem In-Reply-To: <702255f9-4bcd-471d-ad06-487cbb62f258@b38g2000prf.googlegroups.com> References: <538050a90808231529s61855330r1ec68048847ef241@mail.gmail.com> <702255f9-4bcd-471d-ad06-487cbb62f258@b38g2000prf.googlegroups.com> Message-ID: <538050a90808240443m71756241pa5e390385f19cb52@mail.gmail.com> On Sun, Aug 24, 2008 at 2:27 PM, alex23 wrote: > On Aug 24, 8:34 pm, "Mohamed Yousef" wrote: >> and sys ,string.. etc add them all twice or four / n times ? >> remove one and then forget to remove one of them in a file and start >> debugging ... this really doesn't look to be a good practice > > No, having each module contain all of the necessary imports for itself > -is- good practice. > > While it might seem more convenient to define all of your imports in > one place, what you're really doing is injecting -all- references to - > all- imported items into -every- module. Having a global soup of > imported items like such is much, much harder to control for > unexpected name conflicts. > > Ideally, you want each module's namespace to -only- contain references > to the external entities it's actually using. This not only makes each > module self-contained and more open to independent re-use, it makes > them -incredibly- easier to debug. > > Please don't confuse temporary convenience with good practice. mm , this seems to be logically or another good behind logic . as PHP already uses that convention -from which i thought python also does - but what about module-wide variables what is the approach to them , will i have to store them in a memory table (SQL) , or keep passing them between objects - which i really hate - From bedouglas at earthlink.net Fri Aug 29 11:17:32 2008 From: bedouglas at earthlink.net (bruce) Date: Fri, 29 Aug 2008 08:17:32 -0700 Subject: python/mechanize - redirect/refresh question Message-ID: <0a6301c909ea$5d862740$0301a8c0@tmesa.com> Hi. I'm using mechanize to parse a page/site that uses the meta http-equiv tag in order to perform a refresh/redirect of the page. I've tried a number of settings, and read different posts on various threads, but seem to be missing something. the test.html page is the page that the url returns, however, i was expecting the test.py app to go ahead and perform the redirect/refresh automatically. does the page (test.html) need to be completely valid html? Any thoughts on what's screwed up here?? thanks ---------------------------------------------------- test.py -------- import re import libxml2dom import urllib import urllib2 import sys, string from mechanize import Browser import mechanize #import tidy import os.path import cookielib from libxml2dom import Node from libxml2dom import NodeList import subprocess import time ######################## # # Parse pricegrabber.com ######################## cj = "p" COOKIEFILE = 'cookies.lwp' #cookielib = 1 urlopen = urllib2.urlopen #cj = urllib2.cookielib.LWPCookieJar() cj = cookielib.LWPCookieJar() Request = urllib2.Request br = Browser() br2 = Browser() if cj != None: print "sss" #install the CookieJar for the default CookieProcessor if os.path.isfile(COOKIEFILE): cj.load(COOKIEFILE) print "foo\n" if cookielib: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) print "foo2\n" user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values1 = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } url="http://schedule.psu.edu/" #======================================= if __name__ == "__main__": # main app txdata = None #---------------------------- ##br.set_cookiejar(cj) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.set_handle_refresh(True) br.addheaders = [('User-Agent', 'Firefox')] #url=str(url)+str("act_main_search.cfm")+"?" #url=url+"Semester=FALL%202008%20%20%20&" #url=url+"CrseLoc=OZ%3A%3AAbington%20Campus&" #url=url+"CECrseLoc=AllOZ%3A%3AAbington%20Campus&" #url=url+"CourseAbbrev=ACCTG&CourseNum=&CrseAlpha=&Search=View+schedule" #url="http://schedule.psu.edu/act_main_search.cfm?Semester=FALL%202008%20%20 %20%20&CrseLoc=OZ%3A%3AAbington%20Campus&CECrseLoc=AllOZ%3A%3AAbington%20Cam pus&CourseAbbrev=ACCTG&CourseNum=&CrseAlpha=" url="http://schedule.psu.edu/act_main_search.cfm?Semester=FALL%202008%20%20% 20%20&CrseLoc=OZ%3A%3AAbington%20Campus&CECrseLoc=AllOZ%3A%3AAbington%20Camp us&CourseAbbrev=ACCTG&CourseNum=&CrseAlpha=&CFID=543143&CFTOKEN=71842529" print "url =",url br.open(url) #cj.save(COOKIEFILE) # resave cookies res = br.response() # this is a copy of response s = res.read() print "slen=",len(s) print s ========================================= test.html Tech Type --------------------------------------------------------- sys.exit() From dudeja.rajat at gmail.com Tue Aug 19 06:11:56 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 19 Aug 2008 11:11:56 +0100 Subject: WindowsXP / CTypes Module - unable to access function in a dll In-Reply-To: References: Message-ID: On Tue, Aug 19, 2008 at 11:04 AM, wrote: > Hi, > > I'm using the CTYPES module of python to load a dll. My dll contains a > Get_Version function as: > long __stdcall af1xEvdoRDll_GetVersion(long version[4]); > > This function accepts a long array of 4 elements. > > Following is the python code I've written: > > from ctypes import * > abc = windll.af1xEvdoRDll > GetVersion = abc.af1xEvdoRDll_GetVersion > print GetVersion > versionArr = c_long * 4 #array of 4 longs > version = versionArr(0, 0, 0, 0) # initializing all elements to 0 > GetVersion(version) #calling dll function > print version > > I'm getting the following output: > <_FuncPtr object at 0x00A1EB70> > <__main__.c_long_Array_4 object at 0x00A86300> > > But I'm not getting the desired output which I expect as : 2.1.5.0 > > > Please suggest what am I missig? > Sorry, the problem is resolved. The code in fact is correct and I got the right answers. It is just that I was not priting results in a right manner. I added : print i in version : print i this solved my problem. Cheers. From cwitts at gmail.com Mon Aug 11 09:17:49 2008 From: cwitts at gmail.com (Chris) Date: Mon, 11 Aug 2008 06:17:49 -0700 (PDT) Subject: if len(str(a)) == len(str(r)) and isMult(a, r): faster if isMult is slow? References: Message-ID: <2c2f6222-9326-44fe-a66b-b78e4b1c5ee6@x41g2000hsb.googlegroups.com> On Aug 11, 3:03?pm, maestro wrote: > If isMult is slow then: > > if len(str(a)) == len(str(r)) and isMult(a, r): > ? ? ? ? ? ? ? ? trues.append((a, r)) > > will be much faster than: > > if isMult(a, r) and len(str(a)) == len(str(r)): > ? ? ? ? ? ? ? ? trues.append((a, r)) > > right? seems obvious ?but there is no magic going on that wouldn't > make this true right? Once a failed condition is met the rest are skipped for evaluation. Whether or not that saves you any reasonable amount of time would be up to the various tests being used with your conditions. If your function isMult is just doing the same work as "if not a % r" then that would be faster than casting your integers/floats to a string and testing their length imo. You could always go through the trouble of profiling your code with separate if statements to see how much time is spent on each, also note your mean failure rate for each conditional test and then decide for yourself which to place first. Hope that helps, Chris From steve at REMOVE-THIS-cybersource.com.au Wed Aug 20 09:24:59 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2008 13:24:59 GMT Subject: exception handling in complex Python programs References: Message-ID: <00bc1604$0$20315$c3e8da3@news.astraweb.com> On Tue, 19 Aug 2008 22:24:45 -0700, eliben wrote: > """ between file() > and open() in Python 2 and 3, a NameError is thrown with open() in > Python 3 and an IOError is thrown in the other three cases against keyboard>. > """ I'm curious about the claim that open() will raise NameError in Python3. I find it hard to credit that claim, but if it is correct, what's the justification for that? > This is *exactly* my concern with Python exceptions. You just never know > what can be thrown at you. It's true that documentation of exceptions is relatively weak in Python. And some functions can raise a bewildering array of exceptions. See for example this thread where somebody notes that urllib2.urlopen() can raise any of six different exceptions: http://mail.python.org/pipermail/baypiggies/2008-April/003187.html And I've had it raise socket.error, which makes seven. And the documentation only mentions one of those exceptions. However, as Gregory Smith describes, some of those seven exceptions are subclasses of others, so it is possible to reduce it down to three cases -- and arguably one of those cases (ValueError) is a bug that needs fixing, not an exception that needs catching. That's probably as bad as it gets in Python, at least for the standard library. Most functions don't raise arbitrary exceptions for sensible data, and if you pass non-sensible data then you should treat the exception as a bug in your code and fix it. -- Steven From toby at tobiah.org Wed Aug 6 12:20:35 2008 From: toby at tobiah.org (Tobiah) Date: Wed, 06 Aug 2008 09:20:35 -0700 Subject: regex question References: <6fqqovFcq6bmU1@mid.uni-berlin.de> Message-ID: On Tue, 05 Aug 2008 15:55:46 +0100, Fred Mangusta wrote: > Chris wrote: > >> Doesn't work for his use case as he wants to keep periods marking the >> end of a sentence. Doesn't it? The period has to be surrounded by digits in the example solution, so wouldn't periods followed by a space (end of sentence) always make it through? ** Posted from http://www.teranews.com ** From theller at python.net Fri Aug 29 17:49:44 2008 From: theller at python.net (Thomas Heller) Date: Fri, 29 Aug 2008 23:49:44 +0200 Subject: ctypes version mismatch In-Reply-To: References: Message-ID: <6hr97oFnqkdgU1@mid.individual.net> Paul McNett schrieb: > Anyone have anything to suggest on this error: > > {{{ > Traceback (most recent call last): > File "shutter_studio.py", line 41, in > File "App.pyo", line 25, in > File "ui\__init__.pyo", line 23, in > File "ui\FrmProductionOrders.pyo", line 10, in > File "ui\PagEditProductionOrders.pyo", line 8, in > File "ui\GrdProductionOrderOpenings.pyo", line 5, in > File "ui\DlgEditProductionOrderOpening.pyo", line 17, in > File "ui\ShutterCanvas.pyo", line 9, in > File "wx\lib\floatcanvas\FloatCanvas.pyo", line 6, in > File "numpy\__init__.pyo", line 46, in > File "numpy\ctypeslib.pyo", line 9, in > File "ctypes\__init__.pyo", line 20, in > Exception: ('Version number mismatch', '1.0.2', '1.0.3') > }}} > > I just updated from python 2.5.1 to 2.5.2, and wxPython 2.8.7.1 to > 2.8.8.1. The issue is only in the py2exe-built app, not when running the > script from the command line. I guess you should remove the build and dist directories and rebuild your app - this is always a good idea when something goes wrong, not only after upgrading Python or Python packages. Thomas From nadeemabdulhamid at gmail.com Fri Aug 15 23:17:12 2008 From: nadeemabdulhamid at gmail.com (Nadeem) Date: Fri, 15 Aug 2008 20:17:12 -0700 (PDT) Subject: Dynamically defined functions via exec in imported module References: <036d8731-5984-4c23-a15d-efe7e01b5d07@x35g2000hsb.googlegroups.com> Message-ID: Well, I found one hack that seems to achieve this by accessing the globals() dictionary of the outermost stack frame and adding an entry to it for the newly created functions: import inspect def dynamicdef(name, amt): '''Dynamically defines a new function with the given name that adds the given amt to its argument and returns the result.''' stm = "def %s(x):\n\treturn x + %d" % (name, amt) print stm exec stm in globals() ## ADDED THIS TO EXPORT THE NEW FUNCTION NAME TO THE TOP LEVEL... inspect.stack()[-1][0].f_globals[name] = eval(name) I guess I'll go with this unless someone suggests an alternate. Thanks anyway, :) --- nadeem From victorsubervi at gmail.com Tue Aug 12 12:04:05 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 12 Aug 2008 18:04:05 +0200 Subject: Cutting and Pasting in Windows IDLE Message-ID: <4dc0cfea0808120904o507da4tdf855e01994802ff@mail.gmail.com> Hi; A couple of weeks ago I asked how to cut and paste multiple lines in the Windows IDLE interface. I can only paste one line at a time! Frustrating. I want it to work like my Linux interpreter. Why doesn?t it? Please help. Someone wrote this, which did not help at all: Well, I'm not really sure what to say. I've just copied that whole section with drag-mouse, Ctrl-C. I then opened a new interpreter window (effectively, Start > Run > python) and right-clicked over the window. At this point, the lines I copied were copied in and the function accepted by the interpreter. I do have QuickEdit on by default in all by console windows, but the only difference I expect that to make is that you'd otherwise have to use the window's System Menu (Alt-Space, Edit, Paste). TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From piyush.chechani at tcs.com Fri Aug 1 03:54:34 2008 From: piyush.chechani at tcs.com (Piyush Chechani) Date: Fri, 1 Aug 2008 13:24:34 +0530 Subject: Sharing common memory space (In form of List) across the python processes. Message-ID: Hi, I am working on a module where I need to share contents of a big List across the processes. I am using socket programming concept for this. My current processing for this is as follows: - 1. There is a server program S which loads the list in the memory, and listens on a particular port, 2. All the other programs which want to access that list sends a request on that server port, 3. Server sends the id of the memory loaded list element to the requesting process. Here I am getting a problem in the reverse function of id(), as my client should get the list object using its id but I don't know the python function for doing this. Please help me in solving this problem, also if you have any other more robust solution for this processing then please share that. Thanks in advance. Piyush. =====-----=====-----===== Notice: The information contained in this e-mail message and/or attachments to it may contain confidential or privileged information. If you are not the intended recipient, any dissemination, use, review, distribution, printing or copying of the information contained in this e-mail message and/or attachments to it are strictly prohibited. If you have received this communication in error, please notify us by reply e-mail or telephone and immediately and permanently delete the message and any attachments. Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From gminick at nie.ma.takiego.adresu.w.sieci.pl Sun Aug 10 10:21:27 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Sun, 10 Aug 2008 14:21:27 +0000 (UTC) Subject: My very first python program, need help References: <6g8a56FenevdU1@mid.individual.net> Message-ID: Dnia Sun, 10 Aug 2008 15:52:37 +0200, WP napisa?(a): Hi, > import re > > def calculate_sum_1(str): ^^^ this word is reserved, better use some other name > for c in str: > if c.isdigit() == False and c != ' ': > # That we assign to the variable we're looping over worries > me... > str = str.replace(c, ' ') It's good that it worries you. AFAIR python behavior when assigning to a variable that is used in for loop is undefined, so you can't count on it. Better introduce second variable. > > mylist = str.split() > > print "(for loop version) mylist after replace() and split() = ", > mylist > > sum = 0 > > for item in mylist: > sum += long(item) You could use list comprehensions and sum function in here. > def calculate_sum_2(str): > #print "In replace_nondigits_2(), str = ", str > p = re.compile('[^0-9]') or: p = re.compile('\d+') '\d+' is for one or more digits > mylist = p.split(str) You don't have to split this string. Just search through it. Findall method seems appropriate. A bit more pythonic approaches to both of your functions: ======================= import re a="123xx,22! p1" # Note that 'string' isn't the best name too. It may be shadowed by # or shadow 'string' module if it's imported. def calculate_sum_1(string): result = '' for i in string: if i.isdigit(): result += i else: result += ' ' return sum([int(i) for i in result.split()]) def calculate_sum_2(string): pat = re.compile('\d+') digits = [int(i) for i in re.findall(pat, string)] return sum(digits) print calculate_sum_1(a) print calculate_sum_2(a) =========================== -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From bdesth.quelquechose at free.quelquepart.fr Fri Aug 15 11:29:17 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 15 Aug 2008 17:29:17 +0200 Subject: negative numbers are not equal... In-Reply-To: References: Message-ID: <48a5bcc0$0$4514$426a74cc@news.free.fr> castironpi a ?crit : (snip) > It would be nice to put together a really canonical case of the use of > the 'is' comparison. FTSOA for the sake of argument, when do you use > it? When I want to test objects identity. An idenity test is an identity test is an identity test is an.... > Why is it even in the language? Because there's a need for it. From rurpy at yahoo.com Thu Aug 28 09:56:34 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Thu, 28 Aug 2008 06:56:34 -0700 (PDT) Subject: How to ignore the first line of the text read from a file References: <6hmqenFmpekqU1@mid.uni-berlin.de> Message-ID: On Aug 27, 11:12 pm, Marc 'BlackJack' Rintsch wrote: > On Wed, 27 Aug 2008 21:11:26 -0700, youngjin.mich... at gmail.com wrote: > > I want to read text line-by-line from a text file, but want to ignore > > only the first line. I know how to do it in Java (Java has been my > > primary language for the last couple of years) and following is what I > > have in Python, but I don't like it and want to learn the better way of > > doing it. > > > file = open(fileName, 'r') > > lineNumber = 0 > > for line in file: > > if lineNumber == 0: > > lineNumber = lineNumber + 1 > > else: > > lineNumber = lineNumber + 1 > > print line > > > Can anyone show me the better of doing this kind of task? > > input_file = open(filename) > lines = iter(input_file) > lines.next() # Skip line. > for line in lines: > print line > input_file.close() > > Ciao, > Marc 'BlackJack' Rintsch A file object is its own iterator so you can do more simply: input_file = open(filename) input_file.next() # Skip line. for line in input_file: print line, input_file.close() Since the line read includes the terminating EOL character(s), print it with a "print ... ," to avoid adding an additional EOL. If the OP needs line numbers elsewhere in the code something like the following would work. infile = open(fileName, 'r') for lineNumber, line in enumerate (infile): # enumerate returns numbers starting with 0. if lineNumber == 0: continue print line, From davidreynon at gmail.com Thu Aug 14 11:35:15 2008 From: davidreynon at gmail.com (korean_dave) Date: Thu, 14 Aug 2008 08:35:15 -0700 (PDT) Subject: for y in range (0,iNumItems)--> not in order? References: <8514d915-95bf-4e57-a16a-68866e0ad789@l42g2000hsc.googlegroups.com> Message-ID: Still the same output... Here's the actual code... for x in range(0,2): for y in range(0,27): for z in range(0,15): print(str(x) + " " + str(y) + " " + str(z)) From nodrogbrown at gmail.com Sat Aug 30 13:56:27 2008 From: nodrogbrown at gmail.com (gordon) Date: Sat, 30 Aug 2008 10:56:27 -0700 (PDT) Subject: Tkinter event loop question References: <9eaef6c3-c913-497f-8ca2-0466eb178c7a@z6g2000pre.googlegroups.com> <759a12fe-75c8-429a-9a64-19dc73a0b779@b30g2000prf.googlegroups.com> Message-ID: <3e350b67-4114-4ce4-9414-e476ae0b0de1@k36g2000pri.googlegroups.com> On Aug 29, 10:46 pm, "Russell E. Owen" wrote: you > can safely compute stuff with a background thread and display it from> the main thread). But cross that bridge later.> > -- Russell thanks Russel gordon From tjreedy at udel.edu Thu Aug 7 14:58:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 07 Aug 2008 14:58:41 -0400 Subject: benchmark In-Reply-To: References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> Message-ID: M8R-n7vorv at mailinator.com wrote: > Is there any reason why the psyco is not a part of the core python > feature set ? Psyco was a PhD project. I do not believe the author ever offered it. Last I knew, it was almost but not completely compatible. > Is there a particular reason it is better to be kept as > a separate extension ? If he did, he would have to commit to updating it to work with new version of Python (2.6/3.0) which I don't believe he wants to do. Last I know, he was working with the PyPy project instead and its JIT technology. On the otherhand, extensions are also restricted by Python's release schedule, including no new features in bug-fix (dot-dot) releases. So library extensions need to be rather stable but maintained. > Are there any implications of using psyco ? It compiles statements to machine code for each set of types used in the statement or code block over the history of the run. So code used polymorphically with several combinations of types can end up with several compiled versions (same as with C++ templates). (But a few extra megabytes in the running image is less of an issue than it was even 5 or so years ago.) And time spent compiling for a combination used just once gains little. So it works best with numeric code used just for ints or floats. Terry J. Reedy From gminick at nie.ma.takiego.adresu.w.sieci.pl Thu Aug 14 07:22:55 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Thu, 14 Aug 2008 11:22:55 +0000 (UTC) Subject: Replace Several Items References: <513926b0-64fe-4fdc-bb33-bc4b8ad3ab10@a70g2000hsh.googlegroups.com> <00b38b78$0$14351$c3e8da3@news.astraweb.com> Message-ID: On 14 Aug 2008 01:54:55 GMT, Steven D'Aprano wrote: >>>> I don't have to, I can anticipate the results. >>> >>> Chances are that you're wrong. >> >> At the moment my average is about 0.75 of mistake per post on >> comp.lang.python (please, bare with me ;-)). I strongly believe that the >> statement I made above won't make this number rise. > Okay, is this going to be one of those things where, no matter what the > benchmarks show, you say "I was right, I *did* anticipate the results. I > just anticipated them correctly/incorrectly."? Don't count on it. I never really cared about being right or wrong and I am not one of those guys who are trying to prove something that actually makes no difference at all. Nice tests, though :) -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From castironpi at gmail.com Thu Aug 7 17:08:37 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 7 Aug 2008 14:08:37 -0700 (PDT) Subject: Fastest way to store ints and floats on disk References: Message-ID: <041395eb-f6c2-4fe6-9dc9-e75068951a1b@j7g2000prm.googlegroups.com> On Aug 7, 1:41?pm, Laszlo Nagy wrote: > ? Hi, > > I'm working on a pivot table. I would like to write it in Python. I > know, I should be doing that in C, but I would like to create a cross > platform version which can deal with smaller databases (not more than a > million facts). > > The data is first imported from a csv file: the user selects which > columns contain dimension and measure data (and which columns to > ignore). In the next step I would like to build up a database that is > efficient enough to be used for making pivot tables. Here is my idea for > the database: > > Original CSV file with column header and values: > > "Color","Year","Make","Price","VMax" > Yellow,2000,Ferrari,100000,254 > Blue,2003,Volvo,50000,210 > > Using the GUI, it is converted to this: > > dimensions = [ > ? ? { 'name':'Color', 'colindex:0, 'values':[ 'Red', 'Blue', 'Green', > 'Yellow' ], }, > ? ? { 'name':'Year', colindex:1, 'values':[ > 1995,1999,2000,2001,2002,2003,2007 ], }, > ? ? { 'name':'Make', colindex:2, 'value':[ 'Ferrari', 'Volvo', 'Ford', > 'Lamborgini' ], }, > ] > measures = [ > ? ? { 'name', 'Price', 'colindex':3 }, > ? ? { 'name', 'Vmax', 'colindex':4 }, > ] > facts = [ > ? ? ( (3,2,0),(100000.0,254.0) ?), # ( dimension_value_indexes, > measure_values ) > ? ? ( (1,5,1),(50000.0,210.0) ), > ? ?.... # Some million rows or less > ] > > The core of the idea is that, when using a relatively small number of > possible values for each dimension, the facts table becomes > significantly smaller and easier to process. (Processing the facts would > be: iterate over facts, filter out some of them, create statistical > values of the measures, grouped by dimensions.) > > The facts table cannot be kept in memory because it is too big. I need > to store it on disk, be able to read incrementally, and make statistics. > In most cases, the "statistic" will be simple sum of the measures, and > counting the number of facts affected. To be effective, reading the > facts from disk should not involve complex conversions. For this reason, > storing in CSV or XML or any textual format would be bad. I'm thinking > about a binary format, but how can I interface that with Python? > > I already looked at: > > - xdrlib, which throws me DeprecationWarning when I store some integers > - struct which uses format string for each read operation, I'm concerned > about its speed > > What else can I use? > > Thanks, > > ? ?Laszlo Take a look at the mmap module. You get direct memory access, backed by the file system. struct + mmap, if you keep your strings small? From gnewsg at gmail.com Sat Aug 2 14:11:25 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sat, 2 Aug 2008 11:11:25 -0700 (PDT) Subject: Searching for some kind of data type References: <33d13c77-e710-4951-a559-7ea8b6e15287@26g2000hsk.googlegroups.com> Message-ID: <5c1ae2a0-ed85-41a7-afca-4e5d29e1eafb@e53g2000hsa.googlegroups.com> On 2 Ago, 18:18, Gary Herron wrote: > Larry Bates wrote: > > Giampaolo Rodola' wrote: > >> Hi, > >> for an FTP server I wrote I'd need to group the FTP commands in one > >> table that defines the command itself, the syntax string, required > >> permission, whether it requires authorization, whether it takes > >> argument and whether there's a need to validate the path from the > >> argument. > >> The more obvious way I found to do that is something like this: > > >> class CommandProperty: > >> ? ? def __init__(self, perm, auth_needed, arg_needed, check_path, > >> syntax): > >> ? ? ? ? self.perm = perm > >> ? ? ? ? self.auth_needed = auth_needed > >> ? ? ? ? self.arg_needed = arg_needed > >> ? ? ? ? self.check_path = check_path > >> ? ? ? ? self.syntax = syntax > > >> ftp_cmds = { > >> ? ? "ABOR" : CommandProperty(perm=None, auth_needed=True, > >> arg_needed=False, check_path=False, syntax="ABOR (abort transfer)."), > >> ? ? "APPE" : CommandProperty(perm='a', ?auth_needed=True, > >> arg_needed=True, ?check_path=True, ?syntax="APPE file-name > >> (append data to an existent file)."), > >> ? ? "CDUP" : CommandProperty(perm='e', > >> auth_needed=True,arg_needed=False, check_path=False, syntax="CDUP (go > >> to parentdirectory)."), > >> ? ? ... > >> ? ? ... > >> ? ? ... > >> ? ? } > > >> ...but I find it somewhat redundant and... "ugly". > >> I was wondering if there was some kind of data type which could better > >> fit such purpose or if someone could suggest me some other approach to > >> do this same thing. Maybe using a dictionary is not the better choice > >> here. > > >> Thanks in advance > > >> --- Giampaolo > >>http://code.google.com/p/pyftpdlib/ > > > Seems completely reasonable to me. ?You might just consider using > > keyword arguments in the __init__ method and eliminate the dictionary > > altogether. > > > Not tested, but you will get the idea: > > > class CommandProperty: > > ? ? def __init__(self, perm = perm, auth_needed = True, arg_needed = > > True, > > ? ? ? ? ? ? ? ? ?check_path = False, syntax = syntax): > > > ? ? ? ? self.perm = perm > > ? ? ? ? self.auth_needed = auth_needed > > ? ? ? ? self.arg_needed = arg_needed > > ? ? ? ? self.check_path = check_path > > ? ? ? ? self.syntax = syntax > > > ftpCommands = dict( > > ? ? ABOR = CommandProperty(perm = None, arg_needed = False, > > ? ? ? ? ? ? ?syntax="ABOR (abort transfer)."), > > ? ? APPE = CommandProperty(perm = 'a', ?check_path=True, > > ? ? ? ? ? ? ?syntax = "APPE file-name (append data to" \ > > ? ? ? ? ? ? ? ? ? ? ? "an existent file)."), > > ? ? CDUP = CommandProperty(perm= 'e', arg_needed = False, > > ? ? ? ? ? ? ?syntax="CDUP (go> to parentdirectory)."), > > ... > > ... > > ... > > ? ? ) > > How does this strike you? ? ?With care, the comment and the table could > be kept aligned and nicely readable > > cmd_data = dict( > ?# cmd = (perm, auth, ? arg, path, ? syntax), > ?ABOR = (None, False, False, False, "ABOR (abort transfer)."), > ?APPE ?= (None, False, False, True, ?"APPE file-name (append data to"), > ?... > ] > > ftpCommands = {} > for cmd,args in cmd_data.iteritems(): > ? ? ftpCommands[cmd] = CommandProperty(*args) > > Gary Herron > > > > > > > IMHO this is a "little" easier to manage because you can take > > advantage of the default values for keyword arguments to eliminate > > some of the arguments. > > > Hope this helps, > > Larry > > -- > >http://mail.python.org/mailman/listinfo/python-list- Nascondi testo citato > > - Mostra testo citato -- Nascondi testo citato > > - Mostra testo citato - Thanks, I didnt' know dict() could be used with =. I think I'm going to use this solution. --- Giampaolo http://code.google.com/p/pyftpdlib/ From larry.bates at websafe.com` Wed Aug 13 00:43:36 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 12 Aug 2008 23:43:36 -0500 Subject: Random Problems In-Reply-To: References: Message-ID: Lanny wrote: > Well the othe day I was making a program to make a list of all the songs in > certian directorys but I got a problem, only one of the directorys was added > to the list. Heres my code: > > import random > import os > import glob > > songs = glob.glob('C:\Documents and Settings\Admin\My > Documents\LimeWire\Saved\*.mp3') > asongs = glob.glob('C:\Documents and Settings\Admin\My > Documents\Downloads\*\*.mp3') > songs.append(asongs) > asongs = glob.glob('C:\Documents and Settings\Admin\My > Documents\Downloads\*\*\*.mp3') > songs.append(asongs) > asongs = glob.glob('C:\Documents and Settings\Admin\My > Documents\Downloads\*\*\*\*.mp3') > songs.append(asongs) > pick = random.choice(songs) > > all goes well but pick awalys is from the first directory but songs awalys > includes all the files I want it to. Im baffaled. > > > > > -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- > 1) You need to either use raw string for your pathnames or use forward slashes. This is because backslash is an escape character to Python and if you get any legal escaped sequence (like \n, \t, etc) it won't work as expected. songs = glob.glob(r'C:\Documents and Settings\Admin\My Documents\LimeWire\Saved\*.mp3') or songs = glob.glob('C:/Documents and Settings/Admin/My Documents/LimeWire/Saved/*.mp3') Yes, forward slashes work just fine on windows. 2) When you have a list (songs) and append another list (asongs) you don't get a combined list, you get a list with the last element being the second list. example: >>> songs = [1,2,3] >>> asongs = [4,5,6] >>> songs.append(asongs) >>> songs [1, 2, 3, [4, 5, 6]] >>> What you wanted was songs.extend(asongs). BTW-Inserting a couple of print statements would have shown you this problem pretty quickly. -Larry From deets at nospam.web.de Fri Aug 29 06:01:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 29 Aug 2008 12:01:05 +0200 Subject: problem with execv command References: Message-ID: <6hpvnoFng7vhU1@mid.uni-berlin.de> dudeja.rajat at gmail.com wrote: > Hi, > > I'm facing problem with the execv command: > > my command is : > os.execv(' C:\Program Files\Subversion\bin\svn ', ( 'list', ' \" > http://subversion.stv.abc.com/svn/Eng \" ' ) ) > > The error I'm getting is : > OSError: [Errno 22] Invalid argument > > > I tried using a variable for http path but still I'm getting the same > error > > Please help. You need to either escape the backslashes in your path using \\, or use python raw string literals like this: r"C:\foo" or use forward-slashes, which windows accepts as well. Diez From kem1723 at yahoo.com Sun Aug 24 20:59:19 2008 From: kem1723 at yahoo.com (Kevin McKinley) Date: Sun, 24 Aug 2008 17:59:19 -0700 (PDT) Subject: Hide Console Message-ID: <300236.79697.qm@web83915.mail.sp1.yahoo.com> When I use py2exe to convert Python script to executable Windows programs I always have a black console pop up behind my program. If i run the script before i convert it with py2exe it don't have the console because i save the script ending with .pyw instead of .py. Is there a way to get rid or hide this console once i've turned it into a executable windows program? Thanks you Kevin McKinley From alexandru.palade at sellerengine.com Tue Aug 12 04:54:14 2008 From: alexandru.palade at sellerengine.com (Alexandru Palade) Date: Tue, 12 Aug 2008 11:54:14 +0300 Subject: Looking out a module for Subversion In-Reply-To: References: Message-ID: <48A14FB6.4020009@sellerengine.com> As for the open source IDE you can always try Eclipse with PyDev extension. Dudeja, Rajat wrote: > Hi, > > I'm new to Python. I only have read "Byte of Python" by Swaroop C H just > to be familiar with sytax of python. I've installed Python 2.5 from > Active State and using its PythonWin Editor / interpreter. This, > unfortunaltely, does not help in debugging. > > I'm looking for an open source IDE / editor that has source level > debugging. Please suggest some tool. > > I'm intending to write a testing tool that uses Subversion. Is there > some module available for subversion, out of the box, that I can import > in my script? > > Regards, > Rajat > > Notice: This e-mail is intended solely for use of the individual or entity to which it is addressed and may contain information that is proprietary, privileged, company confidential and/or exempt from disclosure under applicable law. If the reader is not the intended recipient or agent responsible for delivering the message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If this communication has been transmitted from a U.S. location it may also contain data subject to the International Traffic in Arms Regulations or U.S. Export Administration Regulations and cannot be disseminated, distributed or copied to foreign nationals, residing in the U.S. or abroad, without the prior approval of the U.S. Department of State or appropriate export licensing authority. If you have received this communication in error, please notify the sender by reply e-mail or collect telephone call and de! > lete or destroy all copies of this e-mail message, any physical copies made of this e-mail message and/or any file attachment(s). > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From iainking at gmail.com Wed Aug 27 10:20:34 2008 From: iainking at gmail.com (Iain King) Date: Wed, 27 Aug 2008 07:20:34 -0700 (PDT) Subject: use of Queue References: Message-ID: <0ef4ba3b-1667-4ba4-994c-6efb5180d0cb@l42g2000hsc.googlegroups.com> On Aug 27, 1:17 pm, Alexandru Mosoi wrote: > On Aug 27, 12:45 pm, Alexandru Mosoi wrote: > > > > > how is Queue intended to be used? I found the following code in python > > manual, but I don't understand how to stop consumers after all items > > have been produced. I tried different approaches but all of them > > seemed incorrect (race, deadlock or duplicating queue functionality) > > > def worker(): > > while True: > > item = q.get() > > do_work(item) > > q.task_done() > > > q = Queue() > > for i in range(num_worker_threads): > > t = Thread(target=worker) > > t.setDaemon(True) > > t.start() > > > for item in source(): > > q.put(item) > > > q.join() # block until all tasks are done > > ok. I think I figured it out :). let me know what you think > > global num_tasks, num_done, queue > num_tasks = 0 > num_done = 0 > queue = Queue() > > # producer > num_tasks += 1 > for i in items: > num_tasks += 1 > queue.put(i) > > num_tasks -= 1 > if num_tasks == num_done: > queue.put(None) > > # consumer > while True: > i = queue.get() > if i is None: > queue.put(None) > break > > # do stuff > > num_done += 1 > if num_done == num_tasks: > queue.put(None) > break Are you sure you want to put the final exit code in the consumer? Shouldn't the producer place a None on the queue when it knows it's finished? The way you have it, the producer could make 1 item, it could get consumed, and the consumer exit before the producer makes item 2. Iain From castironpi at gmail.com Sat Aug 23 20:51:01 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 23 Aug 2008 17:51:01 -0700 (PDT) Subject: property() usage - is this as good as it gets? References: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> Message-ID: On Aug 22, 11:18 am, David Moss wrote: > Hi, > > I want to manage and control access to several important attributes in > a class and override the behaviour of some of them in various > subclasses. > > Below is a stripped version of how I've implemented this in my current > bit of work. > > It works well enough, but I can't help feeling there a cleaner more > readable way of doing this (with less duplication, etc). > > Is this as good as it gets or can this be refined and improved > especially if I was to add in a couple more attributes some fairly > complex over-ride logic? > > #!/usr/bin/env python > > class A(object): > def __init__(self): > self._x = None > self._y = None > > def _set_x(self, value): > self._x = value > > def _get_x(self): > return self._x > > x = property(_get_x, _set_x) > > def _set_y(self, value): > self._y = value > > def _get_y(self): > return self._y > > y = property(_get_y, _set_y) To the OP: you have a unique procedure executed for every attribute of an instance, for each of set, get, and del. That's a lot of code. If you don't want unique procedures, what patterns should they follow? What is wrong with the way you overrode 'get_x' above? When brainstorming, don't restrict yourself to Python syntax-- make something up, and we'll write Python. From fredrik at pythonware.com Wed Aug 13 04:33:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Aug 2008 10:33:13 +0200 Subject: python tr equivalent (non-ascii) In-Reply-To: <552ee625-5d07-4f37-958f-abe046cdff3d@v1g2000pra.googlegroups.com> References: <552ee625-5d07-4f37-958f-abe046cdff3d@v1g2000pra.googlegroups.com> Message-ID: kettle wrote: > I was wondering how I ought to be handling character range > translations in python. > > What I want to do is translate fullwidth numbers and roman alphabet > characters into their halfwidth ascii equivalents. > In perl I can do this pretty easily with tr: > > tr/\x{ff00}-\x{ff5e}/\x{0020}-\x{007e}/; > > and I think the string.translate method is what I need to use to > achieve the equivalent in python. Unfortunately the maktrans method > doesn't seem to accept character ranges and I'm also having trouble > with it's interpretation of length. What I came up with was to first > fudge the ranges: > > my_test_string = u"???????" > f_range = "".join([unichr(x) for x in > range(ord(u"\uff00"),ord(u"\uff5e"))]) > t_range = "".join([unichr(x) for x in > range(ord(u"\u0020"),ord(u"\u007e"))]) > > then use these as input to maketrans: > my_trans_string = > my_test_string.translate(string.maketrans(f_range,t_range)) > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode characters in position > 0-93: ordinal not in range(128) maketrans only works for byte strings. as for translate itself, it has different signatures for byte strings and unicode strings; in the former case, it takes lookup table represented as a 256-byte string (e.g. created by maketrans), in the latter case, it takes a dictionary mapping from ordinals to ordinals or unicode strings. something like lut = dict((0xff00 + ch, 0x0020 + ch) for ch in range(0x80)) new_string = old_string.translate(lut) could work (untested). From sjmachin at lexicon.net Mon Aug 4 06:19:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 4 Aug 2008 10:19:27 +0000 (UTC) Subject: xlrd References: Message-ID: Yeats uol.com.br> writes: > > > Hi, > > Years ago i use xlrd to read data from > excel and now I need again, but i get strange result. The code is: > > from xlrd import * > > Planilha = > open_workbook('C:\\Resultados.xls')Resultados = > Planilha.sheet_by_name('Resultados')c = > (Resultados.cell_value(2,2))print c So that's cell_value(rowx=2, colx=2). colx=2 translates to column C on your screen. rowx=2 translates to row 3 on your screen. What does cell C3 show on your screen when you use Excel? > > and the result is: 0, but the value in > cell is : VERDADEIRO And in what cell is VERDADEIRO on your screen? By the way, it's usually a good idea to say what version of Windows, Python and xlrd that you are using. It's also usually a good idea to check the README file for a third-party module or package to find out where it is suggested that you ask questions ... the answer is rarely comp.lang.python. Cheers, John [xlrd author] From bearophileHUGS at lycos.com Tue Aug 5 13:14:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 5 Aug 2008 10:14:11 -0700 (PDT) Subject: proposal, change self. to . References: Message-ID: <235bd23b-9841-43dc-8629-b8cccd3abf29@b1g2000hsg.googlegroups.com> Heiko Wundram: > > how about changing the precious self. to . > > imagine > > self.update() > > .update() > > simple right? I suggest you to start using Ruby instead. Bye, bearophile From max at alcyone.com Mon Aug 4 05:25:43 2008 From: max at alcyone.com (Erik Max Francis) Date: Mon, 04 Aug 2008 02:25:43 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> <5a0b303a-8324-4eeb-a975-397371bf2875@b1g2000hsg.googlegroups.com> Message-ID: Antoon Pardon wrote: > Maybe I'm going to be pedantic here, but I fear that your code won't > work with matrices. The problem is that multiplication is not > commutative with matrices. This means that matrices have two divisions a right > and a left division. A far as I know the "/" operator usaly implements > the left division while solving is done by using a right division. > > So your code will probably fail when applied to matrices. You're right in your general point, but usually division between matrices isn't defined at all because of this ambiguity. However the general point can still exist between `solveLeft` and `solveRight` functions which do something along the lines of a*b**-1 and a**-1*b. A single `solve`, of course, would choose one of these, and syntactically it might be quite reasonable to define matrix division that does one of these and have a single `solve` function that accomplishes it. Therefore, the general point about polymorphism still stands. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis It is human nature to think wisely and act foolishly. -- Anatole France From simon at brunningonline.net Wed Aug 27 04:26:48 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 27 Aug 2008 09:26:48 +0100 Subject: Python and database unittests In-Reply-To: <3f0d61c40808270048y4173328dhddee0306bb61eb5@mail.gmail.com> References: <485093c5-a0f5-482e-b8fd-3cdd119020d1@r15g2000prd.googlegroups.com> <3f0d61c40808270048y4173328dhddee0306bb61eb5@mail.gmail.com> Message-ID: <8c7f10c60808270126k51b24a9emae30e3485997732f@mail.gmail.com> 2008/8/27 Marco Bizzarri : > I strongly disagree on using mocks for a database; checking sequences > of SQL statement is fragile, painful, and leads you to frustration > when the actual SQL and the generated SQL do not match. Clearly you need integration tests as well as unit tests, but the unit tests ought to isolate the code under test, so stubbing out external dependencies is the norm. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From michele.simionato at gmail.com Tue Aug 5 08:01:22 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 5 Aug 2008 05:01:22 -0700 (PDT) Subject: Hobbyist - Python vs. other languages References: Message-ID: <773321ae-b3ff-46c0-8e87-34a59dcec603@z72g2000hsb.googlegroups.com> On Jul 31, 8:32?pm, fprintf wrote: > Since I don't have a specific problem to solve, besides > Pythonchallenge (which I found very cryptic), and Project Euler (which > I found beyond my mathematics skills), is there a place to go for > increasingly difficult problems to solve? I have followed a number of > the recommended online tutorials that contain a logical progression of > problems and yet they all end at the point where a person has enough > knowledge of the syntax, but not really enough to do anything. Just today I saw this recipe on the cookbook, "TV-Series Current Episode Info": http://code.activestate.com/recipes/572193/ As you see, there are plenty of useful things you can do with a programming language ;) Another trivial example: I am keeping an electronic journal as a Python script which checks today's date, create a file with that date (if it does not exist already) and open it with Emacs. That's all. I can search the journal with grep. Since I write the journal in rst format I can publish it on the Web in HTML or print it in PDF. It takes 20 minutes to write a script like that, and it working better for my needs than any commercial application could. The biggest feature is the absence of features: less is more. Michele Simionato From modelnine at modelnine.org Wed Aug 6 08:54:13 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Wed, 06 Aug 2008 14:54:13 +0200 Subject: Find class of an instance? In-Reply-To: References: Message-ID: <1218027253.4182.2.camel@phoenix> Am Mittwoch, den 06.08.2008, 08:44 -0400 schrieb Neal Becker: > Sounds simple, but how, given an instance, do I find the class? .__class__ For example: Python 2.5.2 (r252:60911, Aug 5 2008, 03:26:50) [GCC 4.3.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x = "hello" >>> x.__class__ >>> --- Heiko. From deets at nospam.web.de Wed Aug 27 12:44:46 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 27 Aug 2008 18:44:46 +0200 Subject: how do I stop SocketServer()? References: Message-ID: <6hleksFmq0nuU1@mid.uni-berlin.de> Alexandru Mosoi wrote: > supposing that I have a server (an instance of SocketServer()) that > waits for a connection (ie is blocked in accept()) and in another > thread i want to stop the server, how do I do that? By setting a timeout on the socket using socket.settimeout, and then periodically check for an abortion condition in the server thread before re-accepting connections. Diez From manthra.mohan at gmail.com Thu Aug 7 12:23:51 2008 From: manthra.mohan at gmail.com (Krishna) Date: Thu, 7 Aug 2008 09:23:51 -0700 (PDT) Subject: Access individual fields in csv using python Message-ID: How do I access individual fields in csv using python? Please let me know ASAP as its real urgent for me. Thanks for your help Krishna From fredrik at pythonware.com Sun Aug 24 12:43:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 24 Aug 2008 18:43:25 +0200 Subject: IDE In-Reply-To: <53839854-fdc6-4ffb-857b-8d68ae41606a@d1g2000hsg.googlegroups.com> References: <53839854-fdc6-4ffb-857b-8d68ae41606a@d1g2000hsg.googlegroups.com> Message-ID: krishna wrote: > i need link of latest IDE of python(GUI) http://wiki.python.org/moin/IntegratedDevelopmentEnvironments (is google broken today?) From tjreedy at udel.edu Tue Aug 5 15:57:50 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 05 Aug 2008 15:57:50 -0400 Subject: string to type object (C) In-Reply-To: <4477a269-f189-4ae1-9c97-e78633bb3d27@2g2000hsn.googlegroups.com> References: <4477a269-f189-4ae1-9c97-e78633bb3d27@2g2000hsn.googlegroups.com> Message-ID: castironpi wrote: > Hello, > > I'm looking for a one-to-one function from strings to the built-in > data types in C. I will be keeping the string in a file. I need the > PyTypeObject* back from it. Use a dict mapping py strings to the object pointers (cast to py ints). From giles.thomas at resolversystems.com Tue Aug 19 12:32:45 2008 From: giles.thomas at resolversystems.com (Giles Thomas) Date: Tue, 19 Aug 2008 17:32:45 +0100 Subject: ANN: Resolver One 1.2 released Message-ID: <48AAF5AD.1050007@resolversystems.com> 2008/8/19 km Hi, sounds great - but disappointing to find it only available on window$. Is there any Linux release in near future ??? KM Not in the near future, unfortunately - but we're looking at getting it running under Mono in the medium term. The big problem is that we'll have to change (or even recode) our grid component. Best regards, Giles -- Giles Thomas MD & CTO, Resolver Systems Ltd. giles.thomas at resolversystems.com +44 (0) 20 7253 6372 Try out Resolver One! 17a Clerkenwell Road, London EC1M 5RD, UK VAT No.: GB 893 5643 79 Registered in England and Wales as company number 5467329. Registered address: 843 Finchley Road, London NW11 8NA, UK -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 26 05:11:05 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 26 Aug 2008 11:11:05 +0200 Subject: generate methods at runtime, but the wrong one gets called In-Reply-To: References: Message-ID: <48b3c879$0$8908$426a74cc@news.free.fr> Maric Michaud a ?crit : (snip) > i don't get your design, it seems over-complicated to mee at first glance. > From coolman.guron at gmail.com Sat Aug 2 16:35:23 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Sat, 2 Aug 2008 13:35:23 -0700 (PDT) Subject: why goes the time change after import statement ? Message-ID: <011a92b4-b911-4f63-9339-be46b48d5f76@v1g2000pra.googlegroups.com> hi i am working on a S3 project and facing a really weird problem! take a look at the following import statements and the time output >>> import time >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) 'Sat, 02 Aug 2008 20:21:56 GMT' # OK >>> import pygtk >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) 'Sat, 02 Aug 2008 20:22:04 GMT' # OK >>> import gtk >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) 'Sat, 02 Aug 2008 08:22:11 PM GMT' # HOW THE HELL THIS HAPPEN ??? not DATE_RFC2822 format gmt time ! i have waisted 3 hours trying to locate the source of this strange problem. so what i am asking is does anyone know to overwrite or fix the defaurl behaviour strftime() ???? From info at orlans-amo.be Sun Aug 17 04:20:48 2008 From: info at orlans-amo.be (info at orlans-amo.be) Date: Sun, 17 Aug 2008 01:20:48 -0700 (PDT) Subject: Good python equivalent to C goto References: <48a744b6$0$299$7a628cd7@news.club-internet.fr> Message-ID: <887b84d8-ee3e-4c55-8518-b2f21ab50619@a1g2000hsb.googlegroups.com> as an oldtimer, I know that in complex code the goto statement is still the easiest to code and understand. I propose this solution using exception. The string exception is deprecated but is simpler for this example. # DeprecationWarning: raising a string exception is deprecated def Goto_is_not_dead(nIn): try: if (nIn == 1): raise 'Goto_Exit' if (nIn == 2): raise 'Goto_Exit' print 'Good Input ' + str(nIn) raise 'Goto_Exit' except 'Goto_Exit': print 'any input ' + str(nIn) if __name__ == '__main__': Goto_is_not_dead(2) Goto_is_not_dead(3) From deets at nospam.web.de Tue Aug 5 18:33:15 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 06 Aug 2008 00:33:15 +0200 Subject: Dictionary to tree format (hopefully simple) In-Reply-To: References: Message-ID: <6fs2pbFd43utU1@mid.uni-berlin.de> Adam Powell schrieb: > Hi! > I have seemingly simple problem, which no doubt someone out there has > already solved, but I'm stumped. Imagine I have a dictionary like > below, in which the keys are parent nodes and the values are a list of > children nodes. > > dict = { 0: [1, 2], 1: [3], 2: [6], 3: [4,7], 4: [5,8], 8: [9] } > > Is there an obvious way to produce a nested tree format for this > dictionary, like this: > > [ 0 [ 1 [ 3 [ 4 [ 5 , 8 [ 9 ] ] , 7 ] ] , 2 [ 6 ] ] > > Thanks for any help, d = { 0: [1, 2], 1: [3], 2: [6], 3: [4,7], 4: [5,8], 8: [9] } nodelists = dict((node ,[node, []]) for node in d.keys()) for node, children in d.iteritems(): for child in children: nodelists[node][1].extend(nodelists.setdefault(child, [child])) print nodelists[0] Two remarks: - don't use "dict" as name for a dictionary - look at the above code *why* not... - the code assumes that 0 is the root. if that wouldn't be the case, you need to search for the root node. I've got an idea - you to? Diez From __peter__ at web.de Tue Aug 26 03:13:46 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 26 Aug 2008 09:13:46 +0200 Subject: smart quotes References: <4188c027-3c64-429b-a1e6-a1f3a79060e8@a3g2000prm.googlegroups.com> Message-ID: Adrian Smith wrote: > Can anyone tell me how to get rid of smart quotes in html using > Python? I've tried variations on > stuff = string.replace(stuff, "\?", "\""), but to no avail, presumably > because they're not standard ASCII. Convert the string to unicode. For that you have to know its encoding. I assume UTF-8: >>> s = "a ?smart quote? example" >>> u = s.decode("utf-8") Now you can replace the quotes (I looked up the codes in wikipedia): >>> u.replace(u"\u201c", "").replace(u"\u201d", "") u'a smart quote example' Alternatively, if you have many characters to remove translate() is more efficient: >>> u.translate(dict.fromkeys([0x201c, 0x201d, 0x2018, 0x2019])) u'a smart quote example' If necessary convert the result back to the original encoding: >>> clean = u.translate(dict.fromkeys([0x201c, 0x201d, 0x2018, 0x2019])) >>> clean.encode("utf-8") 'a smart quote example' Peter From mail at timgolden.me.uk Wed Aug 6 15:50:19 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 06 Aug 2008 20:50:19 +0100 Subject: Calculate sha1 hash of a binary file In-Reply-To: <3e828257-07b5-478e-939d-8bf6addc112a@k30g2000hse.googlegroups.com> References: <3e828257-07b5-478e-939d-8bf6addc112a@k30g2000hse.googlegroups.com> Message-ID: <489A007B.5030503@timgolden.me.uk> LaundroMat wrote: > Hi - > > I'm trying to calculate unique hash values for binary files, > independent of their location and filename, and I was wondering > whether I'm going in the right direction. > > Basically, the hash values are calculated thusly: > > f = open('binaryfile.bin') > import hashlib > h = hashlib.sha1() > h.update(f.read()) > hash = h.hexdigest() > f.close() > > A quick try-out shows that effectively, after renaming a file, its > hash remains the same as it was before. > > I have my doubts however as to the usefulness of this. As f.read() > does not seem to read until the end of the file (for a 3.3MB file only > a string of 639 bytes is being returned, perhaps a 00-byte counts as > EOF?), is there a high danger for collusion? Guess: you're running on Windows? You need to open binary files by using open ("filename", "rb") to indicate that Windows shouldn't treat certain characters -- specifically character 26 -- as special. TJG From gminick at bzt.bzt Fri Aug 22 06:05:06 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Fri, 22 Aug 2008 10:05:06 +0000 (UTC) Subject: def X(l=[]): weirdness. Python bug ? References: <8824d$48ae83b2$18847a51$1995@news.chello.nl> <6h7fvbFjm6ogU2@mid.uni-berlin.de> Message-ID: On Fri, 22 Aug 2008 11:42:03 +0200, Diez B. Roggisch wrote: > It's amazing. I didn't analyse this properly, but IMHO this issue is the > single most asked question (or rather the effects in produces) on this list. > > Maybe we should get *really* explicit in > > http://docs.python.org/tut/node6.html#SECTION006710000000000000000 > > and > > http://docs.python.org/ref/function.html > > Big, red warnings, or some such. +1 Documenting this should also make it easier to understand the difference between mutable/immutable objects before one comes on c.l.py and asks about it. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From rajat.dudeja at aeroflex.com Thu Aug 14 11:37:06 2008 From: rajat.dudeja at aeroflex.com (Dudeja, Rajat) Date: Thu, 14 Aug 2008 11:37:06 -0400 Subject: How do I organize my Python application code? In-Reply-To: References: Message-ID: >>Fredrik Lundh wrote: >> That's all there is; there's no header files or declaration files or >> explicitly maintained object files etc; the program itself is just a >> bunch of Python files. >I would simply add that if your python script produces one or more output files (for example a text or graphic file) >you might want to have an 'output' directory in your project. >Some people use a 'src' directory, but that is not nearly as neccessary as in a complied language. Thanks Ken and Fredrik for your direction. Cheers, Rajat Notice: This e-mail is intended solely for use of the individual or entity to which it is addressed and may contain information that is proprietary, privileged, company confidential and/or exempt from disclosure under applicable law. If the reader is not the intended recipient or agent responsible for delivering the message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If this communication has been transmitted from a U.S. location it may also contain data subject to the International Traffic in Arms Regulations or U.S. Export Administration Regulations and cannot be disseminated, distributed or copied to foreign nationals, residing in the U.S. or abroad, without the prior approval of the U.S. Department of State or appropriate export licensing authority. If you have received this communication in error, please notify the sender by reply e-mail or collect telephone call and delete or destroy all copies of this e-mail message, any physical copies made of this e-mail message and/or any file attachment(s). From maric at aristote.info Wed Aug 13 21:19:00 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 14 Aug 2008 03:19:00 +0200 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: <76fd5acf0808131659i361d7fbdo595bebf57aeab317@mail.gmail.com> References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> <200808122240.22517.maric@aristote.info> <76fd5acf0808121415h41cc580bj85d96e648c54ab4b@mail.gmail.com> <200808140141.38909.maric@aristote.info> <76fd5acf0808131659i361d7fbdo595bebf57aeab317@mail.gmail.com> Message-ID: <48A38804.5060603@aristote.info> Calvin Spealman a ?crit : > On Wed, Aug 13, 2008 at 7:41 PM, Maric Michaud wrote: >> I was not aware of any "nested classes are unsupported" before and didn't >> consider nested classes as bad practice till now, even with the pickle >> limitation (not every class are intended to be pickled), more you didn't give >> any evidence or any pertinent quote of this and at least one of Guido in the >> above threads seems contradict you : >> http://mail.python.org/pipermail/python-dev/2002-November/029906.html > > Of course, I don't have to agree with Guido, neither do I, for sure. > but I don't really think > his comment there counts as some encouragement of the practice. It > also isn't an example that actually demonstrates the things people > misuse about nesting classes, although its definitely an example that > I think could be done much better without them, at all. > Yes this example is some sort of metalanguage using class statment in a derived way, It comes in mind sometimes by the fact there is no other way to extend the language to make DSL in python (perhaps easy extend will be popular one day, but I doubt). I did something like that before in an application and won't encourage anyone to do so. > The use of nested classes to define some hierarchical structure is > subject, at best. And, the examples I see aren't even hierarchical. > The nesting doesn't seem to gain them anything. As a matter of fact, > wouldn't that example be a lot more clear with one class and some > "Attribute" properties describing the structure? > > What rubs me the wrong way about nested classes is that they aren't > even "real" classes. That is, they aren't being used to instantiate > instances, but just as dummy scopes to hold some attributes. They are > abusing classes as property bags. > Here, I disagree, the helper classes example is good IMO, defining an Iterator as an inner class and referencing it by MyIterable.Iterator is good style. That said, I understood from your first post that python community in general will discourage nested classes as bad practice and consider them not supported by the language, statment for which I can't find or remember no evidence. >> BTW my concern was not really about nested classes but the asymetry between >> function scope and classes scope, there are at least two examples that come >> to my mind and for which I don't see good argument to keep the situation as >> it is. First is the very odd behavior of genexp, second is the dynamic type >> factory, I know it's not a big deal to in each case and can live with this, >> but these pieces of code fail unexpectedly while even a experimented python >> programmer would have thought they work at first glance, and the explanation >> of why they fail to a newcomer is not easy (specially for the first) >> >> (1) this fail only on the last line while it would have work well with >> listcomp and works well in a function definition >> class A(object) : >> l = range(5) >> m = list(a+b for a in l for b in range(5)) >> n = list(a+b for a in range(5) for b in l) > > I can admit that this behavior can be surprising, but it isn't > something I really see cropping up as a problem. How often do you see > that you need to have any kind of procedural behavior in a class body? > In other words, in all but rare cases, the order of the class body > lines shouldn't change the resulting class, but this example breaks > that expectation. > I wrote something like that a few months ago, and found it both simple concise and elegant : class test_suite1(test_suite) : roles = (role1, ...) actors = (actor1, ...) use_cases = [ (actor, role) for actor in actors for role in roles ] which I wrote at first tuple((actor, role) for ...) and came to the problem. Of course use_cases can be made a true generator, but in this particular case building the tuple/list together with the class is good enough. >> (2) This won't work as it would with nested functions, you need to build the >> new calss directly with type('dynamic', (object,), {"type_": type_}) >> >> def create_type(type_) : >> class dynamic(object) : >> type_ = type_ >> return dynamic > > This is simply completely invalid. That code at the beginning of any > body will _always_ raise either an UnboundLocalError or a NameError, > because you are assigning to the same name you are dereferencing. That > line will always be either an error or a no-op, anywhere it appears. > It has nothing to do with nesting of any sort. > Yes, of course, sorry, it should be : def create_type(t) : class dynamic(object) : type_ = t return dynamic but this work to my surprise ! I just thought the "t" in the class body would be looked up in global namespace. The design is that "free vars doesn't bind to class namespaces" not that "free vars of class namespaces bind to global namespace", my mistake. >> -- >> _____________ >> >> Maric Michaud >> -- >> http://mail.python.org/mailman/listinfo/python-list > > > From Edwin.Madari at VerizonWireless.com Thu Aug 14 21:02:19 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Thu, 14 Aug 2008 21:02:19 -0400 Subject: SOAPpy and ArrayOfString In-Reply-To: Message-ID: <20080815010231.8D4291E4007@bag.python.org> for someMethod(Field1 ArrayOf_xsd_string, other_parameters) a call someMethod( ['str1', 'str2', 'str3'], other_parameters) *works for me* with SOAPpy 0.12.0. yes sir it does. in PERL, let alone array types, even for simple types it was hard for me with all the '->', and '$' prefixing for objects and variables. I use following snippet to check arguments, and return types from a wsdl for each method. If any on them is not a simple type, check the wsdl manually for details of the data type. ==================================================== import os, sys, glob from SOAPpy import WSDL def checkwsdl(file): if os.path.isfile(file): print 'wsdl:%s' % file server = WSDL.Proxy(file) for ct, k in enumerate(server.methods.keys()): args =[] rets = [] callInfo = server.methods[k] for ct2, name in enumerate(callInfo.inparams): args.append('%s %s' % (name.name.encode(), name.type[1].encode())) for ct2, name in enumerate(callInfo.outparams): rets.append('%s %s' % (name.name.encode(), name.type[1].encode())) print '%s. %s(%s)\n\treturns(%s)' % ( ct+1, k.encode(), ',\n\t\t'.join(args), ',\n\t\t'.join(rets)) print if __name__ == '__main__' : args = sys.argv[1:] for arg in args: for file in glob.glob(arg): checkwsdl(file) ==================================================== Even though a method may be asking for an array, server may be accepting only up to a certain number of elements in the array. And check the data type for elements in the array. of course I had to tweak a couple of SOAPpy modules to accept long data type, and work from behind a firewall. hope that helps... thanks Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org]On Behalf Of annu miya Sent: Thursday, August 14, 2008 12:11 PM To: python-list at python.org Subject: SOAPpy and ArrayOfString Hi, In the article below you mention that you were succesful at doing this through perl. Would it be possible to send me the perl code? http://mail.python.org/pipermail/python-list/2007-January/423311.html Thank You Regards Sid The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jimgardener at gmail.com Thu Aug 28 13:01:42 2008 From: jimgardener at gmail.com (jimgardener) Date: Thu, 28 Aug 2008 10:01:42 -0700 (PDT) Subject: cannot find object instance References: <6b8a855f-8ff4-41f8-87f1-1b832368dd83@v16g2000prc.googlegroups.com> <48b6d3a1$0$27466$426a74cc@news.free.fr> Message-ID: On Aug 28, 9:35 pm, Bruno Desthuilliers wrote: Such a ping-pong between two classes is more often > than not a design smell. thanks Bruno,i understand my mistake..should have figured it out myself thanks again jim From info at thegrantinstitute.com Tue Aug 19 21:10:23 2008 From: info at thegrantinstitute.com (Anthony Jones) Date: 19 Aug 2008 18:10:23 -0700 Subject: Professional Grant Proposal Writing Workshop (September 2008: British Columbia Institute of Technology - Vancouver Campus) Message-ID: <20080819181022.1AC4026A075D7281@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Aug 15 13:19:21 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 15 Aug 2008 10:19:21 -0700 (PDT) Subject: negative numbers are not equal... References: Message-ID: On Aug 15, 8:56?am, Dan Lenski wrote: > On Thu, 14 Aug 2008 17:18:55 -0300, ariel ledesma wrote: > > hello guys > > > i just ran into this when comparing negative numbers, they start > > returning False from -6 down, but only when comparing with 'is' > > > ?>>> m = -5 > > ?>>> a = -5 > > ?>>> m is a > > True > > ?>>> m = -6 > > ?>>> a = -6 > > ?>>> m is a > > False > > ?>>> m == a > > True > > > i read that 'is' compares if they are really the same object, but i > > don't that's it because then why does -5 return True? of course i could > > only use == to compare, but still, what am i missing here? thanks in > > advance > > They also return False for positive numbers > 256. ?Try this: > ?>>> print [x for x in range(-10,260) if x is not x+1-1] > [-10, -9, -8, -7, -6, 257, 258, 259] > > There is a good explanation for this: the "is" operator checks for object > identity, not equality. ?Basically "a is m" asks, does the variable name > "a" reference the same memory location as the variable name "m"? > > For integers in the range of -5<=x<=256, Python pre-caches all of these > values, and whenever a variable takes on one of those values, it uses the > cached value. ?This is an optimization: it prevents the need to allocate > a new Python object for these very very common small integer values. > > For integer literals outside this range, a new Python object gets created > when they are assigned to variables, so a=500 followed by m=500 will > create new objects. > > The "is" operator just shows the effect of this caching. ?It's > unimportant for real code since you never care whether two numeric > variables refer to the same object (only important for complex data > structures where their storage may overlap)... only whether they are > equal or not. > > Dan Lenski > > (PS- The small integer pre-caching is described somewhere in the C API > docs.) It would be nice to put together a really canonical case of the use of the 'is' comparison. FTSOA for the sake of argument, when do you use it? Why is it even in the language? If you're iterating over a list, flagA= object() flagB= object() flagC= -10 listA= [ objectA, objectB, flagA, objectC, flagB, -10, objectD ] flags= [ listA, listB, listC ] for iA in listA: for flag in flags: if iA is flag: handle( iA ) This case actually misses handleC(). The solution is that the function that is returning '-10' cannot return -10, it has to return flagC. This can cause difficulties in cases when you're doing operations on flags. Worse, if flagC is nested somewhere, say moduleA.classB.flagC, you still have to work with that, not its value. From ivosh at ivosh.net Fri Aug 29 02:46:50 2008 From: ivosh at ivosh.net (Ivo Raisr) Date: Fri, 29 Aug 2008 08:46:50 +0200 Subject: Python-2.3.4 on OSF1 V4.0? Message-ID: <6055659e0808282346r2fcca861r21b5e09ce67d06e4@mail.gmail.com> Hi Edmond and any interested reader, I've successfully patched _socket extension of python 2.5.1 to build on OSF1 V4.0 with gcc 4.1.2. The following construct is put right after #include "Python.h" and #include "structmember.h": #define _POSIX_PII_SOCKET #define _LIBC_POLLUTION_H_ Ivosh Raisr From nytrokiss at gmail.com Sun Aug 24 14:48:20 2008 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 24 Aug 2008 11:48:20 -0700 Subject: Interrupt python thread In-Reply-To: References: Message-ID: <8a6b8e350808241148k496fcdf6hb6a938798d848b12@mail.gmail.com> Group all the threads in a list and call the stop method on all of them. On Sun, Aug 24, 2008 at 1:48 AM, BlueBird wrote: > Hi, > > I have a program with a master thread and several slave threads. > > Whenever an exception occurs, in the master thread or in one of the > slave threads, I would like to interrupt all the threads and the main > program. Threading API does not seem to provide a way to stop a > thread, is there anyway to achieve that ? > > The closest thing I found is thread.interrupt_main() but it's far from > perfect : > - it only allow to interrupt the main thread > - if the main thread is sleeping, it does not interrupt it (at least > on windows) > > cheers, > > Philippe > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Mon Aug 4 18:20:18 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 05 Aug 2008 08:20:18 +1000 Subject: What Python looks like References: Message-ID: <87ej54778d.fsf@benfinney.id.au> iu2 writes: > I'm curious, what did Python code look like to those of you who have > seen a bunch of Python code for the first time before knowing Python? To me it looked like the pseudo-code used for describing algorithms, allowing clear understanding and redesign of the algorithm before adding all the cruft "necessary" to make a real program from it. I was very impressed, therefore, that program code could be so clear and readable, and yet require so little computer-friendly cruft. > (I can tell, for example, that seeing perl for the first time looked > like C with many $$$, I could see "if" and "for" and "while" but they > were meaningless. Being already familiar with Bourne-style shell programs, Perl just looked to me like an even-more-baroque version of Bourne shell syntax. Not surprising, since that was one of its main inspirations. > Or Lisp for the first time looked like many words, no operators, how > could that make a program???) I had no referent with which to compare Lisp when I first saw it. I did wonder "if the program is so nicely indented anyway, why are all these parentheses necessary?" That was many years before I encountered Python :-) -- \ ?I see little commercial potential for the Internet for at | `\ least ten years.? ?Bill Gates, 1994 | _o__) | Ben Finney From matthias.blaesing at rwth-aachen.de Mon Aug 18 10:07:44 2008 From: matthias.blaesing at rwth-aachen.de (Matthias =?iso-8859-1?q?Bl=E4sing?=) Date: 18 Aug 2008 14:07:44 GMT Subject: Dropping privileges in python daemon References: Message-ID: Am Mon, 18 Aug 2008 14:33:27 +0200 schrieb David H?rdeman: > > I'm used from C programming to use setresuid() to change the real, > effective and saved uid in one go, and although the os module has some > of the set*uid() functions it doesn't seem to have setresuid(). no - python offers the posix function setuid. Have a look here: http://www.opengroup.org/onlinepubs/000095399/functions/setuid.html Without any further knowledge this should do everything you want from it and it is available from the posix and/or the os module. HTH Matthias From sjmachin at lexicon.net Wed Aug 6 17:36:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 6 Aug 2008 14:36:01 -0700 (PDT) Subject: Parsing of a file References: <760c7cd4-5a23-4e8e-801d-31670afd050b@l42g2000hsc.googlegroups.com> <91b5cd11-1bb6-4715-8964-85afc77862d1@1g2000pre.googlegroups.com> Message-ID: <7f838daa-399d-40ae-a6a8-4551b25e4c68@b30g2000prf.googlegroups.com> On Aug 7, 7:06 am, John Machin wrote: > On Aug 7, 6:02 am, Mike Driscoll wrote: > > > > > On Aug 6, 1:55 pm, Tommy Grav wrote: > > > > I have a file with the format > > > > Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames > > > 5 Set 1 > > > Field f31448: Ra=20:24:58.13 Dec=+79:39:43.9 MJD=53370.06811620 Frames > > > 5 Set 2 > > > Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames > > > 5 Set 3 > > > Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames > > > 5 Set 4 > > > Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames > > > 5 Set 5 > > > Field f30560: Ra=20:27:01.82 Dec=+74:47:50.3 MJD=53370.06860400 Frames > > > 5 Set 6 > > > Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames > > > 5 Set 7 > > > Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames > > > 5 Set 8 > > > Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames > > > 5 Set 9 > > > Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames > > > 5 Set 10 > > > > I would like to parse this file by extracting the field id, ra, dec > > > and mjd for each line. It is > > > not, however, certain that the width of each value of the field id, > > > ra, dec or mjd is the same > > > in each line. Is there a way to do this such that even if there was a > > > line where Ra=****** and > > > MJD=******** was swapped it would be parsed correctly? > > > > Cheers > > > Tommy > > > I'm sure Python can handle this. Try the PyParsing module or learn > > Python regular expression syntax. > > >http://pyparsing.wikispaces.com/ > > > You could probably do it very crudely by just iterating over each line > > and then using the string's find() method. > > Perhaps you and the OP could spend some time becoming familiar with > built-in functions and str methods. In particular, str.split is your > friend: > > C:\junk>type tommy_grav.py > # Look, Ma, no imports! > > guff = """\ > Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames > 5 Set 1 > Field f31448: MJD=53370.06811620123 Dec=+79:39:43.9 Ra=20:24:58.13 > Frames 5 Set > 2 > Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames > 5 Set 3 > Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames > 5 Set 4 > Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames > 5 Set 5 > > Field f30560: Ra=20:27:01.82 Dec=+74:47:50.3 MJD=53370.06860400 Frames > 5 Set 6 > Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames > 5 Set 7 > Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames > 5 Set 8 > Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames > 5 Set 9 > Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames > 5 Set 10 > > """ > > is_angle = { > 'ra': True, > 'dec': True, > 'mjd': False, > } > > def convert_angle(text): > deg, min, sec = map(float, text.split(':')) > return (sec / 60. + min) / 60. + deg > > def parse_line(line): > t = line.split() > assert t[0].lower() == 'field' > assert t[1].startswith('f') > assert t[1].endswith(':') > field_id = t[1].rstrip(':') > rdict = {} > for f in t[2:]: > parts = f.split('=') > if len(parts) == 2: > key = parts[0].lower() > value = parts[1] > assert key not in rdict > if is_angle[key]: > rvalue = convert_angle(value) > else: > rvalue = float(value) > rdict[key] = rvalue > return field_id, rdict['ra'], rdict['dec'], rdict['mjd'] > > for line in guff.splitlines(): > line = line.strip() > if not line: > continue > field_id, ra, dec, mjd = parse_line(line) > print field_id, ra, dec, mjd > > C:\junk>tommy_grav.py > f29227 20.3962611111 67.5 53370.0679769 > f31448 20.4161472222 79.6621944444 53370.0681162 > f31226 20.4126388889 78.4458888889 53370.0682386 > f31004 20.4181333333 77.2296944444 53370.0683602 > f30782 20.4310944444 76.0135 53370.0684821 > f30560 20.4505055556 74.7973055556 53370.068604 > f30338 20.4756527778 73.5811111111 53370.0687262 > f30116 20.5060277778 72.3648888889 53370.0688489 > f29894 20.5412611111 71.1486111111 53370.0689707 > f29672 20.5810805556 69.9323888889 53370.0690935 > > Cheers, > John Slightly less ugly: C:\junk>diff tommy_grav.py tommy_grav_2.py 18,23d17 < is_angle = { < 'ra': True, < 'dec': True, < 'mjd': False, < } < 27a22,27 > converter = { > 'ra': convert_angle, > 'dec': convert_angle, > 'mjd': float, > } > 41,44c41 < if is_angle[key]: < rvalue = convert_angle(value) < else: < rvalue = float(value) --- > rvalue = converter[key](value) From simon at mullis.co.uk Mon Aug 25 08:52:24 2008 From: simon at mullis.co.uk (Simon Mullis) Date: Mon, 25 Aug 2008 14:52:24 +0200 Subject: Equivalents of Ruby's "!" methods? Message-ID: <23d7e1bb0808250552r7d2b7097ye9e8777b4dcaa99c@mail.gmail.com> Hi All, Quick question, I can't seem to find the answer online (well, at the moment I think the answer is a simple "no" but I would like to confirm). Consider the following hash: h = { "1" : "a\r", "2" : "b\n" } In order to strip the dict values in Python I (think) I can only do something like: for k,v in h.items: h[k] = v.strip() While in Ruby - for the equivale dict/hash - I have the option of an in-place method: h.each_value { |v| val.strip! } Are there Python equivalents to the "!" methods in Ruby? The reason I ask is that I have some fairly complex data-structures and this would make my code alot cleaner... If this is not an accepted and pythonic way of doing things then please let me know... and I'll stop! Thanks in advance SM -- Simon Mullis _________________ simon at mullis.co.uk From vat.vjay10 at gmail.com Sun Aug 24 08:53:23 2008 From: vat.vjay10 at gmail.com (vat.vjay10 at gmail.com) Date: Sun, 24 Aug 2008 05:53:23 -0700 (PDT) Subject: Hai you looking Real Esate Agents India Message-ID: <2697bd8f-9dc6-405e-8243-513c3353ab18@b2g2000prf.googlegroups.com> http://www.moneymaking4.blogspot.com/ From andybak at gmail.com Tue Aug 12 06:41:46 2008 From: andybak at gmail.com (andybak) Date: Tue, 12 Aug 2008 03:41:46 -0700 (PDT) Subject: Jason Orendorff's path module Message-ID: Hi, I know this has been consigned to oblivion by the BDFL but I'm rather addicted to it's use. I notice the original site is no longer there. Has anyone got a cached copy of the page that I can host for posterity? Which rather makes me wonder - lot's of people liked this module or rather disliked os.path. Is there anything salvageable from the BDFL's objections worthy of a PEP? Andy From __peter__ at web.de Wed Aug 27 09:50:06 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 27 Aug 2008 15:50:06 +0200 Subject: finding out the number of rows in a CSV file [Resolved] References: <3aaa109e-9a7e-4d02-8af5-0161251d7678@t54g2000hsg.googlegroups.com> <0bc6097f-af52-4951-a413-e9a983df93c7@79g2000hsk.googlegroups.com> Message-ID: Jon Clements wrote: > On Aug 27, 12:54 pm, SimonPalmer wrote: >> after reading the file throughthe csv.reader for the length I cannot >> iterate over the rows. How do I reset the row iterator? > > If you're sure that the number of rows is always less than 200. Or 2000. Or 20000... Actually any number that doesn't make your machine fall into a coma will do. > Slightly modify Simon Brunning's example and do: > > rows = list( csv.reader(open('filename.csv')) ) > row_count = len(rows) > for row in rows: > # do something Peter From ethan at stoneleaf.us Thu Aug 7 15:14:06 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 07 Aug 2008 11:14:06 -0800 Subject: very newbie question In-Reply-To: <5F1D8E1D20CE4B7D9E874FED0AFFD677@Home> References: <5F1D8E1D20CE4B7D9E874FED0AFFD677@Home> Message-ID: <489B497E.1010603@stoneleaf.us> garywood wrote: > stuck on python for absolute beginners > chapter 6 > i actually done what i was supposed to do use the function ask_number > for guess a number > but for some reason it does not count correctly the number of tries > > # Guess My Number > # > # The computer picks a random number between 1 and 100 > # The player tries to guess it and the computer lets > # the player know if the guess is too high, too low > # or right on the money > > import random > > print "\tWelcome to 'Guess My Number'!" > print "\nI'm thinking of a number between 1 and 100." > print "Try to guess it in as few attempts as possible.\n" > > # set the initial values > > > > def ask_number(): > the_number = random.randrange(100) + 1 > guess = int(raw_input("Take a guess: ")) > tries = 1 > > > > > while (guess != the_number): > > > if (guess > the_number): > print "Lower..." > > else: > print "Higher..." > tries += 1 ^-- *not needed* > > > guess = int(raw_input("Take a guess: ")) > tries += 1 > > > > > ask_number() > > > > > print "You guessed it! The number was", the_number > print "And it only took you", tries, "tries!\n" > > raw_input("\n\nPress the enter key to exit.") > > > ------------------------------------------------------------------------ ~Ethan~ From tdelaney at avaya.com Thu Aug 7 19:20:45 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 8 Aug 2008 07:20:45 +0800 Subject: Psycho question In-Reply-To: Message-ID: David C. Ullrich wrote: > f: 0.0158488750458 > g: 0.000610113143921 > h: 0.00200295448303 > f: 0.0184948444366 > g: 0.000257015228271 > h: 0.00116610527039 I suspect you're hitting the point of diminishing returns with g, and any further investigations into optimisation are purely for fun and learning ;) Tim Delaney From ktenney at gmail.com Fri Aug 8 17:21:40 2008 From: ktenney at gmail.com (Kent Tenney) Date: Fri, 8 Aug 2008 21:21:40 +0000 (UTC) Subject: sending to an xterm References: <20080808205821.GJ23567@dragontoe.org> Message-ID: Derek Martin pizzashack.org> writes: > > On Fri, Aug 08, 2008 at 08:25:19PM +0000, Kent Tenney wrote: > > Howdy, > > > > I want to open an xterm, send it a command and have it execute it. > > You can't do that. xterm doesn't execute shell commands passed on > stdin... It can, however, execute one passed on the command line. > > Instead of just running xterm, you can run "xterm -e 'cmd foo bar'" > where cmd is the program to run and foo and bar are its arguments. > The problem is that as soon as the program exits, xterm will exit > also. > Sorry to reply before getting googly This appears to be a solution; xterm -e "ls; bash" http://www.linuxforums.org/forum/misc/115239-getting-prompt-after-xterm-e-command.html From notvalid2 at sbcglobal.net Thu Aug 28 18:05:51 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Thu, 28 Aug 2008 15:05:51 -0700 Subject: Python in a Nutshell -- Book vs Web Message-ID: I read an Amazon of Python in a Nutshell. The first edition is supposedly much like the web site. What web site? The second edition apparently adds more to the book than the web site. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From apardon at forel.vub.ac.be Mon Aug 4 04:56:52 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Aug 2008 08:56:52 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> <5a0b303a-8324-4eeb-a975-397371bf2875@b1g2000hsg.googlegroups.com> Message-ID: On 2008-08-01, Terry Reedy wrote: >> Nevertheless, I think this is probably the best example of the >> enhanced polymorphism of "if x" yet. I'm kind of surprised no one >> came up with it.) > > I think of Python code as 'generic' rather than 'polymorphic'. I am not > sure if that is a real difference or not, since I am a bit fuzzy on the > meaning of 'polymorphic' in this context. > > The generality of 'if x:' depends on the context. If x is defined as a > number by doc or previous code (or possibly even by subsequent code), > then 'if x:' is equivalent to 'if x != 0:'. At this point, it is a > stylistic argument which to use. > > But here is an example where 'if x:' is more generic. > > def solve(a,b): > 'a and b such that b/a exists' > if a: > return a/b > else: > raise ValueError('a not invertible, cannot solve' > > Now suppose we have a matrix class (2x2 for simplicity and realism). > Its __bool__ (3.0) method implements 'is non-singular'. As written > above, solve(mat,vec) works (with compatible mat and vec sizes), but it > would not with 'if a != 0:'. > > Of course, the issue goes away by not looking before the leap: > > def solve(a,b): > return a/b > # let callers deal with exceptions > or > try: > return a/b > except... > # raise customized error Maybe I'm going to be pedantic here, but I fear that your code won't work with matrices. The problem is that multiplication is not commutative with matrices. This means that matrices have two divisions a right and a left division. A far as I know the "/" operator usaly implements the left division while solving is done by using a right division. So your code will probably fail when applied to matrices. -- Antoon Pardon From steve at REMOVE-THIS-cybersource.com.au Sat Aug 23 04:16:59 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 23 Aug 2008 08:16:59 GMT Subject: setattr and getattr, when to use? References: <920d6a60-580d-4b89-8dfd-cd44b05676ae@25g2000hsx.googlegroups.com> Message-ID: <00bfc23f$0$20312$c3e8da3@news.astraweb.com> On Fri, 22 Aug 2008 20:50:17 -0700, maestro wrote: > Why are these functions there? Is it somehow more idiomatic to use than > to do obj.field ? Heavens no!!! Using setattr and getattr is *less* idiomatic. > Is there something you can with them that you can't by obj.field > reference? Absolutely. Consider: class Foo(object): pass foo = Foo() setattr(foo, "x y", 1) print getattr(foo, "x y") That's probably an abuse of setattr/getattr, but there are times where you might not know the name of the attribute until runtime, so you can't write foo.attr since you don't know what to write in place of attr. That's where setattr and getattr (as well as delattr and hasattr) come into play. -- Steven From fredrik at pythonware.com Sat Aug 30 08:20:47 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 30 Aug 2008 14:20:47 +0200 Subject: Advice on the style to use in imports In-Reply-To: <3f0d61c40808300512x1dcd5061t19ad7323b7ef15e9@mail.gmail.com> References: <3f0d61c40808300512x1dcd5061t19ad7323b7ef15e9@mail.gmail.com> Message-ID: Marco Bizzarri wrote: > I'm showing what I used in my current project, and will accept your > advices on how I should change them. > > The style is consistently the following: > > from package.subpackge.module import MyClass > > Is this an accepted way to write imports? According to what I > understood in articles, I don't think so. importing objects instead of the module (namespace) they live in can cause all sorts of aliasing and dependency issues. avoid unless you know exactly what you're doing. From steve at REMOVE-THIS-cybersource.com.au Sat Aug 9 00:22:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Aug 2008 04:22:02 GMT Subject: internet searching program References: <304d52cb-a8a8-46d5-81be-4eb01c73d479@26g2000hsk.googlegroups.com> Message-ID: <00ad1698$0$20318$c3e8da3@news.astraweb.com> On Fri, 08 Aug 2008 19:59:02 -0700, KillSwitch wrote: > Is it possible to make a program to search a site on the internet, then > get certain information from the web pages that match and display them? > Like, you would put in keywords to be searched for on youtube.com, then > it would search youtube.com, get the names of the videos, the links, and > the embed information? Or something like that. Search the Internet? Hmmm... I'm not sure, but I think Google does something quite like that, but I don't know if they do it with a computer program or an army of trained monkeys. -- Steven From paul.nospam at rudin.co.uk Sun Aug 24 13:21:55 2008 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Sun, 24 Aug 2008 18:21:55 +0100 Subject: Date Comparison and Manipulation Functions? References: Message-ID: <874p5apbv0.fsf@rudin.co.uk> "W. eWatson" writes: > Are there some date and time comparison functions that would compare, say, > > Is 10/05/05 later than 09/22/02? (or 02/09/22 format, yy/mm/dd) > Is 02/11/07 the same as 02/11/07? > > Is 14:05:18 after 22:02:51? (24 hour day is fine) > > How about the date after 02/28/04 is 02/29/04, or the date after > 09/30/08 is 10/01/08? > > How about is 03/03/04 20:10:08 after 03/07/03 14:00:00? Probably the > others above will suffice. http://docs.python.org/lib/module-datetime.html From gordyt at gmail.com Wed Aug 13 12:22:22 2008 From: gordyt at gmail.com (gordyt) Date: Wed, 13 Aug 2008 09:22:22 -0700 (PDT) Subject: datetime from uuid1 timestamp References: Message-ID: Howdy Kent, Interesting question! Give this a shot: import datetime import time import uuid # get offset in seconds between the UUID timestamp Epoch (1582-10-15) and # the Epoch used on this computer DTD_SECS_DELTA = (datetime.datetime(*time.gmtime(0)[0:3])- datetime.datetime(1582, 10, 15)).days * 86400 def uuid1_to_ts(u): """Return a datetime.datetime object that represents the timestamp portion of a uuid1. Parameters: u -- a type 1 uuid.UUID value Example usage: print uuid1_to_ts(uuid.uuid1()) """ secs_uuid1 = u.time / 1e7 secs_epoch = secs_uuid1 - DTD_SECS_DELTA return datetime.datetime.fromtimestamp(secs_epoch) --gordon From frankrentef at yahoo.com Thu Aug 7 14:56:53 2008 From: frankrentef at yahoo.com (frankrentef) Date: Thu, 7 Aug 2008 11:56:53 -0700 (PDT) Subject: Create a short way to save typing script over and over.... Message-ID: I have a statement "url = 'http://xyzserver/'" so in my code every time I need to use xyzserver I state "url +...." What I' m now trying to do is create a call to a login process. The script for the login process is below. I'd like to call "adminlogin" and not have to keep entering the same several lines of script each and everytime (I'm testing various login functions and rule changes.) I'm a newbie, can someone walk me through this? THNX #Login to ISeDeposit Admin ie.navigate (url + 'isweb/admin/default.aspx') ie.textBoxSet ('AdminLogin1:Username','Admin') ie.textBoxSet ('AdminLogin1:inputPassword','Password') ie.buttonClick ('AdminLogin1:btnLogin') From circularfunc at gmail.com Sun Aug 31 22:43:01 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 31 Aug 2008 19:43:01 -0700 (PDT) Subject: Some problems with classes References: Message-ID: <336b0d9e-2af8-45c1-b5b7-adb508fe7853@t54g2000hsg.googlegroups.com> class Animal(object): def __init__(self, name, weight): self.name = name self.weight = weight def speak(self): print "speak" class Vegetable(object): def __init__(self, name, volume): self.name = name self.volume = volume def split(self): print "tjoff" class Vegan(Animal, Vegetable): def __init__(self, name, attacks): self.name = name self.attacks = attacks From stefan_ml at behnel.de Tue Aug 26 02:28:20 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 26 Aug 2008 08:28:20 +0200 Subject: python xslt library In-Reply-To: References: Message-ID: <48B3A284.3040606@behnel.de> Owen Zhang wrote: > Can anyone recommand the best performance python xslt library? lxml. It's based on libxml2/libxslt. http://codespeak.net/lxml Stefan From gminick at nie.ma.takiego.adresu.w.sieci.pl Tue Aug 12 10:54:10 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Tue, 12 Aug 2008 14:54:10 +0000 (UTC) Subject: trying to use SOCK_RAW yields error " References: <3b701b38-9dd3-48f6-bdb0-c04fc9085008@x41g2000hsb.googlegroups.com> Message-ID: Dnia Tue, 12 Aug 2008 07:21:15 -0700 (PDT), Tzury Bar Yochay napisa?(a): > I changed as instructed: > server = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, > socket.getprotobyname('ip')) > > now I am getting: > > Traceback (most recent call last): > File "tcpsrv.py", line 15, in > server.bind((host,port)) > File "", line 1, in bind > socket.error: (19, 'No such device') What's the value of host variable? AFAIR it should be the name of the interface you want to bind to ('eth0', 'ppp0', whatever). -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From sjmachin at lexicon.net Mon Aug 4 05:34:43 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 4 Aug 2008 02:34:43 -0700 (PDT) Subject: Trying to fix Invalid CSV File References: <0427191c-d493-442d-ba26-94802bc6062b@v13g2000pro.googlegroups.com> <078f7aad-3bba-49b4-8978-18ac5bfaa6f7@r15g2000prd.googlegroups.com> <6bade254-5001-4ae2-a000-003b84437a76@w1g2000prk.googlegroups.com> Message-ID: On Aug 4, 6:15 pm, Ryan Rosario wrote: > On Aug 4, 1:01 am, John Machin wrote: > > > On Aug 4, 5:49 pm, Ryan Rosario wrote: > > > > Thanks Emile! Works almost perfectly, but is there some way I can > > > adapt this to quote fields that contain a comma in them? > > > You originally said "I have a very large CSV file that contains double > > quoted fields (since they contain commas)". Are you now saying that > > if a field contained a comma, you didn't wrap the field in quotes? Or > > is this a separate question unrelated to your original problem? > > I enclosed all text fields within quotes. The problem is that I have > quotes embedded inside those text fields as well and I did not double/ > escape them. Emile's snippet takes care of the escaping but it strips > the outer quotes from the text fields and if there are commas inside > the text field, the field is split into multiple fields. Of course, it > is possible that I am not using the snippet correctly I suppose. Without you actually showing how you are using it, I can only surmise: Emile's snippet is pushing it through the csv reading process, to demonstrate that his series of replaces works (on your *sole* example, at least). Note carefully his output for one line is a *list* of fields. The repr() of that list looks superficially like a line of csv input. It looks like you are csv-reading it a second time, using quotechar="'", after stripping off the enclosing []. If this guess is not correct, please show what you are actually doing. If (as you said) you require a fixed csv file, you need to read the bad file line by line, use Emile's chain of replaces, and write each fixed line out to the new file. From bearophileHUGS at lycos.com Sun Aug 17 18:24:06 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 17 Aug 2008 15:24:06 -0700 (PDT) Subject: like a "for loop" for a string References: <6bc8134c-fd89-4a98-8a99-813f41b26813@k30g2000hse.googlegroups.com> <58d6c42e-dbce-40f9-a962-e8543ba6f93e@v57g2000hse.googlegroups.com> <37e349e2-5089-4574-a7c3-19fef812bc70@l42g2000hsc.googlegroups.com> Message-ID: <1a8819f7-3eb4-41bd-bc9e-ae2aa03f0139@s50g2000hsb.googlegroups.com> MRAB: > If it was introduced into Python v3.x then wouldn't it have to be > called str.split in order to be consistent with xrange -> range? :-) xsplit may be a name fit for Python 2.6/2.7. Regarding Python 3.0 you may be right, but then when you want the list of parts you have to do: list(somestring.split()) While to count the number of parts on Python 3.0 this may suffice: sum(1 for part in somestring.split()) Unless you use a leniter() function that counts the lazy iterations (its functionality can be folded inside the len() too, like in some lazy languages). Most of the times I think a lazy splitting may suffice, so in Python 3.0 the eager version may be absent :-) Bye, bearophile From george.sakkis at gmail.com Mon Aug 11 16:11:42 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 11 Aug 2008 13:11:42 -0700 (PDT) Subject: ANN: papyros 0.2 Message-ID: I am pleased to announce papyros-0.2, the second alpha release of papyros: http://code.google.com/p/papyros/. Compared to the initial release 14 months ago, only the basic goal has remained the same; both the API and the internals have been thoroughly revamped. Some of the highlights are: - As simple as it gets: for most purposes, the API is reduced to a single method ("dispatcher.execute(tasks)"). - Easier task definition. - (Optional) ordered task execution and chunksize (inspired from pyprocessing). - A distributed group can now handle concurrently more than one independent task sequences: enables serving multiple clients. - Several bug fixes and performance improvements. About ----- Papyros is a small platform independent package for parallel processing. Currently two main implementations are provided for the same API: one using multiple threads and the other multiple processes on one or more hosts through Pyro (http://pyro.sourceforge.net/). From asmodai at in-nomine.org Wed Aug 13 07:51:50 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 13 Aug 2008 13:51:50 +0200 Subject: You advice please In-Reply-To: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> Message-ID: <20080813115150.GE87062@nexus.in-nomine.org> -On [20080813 13:16], Hussein B (hubaghdadi at gmail.com) wrote: >My friends are about to open a Ruby/Rails shop and they are asking me >to join them. I hope they are fully aware of the scaling problems RoR can have. >Why Python isn't getting this attention although is a much more mature >language and it is used by many big, big names? At least in my experience Python is getting more and more exposure. More job openings as well. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B A liar needs a good memory... From steve at REMOVE-THIS-cybersource.com.au Mon Aug 11 12:33:42 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2008 16:33:42 GMT Subject: eval or execute, is this the (most) correct way ? References: Message-ID: <00b06501$0$14351$c3e8da3@news.astraweb.com> On Mon, 11 Aug 2008 17:26:56 +0200, Stef Mientki wrote: > I'm trying to make an editor with an integrated Shell. ... > Is this the (most) correct / elegant way, or are there better solutions > ? The best solution is not to re-invent the wheel: "import code" is the way to emulate Python's interactive interpreter. Try running "python -m code" at a regular shell (not the Python shell, your operating system's shell). Doing a search of the file code.py, I don't find the string "eval" at all. My guess is that your approach is probably not the best way. -- Steven From cwitts at gmail.com Fri Aug 22 08:56:42 2008 From: cwitts at gmail.com (Chris) Date: Fri, 22 Aug 2008 05:56:42 -0700 (PDT) Subject: need help using enumerate ?? References: <3592f6a7-177f-4d1c-beed-69b72a0c2e43@i20g2000prf.googlegroups.com> Message-ID: On Aug 22, 1:14 pm, "Eric_Dex... at msn.com" wrote: > I am trying to take some data in file that looks like this > > command colnum_1 columnum_2 > > and look for the command and then cange the value in the collum(word) > number indicated. I am under > the impression I need enumerate but I am not sure what to do with it > any help would be nice. > > import sys > > parse1filerows = [] > csoundrows = [] > > filename = sys.argv[0] > number = sys.argv[1] > outfile = open('test.sco','w') > > infile = open(filename, 'r') > for line in infile: > csoundrows.append(line.split()) > parsefile = open('parsefile1.txt', 'r') > for line in parsefile: > parsefile1rows.append(line.split()) > for row in csoundrows: > for prow in parsefile1rows: > test = 0 > if parsefile1[prow][0] in csoundrow[row]: > for pcol in parsefile1[prow]: > if test == 1: > csoundrows[row][int(pcol)] = str(int(csoundrows[row] > [int(pcol)] + number) > for row in csoundrows: > for word in rows: > outfile.write(row) Rather confusing code there and non-functional. You never close your file handles, when finished with a file use the .close() method sys.argv[0] <-- the first element is the name of your .py file and not the first argument you supply. When iterating over a list like csoundrows you don't need to do for row in csoundrows: if ... in csoundrow[row]: # This will try to use 'row' as an index but rather if ... in row: Now, this is how I intepretted your question. from sys import argv, exit if len(argv) != 3: """Ensure the correct number of arguments are supplied""" exit('Incorrect number of arguments.') try: """Checks if the Input file exists and exits if open fails.""" inFile = open(argv[1], 'rb') except IOError: exit('Input file does not exist.') if not argv[2].isdigit(): """Argument #2 needs to be a number""" exit('Column number is not numerical.') idx = int(argv[2]) outFile = open('test.sco', 'wb') """Assuming your data in the parse file was a set of key, value pairs to be used for replacement in the input file. Just splitting on the basic space and assigning the first element as the key and the rest of the string as the value to be used for replacement. """ replaceData = {} for line in open('replacementInstructions.txt', 'rb'): key = line.strip().split(' ')[0] value = line.strip().split(' ')[1:] replaceData[key] = value """Iterate over your input file, split the line into it's component parts and then lookup if the first element 'command' is contained in the replacement data and if so change the data. If you want all input to be saved into your output file, just dedent the 'outFile.write' line by one level and then all data will be saved. """ for line in inFile: record = line.strip().split(' ') if record[0] in parseRows: record[idx] = parseRows[record[0]] outFile.write('%s\n' % ' '.join(record) ) inFile.close() outFile.close() From fetchinson at googlemail.com Thu Aug 14 23:38:05 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 14 Aug 2008 20:38:05 -0700 Subject: =?ISO-8859-1?Q?Re:_Don=B4t_find_HTMLgen?= In-Reply-To: <121682ff-1bfe-44db-a038-e764f26f012f@d77g2000hsb.googlegroups.com> References: <121682ff-1bfe-44db-a038-e764f26f012f@d77g2000hsb.googlegroups.com> Message-ID: > Good day Mr. Guido, excuse my poor english. > > I am looking for HTMLgen module but not to find this, the link > referenced in www.python.org it does not exist. > > I have need to develop in cgi and would want to do it of the possible > traditional form but, i like any module for my help. Since gentoo and debian (I think) were packaging it you can get it from their package repositories. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From ironfroggy at gmail.com Tue Aug 12 02:59:36 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Tue, 12 Aug 2008 02:59:36 -0400 Subject: How to iterate a sequence, with skipping the first item? In-Reply-To: References: Message-ID: <76fd5acf0808112359y4708c85ej38b74a413bf867bd@mail.gmail.com> i = iter(container.iterChildren()) i.next() for x in i: ... On Tue, Aug 12, 2008 at 2:51 AM, ray wrote: > A container object provides a method that returns an iterator object. > I need to iterate the sequence with that iterator, but need to skip > the first item. I can only iterate the whole sequence with: > for x in container.iterChildren(): > How to skip the first item? It seems that it's a simple question. > Could somebody help me? Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From raashid_hbk at yahoo.com Sun Aug 17 14:35:14 2008 From: raashid_hbk at yahoo.com (raashid bhatt) Date: Sun, 17 Aug 2008 11:35:14 -0700 (PDT) Subject: how to call API Functions in python References: <46c57206-49a8-48b1-966f-2beab4ac433e@w24g2000prd.googlegroups.com> <51d09a98-685f-4fbd-86df-c3eca9d5e309@o40g2000prn.googlegroups.com> Message-ID: On Aug 17, 11:27?am, Wojtek Walczak wrote: > On Sun, 17 Aug 2008 11:22:52 -0700 (PDT), raashid bhatt wrote: > >> > how to call API Functions in python > > >> The same way as you'd call any other function, of course. ?What API are > >> you referring to? > > i am talking about WINAPI > > I am not a Windows guy, but maybe ctypes module will be helpful > for you. > > -- > Regards, > Wojtek Walczak,http://www.stud.umk.pl/~wojtekwa/ Thanks a lot man That is what i wanted to know From gminick at bzt.bzt Mon Aug 25 09:36:40 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Mon, 25 Aug 2008 13:36:40 +0000 (UTC) Subject: passing arguments to exec References: <53975d0c-7a7d-47c3-9cd7-64f80672bb50@j1g2000prb.googlegroups.com> Message-ID: On Mon, 25 Aug 2008 06:31:53 -0700 (PDT), Alexandru Mosoi wrote: > i want to execute a python script using exec open('script.py'). how do > I pass arguments? Take a look at subprocess module. It comes with a set of examples. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From Ross at no.thanks.spammers Wed Aug 27 16:21:03 2008 From: Ross at no.thanks.spammers (RgeeK) Date: Wed, 27 Aug 2008 16:21:03 -0400 Subject: Global var access in imported modules? Message-ID: <48b5b72f$1@news.alcatel.com> I have a main module doStuff.py and another module utility.py. At the start of doStuff.py I call import utility.py Then I also proceed to initiallize some global variables sName = "" Then I create a class, some methods etc. In one of the methods I assign a value to my variable sName. Then I call a function from within my utility.py file: utility.makeOne(stuff) Within my utility.py file, I define the makeOne function. But I want to use that same global variable "sName" In utility.py I have tried to indicate that I'm using the global "sName" through the statement: global sName But when I go to use the variable it still gives me an error: NameError: global name 'sName' is not defined I thought perhaps I need to indicate 'globality' in my main module, so before I initiallized sName in doStuff.py I added: global sName But it doesn't help me. I had this issue before and resolved it by declaring the variable global in the sub-module utility.py, but then I needed to reference it in my main module with a prefix: utility.sName = "" It's more verbose,and defining globals in a submodule seems backward. But also, what if I need to access "sName" in another imported module, say "otherstuff.py"? I would do my "import otherstuff" call in my main module, but would I have to put an "import utility" into the otherstuff.py file? Is there some way I can define globals in my main module, and have them accessible in all my imported submodule? As you can see I'm a little unsure about the global handling in a multi-module environment. Any suggestions appreciated. I've read http://docs.python.org/ref/naming.html but it hasn't enlightened me on this one. From mensanator at aol.com Sat Aug 9 23:28:44 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 9 Aug 2008 20:28:44 -0700 (PDT) Subject: The wrong approach to things References: <0c435465-b769-45b9-8c6e-57d57abc5c31@j33g2000pri.googlegroups.com> Message-ID: On Aug 9, 9:20?pm, teh_sAbEr wrote: > Ok, so this isn't necessarily a programming issue, but anyways. I've > managed to write that random wallpaper changer i've been wanting to > make, but i've run into a little problem. According to the MS > Knowledge Base, SystemParametersInfo() can't take a .jpg file as an > argument when changing the wallpaper (it doesn't work, i've tried it), > only .bmps so i'm stuck converting one of my many wallpapers from .jpg > to .bmp, passing that to SystemParametersInfo(), and deleting the > previous .bmp so that i don't have any duplicates. The problem with > this is that other members of my family use this computer too, and > they sometimes set the desktop wallpaper to some other, usually funny > picture they've got stored on the HD, and when I run this little > script it'll delete whatever the current wallpaper is, regardless of > whether its one of mine or not. Any suggestions on how to work around > this problem? Why not rename the file instead of deleting it? > > #random wallpaper changer! > import win32gui #use this to change the wallpaper. > import os > import os.path > import random > import Image > SPI_SETDESKWALLPAPER = 20 ?#It took me WAY too long to find them. > SPI_GETDESKWALLPAPER = 115 #I should keep these handy. > > def RandomlySelectWallpaper(filePaths): > ? ? CurrentWallpaper = > win32gui.SystemParametersInfo(SPI_GETDESKWALLPAPER) > ? ? while True: > ? ? ? ? index = random.randint(0,len(filePaths)-1) > ? ? ? ? RandomlySelectedWallpaper = filePaths[index] > ? ? ? ? if RandomlySelectedWallpaper <> CurrentWallpaper: > ? ? ? ? ? ? break > ? ? print RandomlySelectedWallpaper > ? ? return RandomlySelectedWallpaper #it should be a string... > > def ChangeDesktopWallpaper(RandomlySelectedWallpaper): > ? ? #so the RIGHT way to do this would be to use > ? ? #win32gui.SystemParametersInfo() to change the wallpaper. > ? ? #1) we convert the image to .bmp. > ? ? #Delete the old wallpaper, actual delete occurs after new > wallpaper has been set. > ? ? pathToCurrentWall = > win32gui.SystemParametersInfo(SPI_GETDESKWALLPAPER) > ? ? root,extension = os.path.splitext(RandomlySelectedWallpaper) > ? ? newFileName = root + '.bmp' > ? ? print "Wallpaper to delete: ", pathToCurrentWall > ? ? try: > ? ? ? ? #every so often something goes wrong at this stage in the > script > ? ? ? ? #and I can't figure out what. Something raises an IOError. > ? ? ? ? Image.open(RandomlySelectedWallpaper).save(newFileName) > ? ? ? ? print "File saved!" > ? ? except IOError: > ? ? ? ? print "Error while converting, please check filepath and > permissions." > ? ? ? ? print "Program will restart in an attempt to generate a > correct wallpaper." > ? ? ? ? Main() > ? ? win32gui.SystemParametersInfo(SPI_SETDESKWALLPAPER,newFileName, > 1+2) > ? ? print "Removing: ", pathToCurrentWall > ? ? os.remove(pathToCurrentWall) > > def Main(): > ? ? #woot. > ? ? listOfWallpaperPaths = GenerateListOfWallpapers() > ? ? RandomlySelectedWall = > RandomlySelectWallpaper(listOfWallpaperPaths) > ? ? ChangeDesktopWallpaper(RandomlySelectedWall) > > Main() From ggpolo at gmail.com Thu Aug 28 17:04:25 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 28 Aug 2008 18:04:25 -0300 Subject: Negative regular expressions (searching for "i" not inside command) In-Reply-To: References: Message-ID: On Thu, Aug 28, 2008 at 5:04 PM, Bart Kastermans wrote: > I have a file in which I am searching for the letter "i" (actually > a bit more general than that, arbitrary regular expressions could > occur) as long as it does not occur inside an expression that matches > \\.+?\b (something started by a backslash and including the word that > follows). > > More concrete example, I have the string "\sin(i)" and I want to match > the argument, but not the i in \sin. > > Can this be achieved by combining the regular expressions? I do not > know the right terminology involved, therefore my searching on the > Internet has not led to any results. Try searching again with the "lookahead" term, or "negative lookahead". > > I can achieve something like this by searching for all i and then > throwing away those i that are inside such expressions. I am now just > wondering if these two steps can be combined into one. > > Best, > Bart > -- > http://www.bartk.nl/ > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From vijayakumar.subburaj at gmail.com Tue Aug 5 08:58:37 2008 From: vijayakumar.subburaj at gmail.com (v4vijayakumar) Date: Tue, 5 Aug 2008 05:58:37 -0700 (PDT) Subject: More Datastore Examples Please Message-ID: Google appengine datastore is not very clear, and I couldn't get much from API documents. It would be very helpful if there are some more detailed documents with examples. Django provides very good documentation, but I don't know how much it is compatible with google appengine. Google appengine examples are not using datastore extensively, so this is also not helping much in modeling datastore. wiki.py is using low level APIs, this looks simple but couldn't find any documentation for this. Web search is also not giving anything useful. Can anyone please provide me some URLs where I can find some datastore examples, articles, etc. Thanks in advance. -- posted the same on google-appengine group. cross posting here. http://groups.google.com/group/google-appengine/browse_thread/thread/ae9ba26893c2854d From rstarkov at gmail.com Sat Aug 23 08:05:02 2008 From: rstarkov at gmail.com (rs387) Date: Sat, 23 Aug 2008 05:05:02 -0700 (PDT) Subject: Odd behaviour on importing variable from module Message-ID: <1af3c163-0563-4528-8f63-1ddeff9d19bd@56g2000hsm.googlegroups.com> Hi, I've found the following behaviour on importing a variable from a module somewhat odd. The behaviour is identical in Python 2.5 and 3.0b2. In summary, here's what happens. I have a module, oddmodule.py (below), that defines a variable, OddVariable, by assigning a value A to it. The file I execute, mainfile.py, imports and re-binds OddVariable to a value B. I have two test modules which import the OddVariable in two different ways, one via "import oddmodule" and another via "from oddmodule import OddVariable". The weird behaviour is that by importing using the former syntax, I can see OddVariable bound to B (as expected), but the latter syntax sees it bound A. Is this the intended behaviour? Am I misunderstanding what is going on here? Source code: <<>> print("Importing oddmodule") OddVariable = ["not", "initialized"] def OddFunction(): print(" OddVariable from oddmodule.OddFunction:", OddVariable) <<>> import oddmodule import testmodule1 import testmodule2 print("Initializing OddVariable") oddmodule.OddVariable = ["some", "list"] print() testmodule2.DoTest() print() testmodule1.DoTest() <<>> from oddmodule import OddVariable, OddFunction def DoTest(): print("STARTING testmodule1.DoTest") print(" OddVariable from testmodule1:", OddVariable) OddFunction() print("FINISHED testmodule1.DoTest") <<>> import oddmodule def DoTest(): print("STARTING testmodule2.DoTest") print(" OddVariable from testmodule2:", oddmodule.OddVariable) oddmodule.OddFunction() print("FINISHED testmodule2.DoTest") OUTPUT: Importing oddmodule Initializing OddVariable STARTING testmodule2.DoTest OddVariable from testmodule2: ['some', 'list'] OddVariable from oddmodule.OddFunction: ['some', 'list'] FINISHED testmodule2.DoTest STARTING testmodule1.DoTest OddVariable from testmodule1: ['not', 'initialized'] !!! OLD VALUE !!! OddVariable from oddmodule.OddFunction: ['some', 'list'] FINISHED testmodule1.DoTest Many thanks, Roman From casey.mcginty at gmail.com Wed Aug 27 04:21:37 2008 From: casey.mcginty at gmail.com (Casey) Date: Wed, 27 Aug 2008 01:21:37 -0700 (PDT) Subject: Usual practice: running/testing modules in a package References: <827c7ee5-fad1-4a8c-8724-d6504c91be6d@w1g2000prk.googlegroups.com> Message-ID: <63d32551-7d94-4ab9-9c06-2bd2c8b8e0b8@a3g2000prm.googlegroups.com> On Aug 12, 9:57?pm, alito wrote: > > A wrapper on the level up works: > > ~/python$ cat importercaller.py > from testpackage import config > config.hello() > > ~/python$ python importercaller.py > hello > > So, how do I run these modules without writing a wrapper script for > each one? I just ran into this problem trying to run a package from a local directory. I agree creating another script just to import the local package is a bad solution. Without another option, I would recommend using a Makefile and creating a target to import the package and kickoff the execution: hello: python -c 'from testpackage import config; config.hello()' and then "make hello" to execute the command. From brtzsnr at gmail.com Wed Aug 27 07:58:09 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Wed, 27 Aug 2008 04:58:09 -0700 (PDT) Subject: use of Queue References: <39824ccb-7e35-4ef4-a150-692af64c0ba5@j1g2000prb.googlegroups.com> <7a862160-e64f-4563-8834-50b0ff6087a1@d45g2000hsc.googlegroups.com> Message-ID: On Aug 27, 2:54?pm, Jeff wrote: > Queue raises an Empty exception when there are no items left in the > queue. ?Put the q.get() call in a try block and exit in the except > block. Wrong. What if producer takes a long time to produce an item? Consumers will find the queue empty and exit instead of waiting. > You can also use a condition variable to signal threads to terminate. This is the solution I want to avoid because it duplicates Queue's functionality. I prefer having a clean solution with nice design to hacking Queue class. From ndbecker2 at gmail.com Fri Aug 8 09:50:42 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 08 Aug 2008 09:50:42 -0400 Subject: bbfreeze problem Message-ID: Any ideas on this? bb-freeze test5-coded-pre.py WARNING: found xml.sax in multiple directories. Assuming it's a namespace package. (found in /usr/lib64/python2.5/site-packages/_xmlplus/sax, /usr/lib64/python2.5/xml/sax) *** applied recipe_matplotlib: using the backend_qt4agg matplotlib backend *** applied *** applied *** applied *** applied SKIPPING: SharedLibrary('libgthread-2.0.so.0',) SKIPPING: SharedLibrary('libglib-2.0.so.0',) *** applied *** applied ================================================== The following eggs are being used: Numeric 24.2 (/usr/lib64/python2.5/site-packages/Numeric) configobj 4.5.2 (/usr/lib/python2.5/site-packages/configobj-4.5.2-py2.5.egg) matplotlib 0.91.2 (/usr/lib/python2.5/site-packages/matplotlib-0.91.2-py2.5- linux-x86_64.egg) setuptools 0.6c8 (/usr/lib/python2.5/site-packages/setuptools-0.6c8-py2.5.egg) ================================================== /usr/lib64/python2.5/site-packages/Numeric looks like a development egg. need to run setup.py bdist_egg Traceback (most recent call last): File "/usr/bin/bb-freeze", line 8, in load_entry_point('bbfreeze==0.96.2', 'console_scripts', 'bb-freeze')() File "/usr/lib/python2.5/site-packages/bbfreeze-0.96.2-py2.5-linux- x86_64.egg/bbfreeze/__init__.py", line 18, in main f() File "/usr/lib/python2.5/site-packages/bbfreeze-0.96.2-py2.5-linux- x86_64.egg/bbfreeze/freezer.py", line 516, in __call__ analyzer.copy(self.distdir) File "/usr/lib/python2.5/site-packages/bbfreeze-0.96.2-py2.5-linux- x86_64.egg/bbfreeze/freezer.py", line 138, in copy eggutil.copyDistribution(x, destdir) File "/usr/lib/python2.5/site-packages/bbfreeze-0.96.2-py2.5-linux- x86_64.egg/bbfreeze/eggutil.py", line 132, in copyDistribution raise RuntimeError("setup.py not found for development egg") RuntimeError: setup.py not found for development egg I don't think I'm using matplotlib, don't understand what dragged it in (python -v on my script does _not_ show any matplotlib) From sharon.kim96 at gmail.com Mon Aug 25 12:00:08 2008 From: sharon.kim96 at gmail.com (sharon k) Date: Tue, 26 Aug 2008 00:00:08 +0800 Subject: newbie question In-Reply-To: <00783B36-B09D-40EA-9543-18911CA24C11@uos.de> References: <00783B36-B09D-40EA-9543-18911CA24C11@uos.de> Message-ID: much thanks, your instructions are clear, problem solved! :) On Mon, Aug 25, 2008 at 11:43 PM, Manuel Ebert wrote: > Hi sharon, > > the problem is here that > a = 12,123 > will actually create a tuple with two elements (namely 12 and 123): > >> a = 12,123 > >> a > (12, 123) > > Converting this to a string yields '(12, 123)', which is not what you want > (sounds confusing, bit soon you'll see how many amazing things can be done > like this :-) > > Try: > >> a = "12,123" > >> a = int(a.replace(',', '')) > > I don't know the urllib, but I suppose if you use it to fetch content from > a web page it will return strings anyway. > > > On Aug 25, 2008, at 5:14 PM, sharon k wrote: > > >> >> thank you for your prompt reply. >> >> sorry seems i run into another problem, as follow; >> >> >>> a = 12,123 >> >>> b = str(a) >> >>> c = int(b.replace(',', '')) >> Traceback (most recent call last): >> File "", line 1, in >> ValueError: invalid literal for int() with base 10: '(12 123)' >> >> the comma has become an empty space, it cannot be converted to an integer. >> i try the above in a winxp python command line. >> >> >> On Mon, Aug 25, 2008 at 10:48 PM, Gerhard H?ring wrote: >> sharon k wrote: >> hi all, >> >> i am new to python. >> > >> i fetch a webpage with urllib, extract a few numbers in a format as >> follow; >> >> 10,884 >> 24,068 >> >> my question is how to remove the comma between the number, since i have to >> add them up later. >> >> Strings have a replace method. Calling replace(",", "") on the string will >> do the trick here. >> >> -- Gerhard >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Sun Aug 24 02:59:55 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 24 Aug 2008 08:59:55 +0200 Subject: Imports awareness in Imported modules problem In-Reply-To: <538050a90808231529s61855330r1ec68048847ef241@mail.gmail.com> References: <538050a90808231529s61855330r1ec68048847ef241@mail.gmail.com> Message-ID: Mohamed Yousef wrote: > why am i doing this in the first place > I'm in the process of a medium project where imports of modules start > to make a jungle and i wanted all needed imports to be in a single > file (namely __init__.py) > and then all imports are made once and other modules feel it Python doesn't use a global namespace -- importing a given module into one module doesn't make it visible everywhere else (and trust me, this is a very good thing). (it uses a global module cache, though, so it's only the first import that actually loads the module) > my goal is basically making W() aware of the re module when called > from A to do that, add "import re" to the top of the C module. see this page for a little more on Python's import mechanism: http://effbot.org/zone/import-confusion.htm From paul at boddie.org.uk Wed Aug 13 12:20:00 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 13 Aug 2008 09:20:00 -0700 (PDT) Subject: xcompile patch for python 2.5.2? References: Message-ID: <17d846b0-14fd-4eb6-b0eb-b940b1033a7e@k7g2000hsd.googlegroups.com> On 12 Aug, 19:30, "Stephen Cattaneo" wrote: > > A friend of mine is attempting to cross compile python 2.5.2 onto a > MIPS64 box. He is asking if there is a cross compile patch for 2.5.2. > Do any of you know where He might find such a thing? Try here: http://bugs.python.org/issue1597850 http://bugs.python.org/issue1006238 http://bugs.python.org/issue848910 http://bugs.python.org/issue1115 Some related bugs (not patches): http://bugs.python.org/issue1760089 It wasn't completely straightforward searching the tracker for "cross- compilation", given an apparent lack of certain typical search features which would facilitate the query, but searching for "cross" and doing searches in the page managed to pull up some results. I'm sure this topic has been covered in the newsgroup/list before, however. Paul From deets at nospam.web.de Tue Aug 26 16:54:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Aug 2008 22:54:23 +0200 Subject: Using Python to shared memory resources between Linux and Windows In-Reply-To: References: Message-ID: <6hj8rvFmlbhkU1@mid.uni-berlin.de> Blubaugh, David A. schrieb: > To All, To whom else if I may ask? > I was wondering if it was possible to utilize python to share a memory > resource between a linux and windows system?? It should be stated that > both the Linux (CENTOS 5) and windows are physically located on the same > computer. Is any of this possible? No, not as that. You can use IPC-mechanisums such as XMLRPC, CORBA or Pyro. But software such as VMWare or VirtualBox tries hard to *not* let guest and host os influence each other. Diez From Lie.1296 at gmail.com Wed Aug 6 05:33:21 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 6 Aug 2008 02:33:21 -0700 (PDT) Subject: Print statement isn't showing up? References: <496954360808050909m103fe08ve1b544ca4d289b40@mail.gmail.com> Message-ID: <3ff28b29-5234-4668-bdeb-0d025e60f0d5@q5g2000prf.googlegroups.com> On Aug 6, 2:28?am, "Timothy Grant" wrote: > On Tue, Aug 5, 2008 at 9:09 AM, Robert Dailey wrote: > > Hi, > > > I have the following code: > > > def ReplaceExternalWithCopy( localDir, remoteDir ): > > ? ? print "Removing external local directory:", localDir > > ? ? rmdirs( localDir ) > > ? ? vfxrepo.copy( remoteDir, localDir ) > > > I noticed that the print statement above does not show up before > > vfxrepo.copy() is called. the copy() function (as well as the rmdirs() > > function) are very long file-system calls that take up to 5 minutes. I > > should see a print statement before these are executed, but I do not. > > Instead it shows up *after* the last 2 lines of code have completed. Is > > there something broken about this? > > My guess is that the output is getting buffered and the buffer doesn't > get flushed until sometime after the function executes. > > -- > Stand Fast, > tjg. [Timothy Grant] Are you calling this function from inside, say, doctests-watched comments. From duncan.booth at invalid.invalid Mon Aug 11 13:53:19 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Aug 2008 17:53:19 GMT Subject: dict.update() useful or not? References: <00b06f78$0$14351$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > dict1.update(dict2) is of course equivalent to this code: > > for key, value in dict2.iteritems(): > dict1[key] = value > > Note that it replaces values in dict1 with the value taken from dict2. I > don't know about other people, but I more often want to keep the values > in dict1 regardless of what's in dict2, and only add items from dict2 if > it is new key. Like this: > > for key, value in dict2.iteritems(): > if not dict1.has_key(key): > dict1[key] = value > If you don't actually need to mutate dict1 in-place then just use update for this: d = dict(dict2) d.update(dict1) dict1 = d > There's the faintest of code smells to me. I would prefer to write > something like this: > > def create_request(url, headers): > headers.update(DEFAULT_HEADERS) > req = urllib2.Request(url, None, headers) > # ... > return req > > but of course this second example does the Wrong Thing, replacing > explicit headers with default values. There's a second code smell with that: even if it did what you want it isn't nice to mutate the parameter passed in as headers. What if the caller wants to reuse the headers again for another call? Much nicer just to do: def create_request(url, headers): hdrs = dict(DEFAULT_HEADERS) hdrs.update(headers) req = urllib2.Request(url, None, hdrs) # ... return req From wannymahoots at gmail.com Tue Aug 19 09:29:35 2008 From: wannymahoots at gmail.com (wannymahoots) Date: Tue, 19 Aug 2008 06:29:35 -0700 (PDT) Subject: optparse escaping control characters References: <4001fcc2-e595-4bd6-9baf-c71db3761d36@m3g2000hsc.googlegroups.com> <00bac3a3$0$20315$c3e8da3@news.astraweb.com> Message-ID: <1c780994-b5bc-48c1-90c5-c691e4897d42@56g2000hsm.googlegroups.com> Thanks for all the responses! From support.desk.ipg at gmail.com Mon Aug 11 15:18:26 2008 From: support.desk.ipg at gmail.com (Support Desk) Date: Mon, 11 Aug 2008 14:18:26 -0500 Subject: SSH utility In-Reply-To: References: Message-ID: <018801c8fbe7$09ec5700$a601a8c0@office.ipglobal.net> What about pexpect? http://www.noah.org/wiki/Pexpect -----Original Message----- From: Alan Franzoni [mailto:alan.franzoni.xyz at gmail.com] Sent: Monday, August 11, 2008 5:41 AM To: python-list at python.org Subject: Re: SSH utility James Brady was kind enough to say: > Hi all, > I'm looking for a python library that lets me execute shell commands > on remote machines. > > I've tried a few SSH utilities so far: paramiko, PySSH and pssh; > unfortunately all been unreliable, and repeated questions on their > respective mailing lists haven't been answered... Twisted conch seems to be your last chance :-) -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From emile at fenx.com Fri Aug 8 16:59:08 2008 From: emile at fenx.com (Emile van Sebille) Date: Fri, 08 Aug 2008 13:59:08 -0700 Subject: I need a Python mentor In-Reply-To: References: Message-ID: A. Joseph wrote: > *Please the first message i sent out contain error, i`m very very sorry.* > > > Hello everybody, i`m new to this list. I was programming in PHP before, > so just of recent I started learning python. I need someone who I can be > giving me some assignment based on the chapter I read in the book, and > tell person will sometime review my code and tell me if it well structured. > > > > Can you be my mentor? > > Abah Josep > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list Try the tutor list... http://mail.python.org/mailman/listinfo/tutor Emile From keshet1 at umbc.edu Fri Aug 22 10:42:13 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Fri, 22 Aug 2008 10:42:13 -0400 Subject: 'While' question Message-ID: <48AED045.7080001@umbc.edu> Thanks. I tried to use 'for' instead of 'while' as both of you suggested. It's running well as my previous version but breaks completely instead of just skipping the empty file. I suspect the reason is that this part is inside another 'for' so it stops everything. I just want to it to break only one 'for', that is go back to 5th line in the example code (directory C has one empty file): receptors = ['A', 'B', 'C'] for x in receptors: print x for i in range(3): for r in (7, 9, 11, 13, 15, 17): f = open('c:/Linux/Dock_method_validation/%s/validation/ligand_ran_line_%s_%sA_secondary_scored.mol2' %(x,i,r), 'r') line = f.readline()[:-1] out_file = open('c:/Linux/Dock_method_validation/%s/validation/pockets.out' %(x),'a') out_file.write('%s ' %i) out_file.write('%s ' %r) # skip to scores j=0 for line in f: line = line.rstrip() if "PRIMARY" not in line: j += 1 if j == 20: break else: for line in f: if "TRIPOS" not in line: line = line.rstrip() out_file.write(line) else: break f.close() out_file.close() Any suggestions as for how to control the "extent of break"? should I do something else instead? Thank you! From dwbear75 at gmail.com Fri Aug 22 12:55:05 2008 From: dwbear75 at gmail.com (DwBear75) Date: Fri, 22 Aug 2008 09:55:05 -0700 (PDT) Subject: rules of thumb for cross os code Message-ID: <76c97ae9-2ca0-4419-8630-c7cf6159811a@v16g2000prc.googlegroups.com> I am considering using python as a replacement for a lot of bash scripting that I have been doing. I would like to be as cross platform as possible, writing scripts for both windows and linux. Are there any guides are general rules of thumb on 1) keeping code os independant 2) nifty lambda's or other things to create functions fit for the environment 3) capturing return codes of other executables called from python; ie use os.system, or popen? or ? From zancudero at gmail.com Tue Aug 5 08:54:51 2008 From: zancudero at gmail.com (Alexei Zankevich) Date: Tue, 5 Aug 2008 15:54:51 +0300 Subject: regex question In-Reply-To: References: <6fqqovFcq6bmU1@mid.uni-berlin.de> Message-ID: <7df72c080808050554w7fb1f0a9p53ca5aa4b21c559b@mail.gmail.com> =) Indeed. But it will replace all dots including ordinary strings instead of numbers only. On Tue, Aug 5, 2008 at 3:23 PM, Jeff wrote: > On Aug 5, 7:10 am, Marc 'BlackJack' Rintsch wrote: > > On Tue, 05 Aug 2008 11:39:36 +0100, Fred Mangusta wrote: > > > In other words I'd like to replace all the instances of a '.' character > > > with something (say nothing at all) when the '.' is representing a > > > decimal separator. E.g. > > > > > 500.675 ----> 500675 > > > > > but also > > > > > 1.000.456.344 ----> 1000456344 > > > > > I don't care about the fact the the resulting number is difficult to > > > read: as long as it remains a series of digits it's ok: the important > > > thing is to get rid of the period, because I want to keep it only where > > > it marks the end of a sentence. > > > > > I was trying to do like this > > > > > s=re.sub("[(\d+)(\.)(\d+)]","... ",s) > > > > > but I don't know much about regular expressions, and don't know how to > > > get the two groups of numbers and join them in the sub. Moreover doing > > > like this I only match things like "345.000" and not "1.000.000". > > > > > What's the correct approach? > > > > In [13]: re.sub(r'(\d)\.(\d)', r'\1\2', '1.000.456.344') > > Out[13]: '1000456344' > > > > Ciao, > > Marc 'BlackJack' Rintsch > > Even faster: > > '1.000.456.344'.replace('.', '') => '1000456344' > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From FettManChu at gmail.com Fri Aug 29 08:42:46 2008 From: FettManChu at gmail.com (Fett) Date: Fri, 29 Aug 2008 05:42:46 -0700 (PDT) Subject: eval() == evil? --- How to use it safely? References: <7x4p54zlh2.fsf@ruckus.brouhaha.com> Message-ID: On Aug 28, 7:57?pm, Paul Rubin wrote: So long story short: if I am expecting a dictionary of strings, I should make a parser that only accepts a dictionary of strings then. There is no safe way to use an existing construct. That is what I was afraid of. I know I will have to deal with the possibility of bad data, but considering my use (an acronym legend for a database), and the fact that the site I plan to use should be secure, these issues should be minimal. The users should be able to spot any obvious false data, and restoring it should be simple. Many thanks to all of you for your alarmist remarks. I certainly don't want to, in any way, put my clients computers at risk by providing unsafe code. From straton at lampsacos.demon.co.uk Sun Aug 31 06:19:19 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Sun, 31 Aug 2008 11:19:19 +0100 Subject: Writing to ms excel In-Reply-To: <167fdb5f-e788-4ec9-ad41-369a41c00356@a2g2000prm.googlegroups.com> References: <56aeb3cd-1e37-4242-aefe-8a33452d61a2@q26g2000prq.googlegroups.com> <3msjb412b55hf4i00fvs3gto8lt6kv05na@4ax.com> <167fdb5f-e788-4ec9-ad41-369a41c00356@a2g2000prm.googlegroups.com> Message-ID: John Machin wrote: > On Aug 31, 11:32 am, Marin Brkic wrote: >> Is there a way to access google >> groups through a similiar interface program as a newsreader. > > I don't know (question has never arisen before). > >> Never >> used them before, and getting a lot of messages to my email every day >> does not sound very appealing to me. > > Either (1) you have not looked at the messages at the link that I gave > you or (2) your idea of "a lot of messages" every day differs wildly > from mine. Email alternatives are (a) one message per posting (b) > daily digest (c) none (use your web browser). > > HTH, > John I use thunderbird for private email, mailing lists and newsgroups. It is easy enough to set up filters to divert messages from specific mailing lists to their own directory. Is this adequate for your needs ? (You do get the whole message, not just the header ) From gagsl-py2 at yahoo.com.ar Tue Aug 5 02:40:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 05 Aug 2008 03:40:58 -0300 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> <12072cbe-139a-430f-81aa-b64bc31b43e5@e39g2000hsf.googlegroups.com> <87zlny8cdg.fsf@nokile.rath.org> Message-ID: En Thu, 31 Jul 2008 09:30:19 -0300, Nikolaus Rath escribi?: > oj writes: >> On Jul 31, 11:37?am, Nikolaus Rath wrote: >>> So why does Python distinguish between e.g. the type 'int' and the >>> class 'myclass'? Why can't I say that 'int' is a class and 'myclass' >>> is a type? >> >> I might be wrong here, but I think the point is that there is no >> distinction. A class (lets call it SomeClass for this example) is an >> object of type 'type', and an instance of a class is an object of type >> 'SomeClass'. > > But there seems to be a distinction: > >>>> class int_class(object): > ... pass > ... >>>> int_class > >>>> int > > [...] > If there is no distinction, how does the Python interpreter know when > to print 'class' and when to print 'type'? If it helps you to understand the issue, in Python 3.0 that difference is gone - the word "class" is used on both cases. See http://bugs.python.org/issue2565 -- Gabriel Genellina From sjmachin at lexicon.net Mon Aug 18 03:33:57 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 18 Aug 2008 00:33:57 -0700 (PDT) Subject: How to delete a line with re? References: Message-ID: <7b23ef27-fb02-414c-aed4-a62795833551@b38g2000prf.googlegroups.com> On Aug 18, 4:22?pm, Peter Otten <__pete... at web.de> wrote: > Peng Yu wrote: > > I want to delete the line with abc in the following program. But the > > following program does not do what I want. Can somebody let me know > > how to do it? > > file="""abcd > > efg > > hijk > > lmn > > """ > > > regex = re.compile("^abcd$", re.MULTILINE) > > print regex.sub('', file), > > What /do/ you want? If you want to remove the trailing newline > > regex = re.compile("^abcd$\n?", re.MULTILINE) > > might work. > Not only might work, but does work, including covering the corner cases where the abcd line is immediately followed by (1) an empty line (2) no newline then end-of-file. It is also more elegant [yes, even regular expressions can be elegant] than what I came up with (see below). Hint for the OP: repr() is your friend. >>> import re >>> src="""abcd ... efg ... abcd ... ... hijk ... abcd""" >>> expected = """efg ... ... hijk ... """ >>> print repr(src) 'abcd\nefg\nabcd\n\nhijk\nabcd' >>> print repr(expected) 'efg\n\nhijk\n' >>> for pattern in ["^abcd$\n?", r"^abcd(\n|\Z)"]: ... regex = re.compile(pattern, re.MULTILINE) ... actual = regex.sub('', src) ... print repr(actual) ... print actual == expected ... 'efg\n\nhijk\n' True 'efg\n\nhijk\n' True >>> Cheers, John From castironpi at gmail.com Sat Aug 9 14:58:57 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 9 Aug 2008 11:58:57 -0700 (PDT) Subject: Fastest way to store ints and floats on disk References: <489B41CE.8080909@shopzeus.com> Message-ID: <1ad14df7-09ea-4b1d-8fac-3025bdd2d522@f63g2000hsf.googlegroups.com> On Aug 7, 2:27?pm, "M.-A. Lemburg" wrote: > On 2008-08-07 20:41, Laszlo Nagy wrote: > > > > > > > ?Hi, > > > I'm working on a pivot table. I would like to write it in Python. I > > know, I should be doing that in C, but I would like to create a cross > > platform version which can deal with smaller databases (not more than a > > million facts). > > > The data is first imported from a csv file: the user selects which > > columns contain dimension and measure data (and which columns to > > ignore). In the next step I would like to build up a database that is > > efficient enough to be used for making pivot tables. Here is my idea for > > the database: > > > Original CSV file with column header and values: > > > "Color","Year","Make","Price","VMax" > > Yellow,2000,Ferrari,100000,254 > > Blue,2003,Volvo,50000,210 > > > Using the GUI, it is converted to this: > > > dimensions = [ > > ? ?{ 'name':'Color', 'colindex:0, 'values':[ 'Red', 'Blue', 'Green', > > 'Yellow' ], }, > > ? ?{ 'name':'Year', colindex:1, 'values':[ > > 1995,1999,2000,2001,2002,2003,2007 ], }, > > ? ?{ 'name':'Make', colindex:2, 'value':[ 'Ferrari', 'Volvo', 'Ford', > > 'Lamborgini' ], }, > > ] > > measures = [ > > ? ?{ 'name', 'Price', 'colindex':3 }, > > ? ?{ 'name', 'Vmax', 'colindex':4 }, > > ] > > facts = [ > > ? ?( (3,2,0),(100000.0,254.0) ?), # ( dimension_value_indexes, > > measure_values ) > > ? ?( (1,5,1),(50000.0,210.0) ), > > ? .... # Some million rows or less > > ] > > > The core of the idea is that, when using a relatively small number of > > possible values for each dimension, the facts table becomes > > significantly smaller and easier to process. (Processing the facts would > > be: iterate over facts, filter out some of them, create statistical > > values of the measures, grouped by dimensions.) > > > The facts table cannot be kept in memory because it is too big. I need > > to store it on disk, be able to read incrementally, and make statistics. > > In most cases, the "statistic" will be simple sum of the measures, and > > counting the number of facts affected. To be effective, reading the > > facts from disk should not involve complex conversions. For this reason, > > storing in CSV or XML or any textual format would be bad. I'm thinking > > about a binary format, but how can I interface that with Python? > > > I already looked at: > > > - xdrlib, which throws me DeprecationWarning when I store some integers > > - struct which uses format string for each read operation, I'm concerned > > about its speed > > > What else can I use? > > ?>>> import marshal > ?>>> marshal.dump(1, open('test.db', 'wb')) > ?>>> marshal.load(open('test.db', 'rb')) > 1 > > It also very fast at dumping/loading lists, tuples, dictionaries, > floats, etc. Depending on how hard-core you want to be, store the int, float, string, and long C structures directly to disk, at a given offset. Either use fixed-length strings, or implement (or find) a memory manager. Anyone have a good alloc-realloc-free library, C or Python? From alexnbryan at gmail.com Fri Aug 29 17:38:20 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Fri, 29 Aug 2008 16:38:20 -0500 Subject: Google License Keys for pyGoogle Message-ID: <473EBAC0-3227-428A-8AA6-489D5A006D14@gmail.com> I know this isn't the right mailing list, but it saves me the hassle of signing up for another one if someone on here knows. I have never used pyGoogle before, and I just read that google isn't giving out license keys anymore? If that is the case, can I still get pygoogle to work another way? if you know anything please help me out! From wgwigw at gmail.com Wed Aug 20 22:57:39 2008 From: wgwigw at gmail.com (momobear) Date: Wed, 20 Aug 2008 19:57:39 -0700 (PDT) Subject: what's wrong with www.planetpython.org? Message-ID: <05cddf90-f72b-487b-82df-a52eccdaec68@i20g2000prf.googlegroups.com> hi, Does anyone know why the www.planetpython.org could not be connected recently? thanks. From fredrik at pythonware.com Wed Aug 13 11:39:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Aug 2008 17:39:34 +0200 Subject: You advice please In-Reply-To: <48A2FBAC.3000103@wiggly.org> References: <20080813110444.7b48ddbc.darcy@druid.net> <76fd5acf0808130811y7d7d6584m721096295a72af98@mail.gmail.com> <48A2FBAC.3000103@wiggly.org> Message-ID: Nigel Rantor wrote: > Throwaway comments like yours that are pithy, emotional and devoid of > any factual content are just the kind of thing that makes lists such as > this less useful than they could be. Oh, please. It's a fact that Python advocacy is a lot more low-key than the advocacy of certain potentially competing technologies. It's always been that way. Too many Europeans involved, most likely. > Have you read this list? > > I would suggest your comment indicates not. This list is a Python forum. Calvin (who's a long time contributor to this forum, which you would have known if you'd actually followed the list for some time) was talking about the real world. From notvalid2 at sbcglobal.net Sat Aug 23 02:10:42 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Fri, 22 Aug 2008 23:10:42 -0700 Subject: Filling in Degrees in a Circle (Astronomy) In-Reply-To: References: Message-ID: Maric Michaud wrote: > Le Saturday 23 August 2008 01:12:48 W. eWatson, vous avez ?crit : >> The other night I surveyed a site for astronomical use by measuring the >> altitude (0-90 degrees above the horizon) and az (azimuth, 0 degrees north >> clockwise around the site to 360 degrees, almost north again) of obstacles, >> trees. My purpose was to feed this profile of obstacles (trees) to an >> astronomy program that would then account for not sighting objects below >> the trees. >> >> When I got around to entering them into the program by a file, I found it >> required the alt at 360 azimuth points in order from 0 to 360 (same as 0). >> Instead I have about 25 points, and expected the program to be able to do >> simple linear interpolation between those. >> >> Is there some simple operational device in Python that would allow me to >> create an array (vector) of 360 points from my data by interpolating >> between azimuth points when necessary? All my data I rounded to the nearest >> integer. Maybe there's an interpolation operator? >> >> As an example, supposed I had made 3 observations: (0,0) (180,45) and >> (360,0). I would want some thing like (note the slope of the line from 0 to >> 179 is 45/180 or 0.25): >> alt: 0, 0.25, 0.50, 0.75, ... 44.75, 45.0 >> az : 0, 1, 2, 3, 180 >> >> Of course, I don't need the az. > > Not sure I got it, but is that fulfill your specs ? > >>>> [20]: def interpolate(a, b) : > slope = float(b[1] - a[1]) / (b[0] - a[0]) > return [ slope * float(i) for i in xrange(b[0]-a[0] + 1) ] > ....: > >>>> [23]: interpolate((0, 0), (180, 45)) > ...[23]: > [0.0, > 0.25, > 0.5, > 0.75, > .... > 44.5, > 44.75, > 45.0] > >>>> [29]: interpolate((80, 20), (180, 45)) > [0.0, > 0.25, > 0.5, > 0.75, > 1.0, > 1.25, > ... > 24.5, > 24.75, > 25.0] > > > Yes, the interpolation part looks right, but the tricky part is to be able to go through the list and find where one needs to generate all the missing az angles. A chunk of my data is in a post above yours. Here's a more revealing set of data where four data points are known: az el 0 10 4 14 (slope is 1) 12 30 (slope is 2) 15 15 (slope is -5) 16 points need to be generated, 0 to 15, representing 15 degrees around the circle. So, I'm doing this in my head, one would get 0 10 (slope is 1) 1 11 2 12 3 13 4 14 5 16 (slope is 2) 6 18 7 18 ... 12 30 13 25 14 20 15 15 I use Python occasionally, and starting up requires some effort, but I've finally decided to take a go at this. I'm working on this now, but my knowledge of python needs refreshing. Right now I have a file of all the az,el data I've collected, and I'd like to open it with Python for XP. However, Python doesn't like this: junkfile = open('c:\tmp\junkpythonfile','w') I get junkfile = open('c:\tmp\junkpythonfile','w') IOError: [Errno 2] No such file or directory: 'c:\tmp\\junkpythonfile' This problematic segment is just a hack of a similar statement which has the same problem and a much longer path. I suspect the problem is with the back slash. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From fredrik at pythonware.com Sun Aug 17 15:37:40 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 17 Aug 2008 21:37:40 +0200 Subject: like a "for loop" for a string In-Reply-To: <19022155.post@talk.nabble.com> References: <19022098.post@talk.nabble.com> <19022155.post@talk.nabble.com> Message-ID: Alexnb wrote: > Ya just an example, to print the numbers 1-5 Sorry, I still don't have the slightest idea what you expect the code to do. >>> But I am wondering is there a way to something like this: >>> >>> funString = "string string string non-string non-string string" >>> and >>> for "string" in funString: >>> print something >>> >>> I know you can't do that; but, is there a way do do something similar >>> that >>> gets the same result? >> >> you seem to have forgotten to specify the result. or did you mean that >> the above should print 1-5? From daniel.watrous at gmail.com Wed Aug 27 13:41:25 2008 From: daniel.watrous at gmail.com (Daniel) Date: Wed, 27 Aug 2008 10:41:25 -0700 (PDT) Subject: problem with packages and path References: <8c1351f9-d349-4c0c-97a4-024c9472bff3@z11g2000prl.googlegroups.com> <2c0bf7a4-16d2-43ca-9f7e-fce000fa626a@34g2000hsh.googlegroups.com> Message-ID: <736acf59-d6e1-40cd-8b56-496fce6cee26@n38g2000prl.googlegroups.com> On Aug 27, 11:00?am, Paul Boddie wrote: > On 27 Aug, 18:44, Daniel wrote: > > > > > I'm writing some unit tests for my python software which uses > > packages. ?Here is the basic structure: > > > mypackage > > [...] > > > ? unittests > > ? ? __init__.py > > ? ? alltests.py > > ? ? test1.py > > ? ? test2.py > > > within alltests.py I would expect to be able to "import > > mypackage.unittests.test1". ?In fact within PyScripter this works as > > expected. ?However, when I execute the code from the command line, I > > get the following error: > > > ImportError: No module named mypackage.unittests.test1 > > One thing to note: if you are running alltests.py directly (which you > don't mention explicitly) then even if you do so from the directory > containing the root of the package hierarchy (mypackage), it will be > the directory containing alltests.py (unittests) which will appear on > the PYTHONPATH/sys.path. Sometimes it's easy to take this behaviour > for granted when running programs. > > A question: what happens if you prepend the directory containing the > root of package hierarchy to sys.path using insert (at element 0) > rather than append? > > Paul I changed it to 'sys.path.insert(0, newpath)', as you suggest, but it doesn't fix the error. I did notice that the directory containing the file alltests.py ends up in the path. I've also noticed that (in WinXP at least) the sys.path modification inserts a '..' in the path, rather than the full path to 'mypackage'. I'm not sure if this makes a difference, but it seems like I should be able to add either '..' or 'path/to/mypackage' to the path and have it find my packages. Any more suggestions? From lists at svrinformatica.it Thu Aug 21 06:56:33 2008 From: lists at svrinformatica.it (Mailing List SVR) Date: Thu, 21 Aug 2008 12:56:33 +0200 Subject: Distinguish file and folder on ftp site In-Reply-To: References: <1218700228.7851.1.camel@localhost.localdomain> Message-ID: <1219316193.8260.1.camel@localhost.localdomain> Il giorno gio, 14/08/2008 alle 10.08 +0200, Fredrik Lundh ha scritto: > Mailing List SVR wrote: > > > is there a simple way to do this? > > > > ftplib seems unable to distinguish between files and dir, a mimetype > > check would be good, > > the FTP protocol doesn't specify the format for the output from the LIST > command, so you have to use some heuristics; see e.g. the code in > > http://svn.python.org/projects/python/trunk/Tools/scripts/ftpmirror.py > > or use a wrapper for Dan Bernstein's ftpparse library (requires a C > compiler): > > http://cr.yp.to/ftpparse.html > http://c0re.23.nu/c0de/ftpparsemodule/ > http://effbot.org/downloads/#ftpparse > ftpparse seems broken, I found ftputil as the best solution, thanks Nicola > Not sure what you mean by "mimetype"; that has nothing to do with > directories vs. files, afaik. > > > > -- > http://mail.python.org/mailman/listinfo/python-list From samuel.morhaim at gmail.com Wed Aug 13 18:30:40 2008 From: samuel.morhaim at gmail.com (Samuel Morhaim) Date: Wed, 13 Aug 2008 18:30:40 -0400 Subject: Can't use DB name with dashes using pymssql ??? In-Reply-To: <65c3648d0808131354x333a7e0cica29217a26f4ce42@mail.gmail.com> References: <65c3648d0808131354x333a7e0cica29217a26f4ce42@mail.gmail.com> Message-ID: <65c3648d0808131530w29728a78ib646dde89481e656@mail.gmail.com> I believe there is a bug in Python.. _mssql ... I am not too familiar with Python yet, but after adding several breakpoints and watching the variable, the last step of pymssql.py is # open the connection con = _mssql.connect(dbhost, dbuser, dbpasswd) con.select_db(dbbase) At this point the contents of dbbase is "Gcare4UI-B6_3_dev" (no quotes)... however, the immediate error is that "Gcare4UI" does not exist. Again removing the DASH from Gcare4UI-B6_3_dev and turning it into Gcare4UIB6_3_dev results in error that can't find DB Gcare4UIB6_3_dev (of course because the DB without the - doesnt exist... ) please help... thanks. On Wed, Aug 13, 2008 at 4:54 PM, Samuel Morhaim wrote: > I tried: > > import sys > import pymssql > > db = 'Gcare4UI-B6_3_dev' > > conn = pymssql.connect (host = "localhost", > user = "myname", > password = "mypassword", > database = db) > > > > And this returns an error saying > Could not locate entry in sysdatabases for database 'Gcare4UI'. No entry > found with that name. > > It is not reading the db name after the Dash... if i remove the dash from > the db to see what happens, it shows this obvious error, because it doesnt > exist... i was just making sure the problem was with the dash > > Could not locate entry in sysdatabases for database 'Gcare4UIB6_3_dev'. No > entry found with that name. > > Anyone had this problem? > > Thanks. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Aug 21 11:40:41 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 21 Aug 2008 17:40:41 +0200 Subject: semantics of the |= operator References: <16f69c9c-386f-41a3-852a-cd482327fc2d@c58g2000hsc.googlegroups.com> Message-ID: <6h5glcFitoeuU1@mid.uni-berlin.de> akva wrote: > Hi All, > > what's the exact semantics of the |= operator in python? > It seems that a |= d is not always equivalent to a = a | d > > For example let's consider the following code: > > def foo(s): > s = s | set([10]) > > def bar(s): > s |= set([10]) > > s = set([1,2]) > > foo(s) > print s # prints set([1, 2]) > > bar(s) > print s # prints set([1, 2, 10]) > > So it appears that inside bar function the |= operator modifies the > value of s in place rather than creates a new value. Yes. That's the exact purpose of the in-place operators when they deal with mutable objects. What else did you expect? Now of course this behaves different: def foo(x): x += 1 y = 100 foo(y) print y will result in y still being 100, as the value 101 that is bound to x inside foo is *not* re-bound to the name y in the outer scope. This is because numbers (and strings and tuples) are immutables, and thus the operation won't modify the 100 in place to become 101, instead return a new object. Diez From wuwei23 at gmail.com Fri Aug 1 01:16:10 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 31 Jul 2008 22:16:10 -0700 (PDT) Subject: how to split text into lines? References: <7ed81072-aaf1-4e06-98b5-e6fa94268cbd@r66g2000hsg.googlegroups.com> Message-ID: <99ec6d87-e204-4ffe-a573-a8e681a072f0@q5g2000prf.googlegroups.com> Chris wrote: > or what about 'string'.splitlines(True) as that retains newline > characters. ;) Okay, you win :) Man, you'd think with the ease of object introspection I'd have at least looked at its docstring :) Cheers, Chris! From gagsl-py2 at yahoo.com.ar Wed Aug 20 05:09:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 20 Aug 2008 06:09:18 -0300 Subject: IDLE issue References: <73045cca0808200056r68a015c0sd41365627ddc1298@mail.gmail.com> Message-ID: En Wed, 20 Aug 2008 04:56:32 -0300, aditya shukla escribi?: > I found something interesting while working in idle.I have windows vista > and > python2.5 > > if i do > import subprocess > proc > =subprocess.Popen('cmd.exe',stdin=subprocess.PIPE,stdout=subprocess.PIPE) > output = proc.communicate('dir\n')[0] > print repr(output) > > This dosen't work in idle Works fine for me, using Windows XP If you're pasting those lines directly over the shell window, beware of this bug: http://bugs.python.org/issue3559 -- Gabriel Genellina From josephtys86 at googlemail.com Sat Aug 9 12:19:42 2008 From: josephtys86 at googlemail.com (josephtys86 at googlemail.com) Date: Sat, 9 Aug 2008 09:19:42 -0700 (PDT) Subject: Extract string from log file References: Message-ID: <5ae1a663-cd2c-4419-a046-9739d927cf9d@p31g2000prf.googlegroups.com> On Aug 9, 11:22?pm, Edwin.Mad... at VerizonWireless.com wrote: > from each line separate out url and request parts. split the request into key-value pairs, use urllib to unquote key-value pairs......as show below... > > import urllib > line = "GET /stat.gif?stat=v&c=F-Secure&v=1.1%20Build%2014231&s=av%7BNorton%20360%20%28Symantec%20Corporation%29+69%3B%7Dsw%7BNorton%20360%20%28Symantec%20Corporation%29+69%3B%7Dfw%7BNorton%20360%20%28Symantec%20Corporation%29+5%3B%7Dv%7BMicrosoft%20Windows%20XP+insecure%3BMicrosoft%20Windows%20XP%20Professional+f%3B26027%3B26447%3B26003%3B22452%3B%7D&r=0.9496 HTTP/1.1" > words = line.split() > for word in words: > if word.find('?') >= 0: > ? ? ? ? req = word[word.find('?') + 1:] > ? ? ? kwds = req.split('&') > ? ? ? for kv in kwds: > ? ? ? ? print urllib.unquote(kv) > > stat=v > c=F-Secure > v=1.1 Build 14231 > s=av{Norton 360 (Symantec Corporation)+69;}sw{Norton 360 (Symantec Corporation)+69;}fw{Norton 360 (Symantec Corporation)+5;}v{Microsoft Windows XP+insecure;Microsoft Windows XP Professional+f;26027;26447;26003;22452;} > r=0.9496 > > good luck > Edwin > > -----Original Message----- > From: python-list-bounces+edwin.madari=verizonwireless.... at python.org > > [mailto:python-list-bounces+edwin.madari=verizonwireless.... at python.org] > On Behalf Of josephty... at googlemail.com > Sent: Saturday, August 09, 2008 10:48 AM > To: python-l... at python.org > Subject: Extract string from log file > > 203.114.10.66 - - [01/Aug/2008:05:41:21 +0300] "GET /stat.gif? > stat=v&c=F-Secure&v=1.1%20Build%2014231&s=av%7BNorton > %20360%20%28Symantec%20Corporation%29+69%3B%7Dsw%7BNorton > %20360%20%28Symantec%20Corporation%29+69%3B%7Dfw%7BNorton > %20360%20%28Symantec%20Corporation%29+5%3B%7Dv%7BMicrosoft%20Windows > %20XP+insecure%3BMicrosoft%20Windows%20XP%20Professional+f > %3B26027%3B26447%3B26003%3B22452%3B%7D&r=0.9496 HTTP/1.1" 200 43 > "http://dfstage1.f-secure.com/fshc/1.1/release/devbw/1.1.14231/ > card.html" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; > SV1; .NET CLR 2.0.50727)" > > does anyone know how can i extract certain string from this log file > using regular expression in python or using XML. can teach me. > --http://mail.python.org/mailman/listinfo/python-list > > The information contained in this message and any attachment may be > proprietary, confidential, and privileged or subject to the work > product doctrine and thus protected from disclosure. ?If the reader > of this message is not the intended recipient, or an employee or > agent responsible for delivering this message to the intended > recipient, you are hereby notified that any dissemination, > distribution or copying of this communication is strictly prohibited. > If you have received this communication in error, please notify me > immediately by replying to this message and deleting it and all > copies and backups thereof. ?Thank you. > > do you mind to explain further. based on the source code that you gave me. what will it output. i wonder. Sorry i am new to string extraction. i do understand your python coding. the only thing i don't understand is this part. for word in words: if word.find('?') >= 0: req = word[word.find('?') + 1:] kwds = req.split('&') for kv in kwds: print urllib.unquote(kv) what does this code do? anyway, is this code automatic. what i mean is can it extract the string everytime when a new log file is being output by the sever? From emile at fenx.com Tue Aug 26 15:23:27 2008 From: emile at fenx.com (Emile van Sebille) Date: Tue, 26 Aug 2008 12:23:27 -0700 Subject: Renaming Excel Spreadsheets In-Reply-To: References: Message-ID: Greg Lindstrom wrote: > Hello, > > I am working with Python to create Excel spreadsheets and have run into > a couple of problems I hope you can help me with. > > First...are there any bindings/libraries into Open Office? > > Now, back to Excel. > > --> Does anyone know a way to create N worksheets? By default, 3 are > created, but I would like more. > > --> Is it possible to rename a worksheet inside of the workbook (change > "Sheet1" to "July 08", for example). Here's some code from years back that adds sheets to a workbook and then renames them. Sheets = [["SlsSrce",None,1], ["SalesReps",None,1], ["Control",None,1]] replist = [] for k in repkeys: if k in currentReps: replist.append([k, reps[k]]) Sheets.append(['Rep-%s' % k, None, 1]) def WorkBookSetup(Sheets): # xl.Visible = 1 wbi = xl.Workbooks.Add() wbi.Activate() sheetcount = xl.Sheets.Count index = 0 for name, ref, nextline in Sheets: if index >= sheetcount: wbi.Sheets.Add() index = index + 1 index = 0 for name, ref, nextline in Sheets: wbi.Sheets[index].Name = name Sheets[index][1] = wbi.Sheets[index] index = index + 1 return wbi HTH, Emile From blog335 at watchesblog.cn Wed Aug 27 23:34:06 2008 From: blog335 at watchesblog.cn (blog335 at watchesblog.cn) Date: Wed, 27 Aug 2008 20:34:06 -0700 (PDT) Subject: A Lange & Sohne Grand Lange 1 Watches: Quality A Lange & Sohne Discount Watches Message-ID: <049b20ff-d68f-4b54-b44d-8cb4c4a1a6d2@p31g2000prf.googlegroups.com> A Lange & Sohne Grand Lange 1 Watches: Quality A Lange & Sohne Discount Watches Quality A Lange & Sohne Grand Lange 1 Watches http://a-lange-sohne-watches.pxhelp.com/a-lange-sohne-grand-lange-1.html Thank you for choosing http://www.pxhelp.com/ Discount A Lange & Sohne Watches http://a-lange-sohne-watches.pxhelp.com/ We guarantee our A Lange & Sohne Grand Lange 1 Watches and A Lange & Sohne Grand Lange 1 Luxury Watches aren't just a simple imitation. We use the same fine materials and technology that the original does. Each A Lange & Sohne Grand Lange 1 Watch produced is examined carefully by our quality test department and every watch is inspected again before being moved out from our warehouse. It is our heartfelt desire that you do experience the joy of shopping when buying one of our A Lange & Sohne Watches at our site http://www.pxhelp.com/ . We guarantee high quality and favorable price we offer. Best service you will receive from us. Any question please contact with us, we are happy to service for you. A Lange & Sohne Grand Lange 1 Watches Items : A Lange & Sohne Grand Lange 1 Luminous Mens Watch 115.029 http://a-lange-sohne-watches.pxhelp.com/A-Lange-Sohne-wristwatch-19.html A Lange & Sohne Grand Lange 1 Mens Watch 115.031 http://a-lange-sohne-watches.pxhelp.com/A-Lange-Sohne-wristwatch-20.html A Lange & Sohne Grand Lange 1 Mens Watch 115.021 http://a-lange-sohne-watches.pxhelp.com/A-Lange-Sohne-wristwatch-21.html A Lange & Sohne Grand Lange 1 Mens Watch 115.032 http://a-lange-sohne-watches.pxhelp.com/A-Lange-Sohne-wristwatch-22.html A Lange & Sohne Grand Lange 1 Mens Watch 115.022 http://a-lange-sohne-watches.pxhelp.com/A-Lange-Sohne-wristwatch-23.html A Lange & Sohne Grand Lange 1 Mens Watch 115.025 http://a-lange-sohne-watches.pxhelp.com/A-Lange-Sohne-wristwatch-35.html A Lange & Sohne Grand Lange 1 Mens Watch 115.026 http://a-lange-sohne-watches.pxhelp.com/A-Lange-Sohne-wristwatch-36.html From nospam at invalid.com Wed Aug 6 20:05:02 2008 From: nospam at invalid.com (Jack) Date: Wed, 6 Aug 2008 17:05:02 -0700 Subject: benchmark Message-ID: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> I know one benchmark doesn't mean much but it's still disappointing to see Python as one of the slowest languages in the test: http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy/ From me at jonbowlas.com Tue Aug 12 08:19:00 2008 From: me at jonbowlas.com (Jon Bowlas) Date: Tue, 12 Aug 2008 13:19:00 +0100 Subject: Help counting the total number of dictionaries inside a list that contain a specified key value In-Reply-To: <8d37bc060808120506n5e94819cp42b99c048bffc903@mail.gmail.com> References: <8d37bc060808120409r70fb5469kb56186b812dcc434@mail.gmail.com> <8d37bc060808120506n5e94819cp42b99c048bffc903@mail.gmail.com> Message-ID: <8d37bc060808120519n7f7cefban136469c49265391a@mail.gmail.com> Hrmm, any ideas why I'd be getting 'SyntaxError: invalid syntax' for both of these? > sum(u'Level 2 Courses' in dct for dct in yourlist) > q = set(['1']); print q, sum(d.get('level') in q for d in thelist) The error occurs at the 'for' I'm afraid I can't use Peters suggestion as I'm using python 2.3 and it doesn't have the collection module. Thanks anyway. Cheers Jon 2008/8/12 Jon Bowlas : > Many thanks for all your reponses, much appreciated. > > I'll get back to you on which is the best for me. > > BTW - yes John thats exactly what I wanted. > > Cheers > > Jon > > Jon Bowlas wrote: >> For example I'd like to kow how many dictionaries there are with a >> level 1, 2 , 23 & 3 etc. How would one go about achieveing this? >> >> Hope someone can help. > > sum(u'Level 2 Courses' in dct for dct in yourlist) > > Christian > > 2008/8/12 Jon Bowlas : >> Hi All, >> >> I have the following list containing dictionaries and I would like to >> be able to count the total number of dictionaries I have that contain >> a certain value set for the 'level' key: >> >> [{'mod_title': u'Introduction to Human Anatomy', 'level': u'1', >> 'modcode': u'ANAT1003', 'deptleveltext': u'', 'deptlevelheader': >> u'Level 1 Courses', 'subj_code': u'AE'}, {'mod_title': u'Developmental >> Neurobiology', 'level': u'2', 'modcode': u'ANAT2008', 'deptleveltext': >> u'', 'deptlevelheader': u'Level 2 Courses', 'subj_code': u'AE'}, >> {'mod_title': u'Human Neuroanatomy', 'level': u'2', 'modcode': >> u'ANAT2010', 'deptleveltext': u'', 'deptlevelheader': u'Level 2 >> Courses', 'subj_code': u'AE'}, {'mod_title': u'Human Anatomy and >> Embryology', 'level': u'2', 'modcode': u'ANAT2050', 'deptleveltext': >> u'', 'deptlevelheader': u'Level 2 Courses', 'subj_code': u'AE'}, >> {'mod_title': u'Ethics of Fertility and Embryo Research', 'level': >> u'2', 'modcode': u'ANAT2099', 'deptleveltext': u'', 'deptlevelheader': >> u'Level 2 Courses', 'subj_code': u'AE'}, {'mod_title': u"Man's Place >> in Nature 1750-1900", 'level': u'23', 'modcode': u'HMED3001', >> 'deptleveltext': u'', 'deptlevelheader': u'Level 2/3 Courses', >> 'subj_code': u'AE'}, {'mod_title': u'Medicine, Disease and Society, >> Antiquity to Renaissance ', 'level': u'23', 'modcode': u'HMED3003', >> 'deptleveltext': u'', 'deptlevelheader': u'Level 2/3 Courses', >> 'subj_code': u'AE'}, {'mod_title': u'Madness and Society', 'level': >> u'23', 'modcode': u'HMED3004', 'deptleveltext': u'', >> 'deptlevelheader': u'Level 2/3 Courses', 'subj_code': u'AE'}] >> >> For example I'd like to kow how many dictionaries there are with a >> level 1, 2 , 23 & 3 etc. How would one go about achieveing this? >> >> Hope someone can help. >> >> Cheers >> >> Jon >> > From cs at zip.com.au Mon Aug 4 00:10:38 2008 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 4 Aug 2008 14:10:38 +1000 Subject: Teething troubles with Python on a Mac In-Reply-To: Message-ID: <20080804041038.GA25764@cskk.homeip.net> On 03Aug2008 23:14, Avinash Vora wrote: >> You will likely cause more problems updating the system python than >> managing the two separate installations. > > That's sadly worrying. It shouldn't be. It is often useful to have multiple versions of stuff installed. Replacing the system stuff means playing in the vendor/distributor's namespace, and you may expect they to cheerfully and freely tread all over your changes if something in Software Update wants to. By keeping a separate Python install you know you are not damaging the system, and the system will not damage you. Personally I use python 2.5 from the macports stuff, which installs to /opt/local. Neatly out of the way. It's all very easy. >> OSX relies on the version of python they ship. > > I think that helps my point--there *are* bug fixes between major > versions despite the new language changes, and that can really only be a > good thing. No, it does not help your point. The OS may rely on a _bug_! It is best to keep the OS and the stuff it uses pristine, because the two parts are shaped to fit each other. They work now, and you're changing something that works. Whether an "upgrade" changes a bug or a feature is irrelevant - it changes behaviour. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Zombies don't get pumped. - Jake, in rec.climbing From dullrich at sprynet.com Tue Aug 5 14:28:26 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 05 Aug 2008 13:28:26 -0500 Subject: Psycho question Message-ID: Just heard about Psycho. I've often wondered why someone doesn't make something that does exactly what Psycho does - keen. Silly question: It's correct, is it not, that Psycho doesn't actually modify the Python installation, except by adding a module or two (so that code not using Psycho is absolutely unaffected)? Thanks, -- David C. Ullrich From adityashukla1983 at gmail.com Tue Aug 19 21:06:13 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Tue, 19 Aug 2008 20:06:13 -0500 Subject: Subprocess module question. Message-ID: <73045cca0808191806r1277669fyba9299451e62a7a5@mail.gmail.com> Hello folks, I am using windows vista and i am trying to communicate with various processes. so when i do import subprocess proc=subprocess.Popen('cmd.exe') --This opens the command prompt But when i do proc=subprocess.Popen('netscan.exe') it gives an error Traceback (most recent call last): File "", line 1, in proc =subprocess.Popen('netscan.exe') File "C:\Python25\lib\subprocess.py", line 594, in __init__ errread, errwrite) File "C:\Python25\lib\subprocess.py", line 816, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified However "netscan.exe" is present on my system. Some please explain why does this happens? Thanks in advance Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From arkanes at gmail.com Tue Aug 26 12:59:15 2008 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 26 Aug 2008 11:59:15 -0500 Subject: Are dictionaries the same as hashtables? In-Reply-To: References: <20080826074338.GB10162@marcher.name> Message-ID: <4866bea60808260959g2162f982yf43dab073cb3a97d@mail.gmail.com> On Tue, Aug 26, 2008 at 11:12 AM, Fredrik Lundh wrote: > Martin Marcher wrote: > >>> Are dictionaries the same as hashtables? >> >> Yes, but there is nothing in there that does sane collision handling >> like making a list instead of simply overwriting. > > are you sure you know what "collision handling" means in this context? I think the confusion comes from thinking that dictionaries are (really) hash tables and thus that things like collision handling are exposed to the user of the data structure. In this sense, no, dictionaries are *not* hash tables. They are mappings of keys to values, and they use hash tables as part of their implementation. From raashid_hbk at yahoo.com Sun Aug 17 14:00:10 2008 From: raashid_hbk at yahoo.com (raashid bhatt) Date: Sun, 17 Aug 2008 11:00:10 -0700 (PDT) Subject: how to call API Functions in python Message-ID: <46c57206-49a8-48b1-966f-2beab4ac433e@w24g2000prd.googlegroups.com> how to call API Functions in python From nytrokiss at gmail.com Thu Aug 21 13:14:37 2008 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 21 Aug 2008 10:14:37 -0700 Subject: Read PDF content In-Reply-To: References: Message-ID: <8a6b8e350808211014h216adc76g9e17f0d86941244b@mail.gmail.com> You can also use pdflib http://www.pdflib.com/download/pdflib-family/pdflib-7/ On Thu, Aug 21, 2008 at 6:47 AM, William Purcell wrote: > Sorry, this last email was meant to be to the list. > > On Thu, Aug 21, 2008 at 8:41 AM, William Purcell < > williamhpurcell at gmail.com> wrote: > >> I have been trying to do the same thing. Here is something I came up with, >> although it's not completely dependent on Python. It requires pdftotext to >> be installed. If your on a linux box, I think it comes in xpdf-utils but I'm >> not comletely sure. Anyway, install pdftotext and then you could use this >> function: >> >> ---------------------------------------------------------------------------- >> import os >> >> def readpdf(filepath): >> cmd = 'pdftotext -layout %s -'%(filepath,) >> lines=os.popen(cmd).readlines() >> return lines >> >> ---------------------------------------------------------------------------- >> I would like to find something totally Python, but this has worked for me >> in a pinch. >> -Bill >> >> >> On Thu, Aug 21, 2008 at 5:00 AM, AON LAZIO wrote: >> >>> Hi, Guys. >>> I am trying to extract the PDF file content(to get the specific >>> information) using python. I already tried pyPdf with no success. >>> Anyone has suggestions? >>> Thanks in advance. >>> >>> Aonlazio >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexnbryan at gmail.com Sun Aug 17 14:22:37 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sun, 17 Aug 2008 11:22:37 -0700 (PDT) Subject: like a "for loop" for a string Message-ID: <19022098.post@talk.nabble.com> Okay, so lets say you have a list: funList = [1,2,3,4,5] and you do: for x in funList: print x this will print 1-5 But I am wondering is there a way to something like this: funString = "string string string non-string non-string string" and for "string" in funString: print something I know you can't do that; but, is there a way do do something similar that gets the same result? -- View this message in context: http://www.nabble.com/like-a-%22for-loop%22-for-a-string-tp19022098p19022098.html Sent from the Python - python-list mailing list archive at Nabble.com. From soid.exe at gmail.com Sat Aug 23 18:20:39 2008 From: soid.exe at gmail.com (Grigory Temchenko) Date: Sat, 23 Aug 2008 15:20:39 -0700 (PDT) Subject: How to know a top directory? References: <2.2.32.20080823112859.0112cedc@pop.xs4all.nl> Message-ID: <6c830468-f9e8-4b65-a138-f994f521986b@n38g2000prl.googlegroups.com> On Aug 23, 5:24?am, Fredrik Lundh wrote: > Michiel Overtoom wrote: > >> I have path "/this/is/path" and I wanna get "/this/is". > >> Also I want to use it as platform independent. If I want to pass "c: > >> \that\path" then I need to get "c:\that". > > > import os > > print os.path.split("/home/user/motoom")[0] > > print os.path.split("c:\\prj\\techniques\\python")[0] > > in this case, os.path.dirname() is more convenient. > > Thanks a lot! From enleverlesX.XmcX at XmclaveauX.com Sun Aug 24 00:51:47 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sun, 24 Aug 2008 06:51:47 +0200 Subject: Launch an application and continue the script's execution In-Reply-To: References: <898271.89410.qm@web37504.mail.mud.yahoo.com> Message-ID: <48b0eb42$0$854$ba4acef3@news.orange.fr> Hi ! Replace: os.startfile("launch_trace.bat") by os.startfile('start "" cmd /c launch_trace.bat') and "le tour est jou?". @-salutations -- Michel Claveau From thudfoo at opensuse.us Sun Aug 3 17:48:47 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Sun, 3 Aug 2008 14:48:47 -0700 Subject: very large dictionary In-Reply-To: References: <5c5e6d6e-04ef-4340-963f-d3825875b32c@e39g2000hsf.googlegroups.com> <6fftjvFb7ktoU2@mid.uni-berlin.de> Message-ID: <3d881a310808031448j5ade69f3k188cd7c92c8172ce@mail.gmail.com> On 3 Aug 2008 20:40:02 GMT, Jorgen Grahn wrote: > On 3 Aug 2008 20:36:33 GMT, Jorgen Grahn wrote: > > On Fri, 1 Aug 2008 01:05:07 -0700 (PDT), Simon Strobl wrote: > > ... > > >> If there is no other way to do it, I will have to learn how to use > >> databases in Python. > > > > If you use Berkeley DB ("import bsddb"), you don't have to learn much. > > These databases look very much like dictionaries string:string, only > > they are disk-backed. > > > ... all of which Sean pointed out elsewhere in the thread. > > Oh well. I guess pointing it out twice doesn't hurt. bsddb has been > very pleasant to work with for me. I normally avoid database > programming like the plague. > > 13.4 shelve -- Python object persistence A ``shelf'' is a persistent, dictionary-like object. The difference with ``dbm'' databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects -- anything that the pickle module can handle. This includes most class instances, recursive data types, and objects containing lots of shared sub-objects. The keys are ordinary strings.... [...] From timothy.grant at gmail.com Thu Aug 28 02:18:07 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Wed, 27 Aug 2008 23:18:07 -0700 Subject: Wild Card String Comparison In-Reply-To: <9kqtk.19193$cW3.1799@nlpi064.nbdc.sbc.com> References: <9kqtk.19193$cW3.1799@nlpi064.nbdc.sbc.com> Message-ID: On Wed, Aug 27, 2008 at 10:00 PM, W. eWatson wrote: > Timothy Grant wrote: >> >> On Wed, Aug 27, 2008 at 8:49 PM, W. eWatson >> wrote: >>> >>> Is it possible to do a search for a wild card string in another string. >>> For >>> example, I'd like to find "v*.dat" in a string called bingo. v must be >>> matched against only the first character in bingo, and not simply found >>> somewhere in bingo, as might be the case for "*v*.dat". >>> -- >>> Wayne Watson (Watson Adventures, Prop., Nevada City, CA) >>> >>> (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) >>> Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet >>> >>> Web Page: >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> Is this what you're looking for? >> > What's this? > ----------------- >> >> Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16) >> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin >> Type "help", "copyright", "credits" or "license" for more information. >>>>> >>>>> x = 'the quick brown fox' > > ------------------ >>>>> >>>>> 'the' in x >> >> True >>>>> >>>>> 'qui' in x >> >> True >>>>> >>>>> 'jumped' in x >> >> False >> >> If that doesn't meet your needs you may want to look at the re >> module. But if you can avoid re's your likely better off. > > re module?? >> >> > There are no wild cards in your examples. * is one wild card symbol? > begin*end means find "begin" followed by any string of characters until it > find the three letters "end". > > "begin here now but end it" should find "begin here now but end" > "beginning of the end is the title of a book" should find "beginning of the > end" > "b egin but end this now" should find nothing. > > > -- > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > Web Page: > -- > http://mail.python.org/mailman/listinfo/python-list > you definitely need the re module then. -- Stand Fast, tjg. [Timothy Grant] From gmkasi at gmail.com Tue Aug 12 06:53:58 2008 From: gmkasi at gmail.com (black) Date: Tue, 12 Aug 2008 03:53:58 -0700 (PDT) Subject: you having special Message-ID: <5d8f0d35-24f7-4416-bc6b-240500452e07@r15g2000prh.googlegroups.com> you having special open it ******************************************************************************************* http://www.AWSurveys.com/HomeMain.cfm?RefID=Maruthakasi G ************ From deets at nospam.web.de Thu Aug 14 07:11:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 14 Aug 2008 13:11:26 +0200 Subject: Fixed-length text file to database script References: Message-ID: <6gii8rFfm052U1@mid.uni-berlin.de> Stacey wrote: > Hi Guys, > > I'm new to Python (mostly) and I'm wanting to use it for a new project > I'm faced with. > > I have a machine (PLC) that is dumping its test results into a > fixed-length text file. I need to pull this data into a database > (MySQL most likely) so that I can access it with Crystal Reports to > create daily reports for my engineers. > > I've been reading the Python manual for about a week now and I'm > learning a lot. Unfortunately, I was given a deadline today that I > cannot meet without a little help. > > I need to know how to write a script that will DAILY pull this text > file into a MySQL database. > > Can anyone show me how to do this? Show us code & data, and we show you how to improve the code. Or would you be able to write the script with the above information? Diez From grahn+nntp at snipabacken.se Sun Aug 3 15:46:37 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 3 Aug 2008 19:46:37 GMT Subject: Using two pythons in an application References: Message-ID: On Sun, 03 Aug 2008 14:01:49 -0400, Allen wrote: > I'm in the process of developing an application that will use Python for > a scripting support. In light of the upcoming changes to Python, I was > wondering if it is possible to link to and use two different versions of > Python so that in the future, scripts could be migrated to the new > version, and older scripts would still work as well. If so are there > any code examples of this. I cannot answer that, sorry. But if I were you, I'd pick a current, stable Python version for my application, and stop worrying for now. If there is a new, incompatible Python version (I assume you're talking about Py3k?) these things will happen: - people around the world will decide to migrate - people will gain experience with migrating Python code - Python 2.x will start to look obsolete - things like Linux distributions and web hosting companies will stop offering Python 2.x - you will be forced (for practical reasons, or to avoid looking silly) to migrate your application (and break old scripts) All this will happen *slowly* -- I believe so slowly that you will have plenty of time to act later. And your users (or whoever has to deal with the scripts) will not be alone; lots of people will sit around migrating old Python code. (Caveat: I don't know much about the Py3k transition, just about other cases like that. Killing off an old language dialect takes time!) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From bearophileHUGS at lycos.com Sat Aug 30 13:01:25 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 30 Aug 2008 10:01:25 -0700 (PDT) Subject: Most pythonic way of weighted random selection References: Message-ID: Manuel Ebert, this may be related/useful: http://code.activestate.com/recipes/498229/ Note that numpy has a bisection method/function that are probably quite faster. Bye, bearophile From gagsl-py2 at yahoo.com.ar Tue Aug 19 23:26:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 20 Aug 2008 00:26:28 -0300 Subject: Python Query: Related to locking a resource in a multithreaded environment References: <48AB17C3.80408@gmx.de> Message-ID: En Tue, 19 Aug 2008 15:58:11 -0300, Nils Oliver Kr?ger escribi?: > My approach what be to write one class for reading and writing to the > configuration and make that class thread-safe using the RLock. > > Then you create one and only one instance of this class and let all your > threads use (not import) that one instance. > > You could achieve that "one and only one" either by having a main > program which creates the instance and pass the reference to each thread > via its __init__ or you implement the Configuration class as a singleton > like this: > > class Singleton(object): [...] >Add your methods for accessing as instance methods to this class and get > the same instance of this class in each thread by calling > Singleton.getInstance(). Singleton.getInstance() is so "javaistic"... :) Actually there is no need for all of that; just define the RLock at the global scope in a module. Don't feel bad by using a "global" name - remember that a Python module acts as a named singleton. Defining an object at module scope is equivalent to defining an instance attribute in your Singleton class. -- Gabriel Genellina From fredrik at pythonware.com Thu Aug 14 04:37:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 10:37:11 +0200 Subject: How do I organize my Python application code? In-Reply-To: References: Message-ID: Dudeja, Rajat wrote: > And my problem is that I don't have an understanding of how the code in > Python is generally organized, in case my code spans multiple files, > modules, etc. I've been using C/C++ althrough my life on Linux and > Visaul Studio, so the way their code is organized in a group of header > files, source files, etc, I'm looking for a similar way in Python way or > an approach to organize my python GUI application code? A Python program consists of a script file (the py file you run to start the program), and usually one or more additional module files (py files that you import). The latter can be organized in packages, where appropriate. There's also a search path (sys.path) that you can modify in various ways (including from within the program) if you want to fetch modules from different locations. That's all there is; there's no header files or declaration files or explicitly maintained object files etc; the program itself is just a bunch of Python files. To learn more about this, the "modules" section in the tutorial is a good start: http://docs.python.org/tut/node8.html Looking at the structure of a few existing projects might also be helpful. From benjamin.kaplan at case.edu Fri Aug 22 18:41:51 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 22 Aug 2008 18:41:51 -0400 Subject: >> and << operators? In-Reply-To: References: Message-ID: On Fri, Aug 22, 2008 at 6:30 PM, defn noob wrote: > What does >> and << do? > > Googling on them and they are just ignored... > > -- > http://docs.python.org/lib/bitstring-ops.html > > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From coolman.guron at gmail.com Sun Aug 3 02:12:27 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Sat, 2 Aug 2008 23:12:27 -0700 (PDT) Subject: why goes the time change after import statement ? References: <011a92b4-b911-4f63-9339-be46b48d5f76@v1g2000pra.googlegroups.com> <6ae5acd5-3d5d-4e81-af2f-a32a9c833122@y38g2000hsy.googlegroups.com> Message-ID: <4bcdd104-21d2-46a6-8ffa-1d3eaa46c617@a8g2000prf.googlegroups.com> On Aug 3, 1:46 am, Paul Hankin wrote: > On Aug 2, 10:35 pm, binaryjesus wrote: > > > > > hi i am working on a S3 project and facing a really weird problem! > > take a look at the following import statements and the time output > > > >>> import time > > >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) > > > 'Sat, 02 Aug 2008 20:21:56 GMT' > > > # OK > > > >>> import pygtk > > >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) > > > 'Sat, 02 Aug 2008 20:22:04 GMT' > > > # OK > > > >>> import gtk > > >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) > > > 'Sat, 02 Aug 2008 08:22:11 PM GMT' > > > # HOW THE HELL THIS HAPPEN ??? not DATE_RFC2822 format gmt time ! > > Reading the manual page for strftime --http://docs.python.org/lib/module-time.html > -- says that '%X' is the locale's appropriate time representation, so > obviously gtk is adjusting your locale. Perhaps use a formatting > string that doesn't depend on the locale: '%H:%M:%S' instead of '%X' > seems to give your preferred format. > > -- > Paul Hankin ok that explain it. but what command does gtk runs that it sets the default behaviour of strfime() to that ? From kyosohma at gmail.com Thu Aug 7 16:14:18 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 7 Aug 2008 13:14:18 -0700 (PDT) Subject: wxPython pop--up ("could not retrieve information...") References: Message-ID: On Aug 7, 1:36?pm, mistersulu wrote: > Hi all: > > I'm using a wx.ListView object with a multi-threaded wxPython app. > The list is dynamically generated and accessed across two or more > threads. ?In spite of the fact that I have checks to see if an item at > a given index is in the list and the entire set of logic is contained > within a try: except: block I periodically get pop-up windows stating > "Could not retrieve information for list control item X" when I try to > change or access the list items. > > I searched the web and groups for similar posts but can't find any > solutions. > > My question is: > > Is there a setting somewhere in wxPython to either disable these pop- > up messages or a semaphore or event locking method to enable cross- > thread access to a listview object? > > Thanks in advance, > sulu Accessing the GUI's main thread in wxPython (and most other GUI toolkits) is a no-no. wxPython does provide a few thread-safe methods, such as wx.CallAfter and wx.PostEvent. Otherwise you'll end up blocking the GUI's main thread and the GUI will become unresponsive. Check out Frank's link for one way to deal with this issue or download the wxPython demo and check the threaded demo out. http://wxpython.org/download.php Also, I recommend joining the wxPython user's mailing list. They're are a lot of nice people there and you'll learn a lot. http://wxpython.org/maillist.php Mike From gminick at nie.ma.takiego.adresu.w.sieci.pl Tue Aug 12 09:03:28 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Tue, 12 Aug 2008 13:03:28 +0000 (UTC) Subject: trying to use SOCK_RAW yields error " References: <3b701b38-9dd3-48f6-bdb0-c04fc9085008@x41g2000hsb.googlegroups.com> Message-ID: Dnia Tue, 12 Aug 2008 05:40:36 -0700 (PDT), Tzury Bar Yochay napisa?(a): Hi, > server = socket.socket(socket.AF_INET, socket.SOCK_RAW, > socket.getprotobyname('ip')) ... > Does anybody have used socket.SOCK_RAW in the past? When using SOCK_RAW, the family should be AF_PACKET, not AF_INET. Note that you need root privileges to do so. -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From wuwei23 at gmail.com Tue Aug 26 22:55:45 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 26 Aug 2008 19:55:45 -0700 (PDT) Subject: Python and database unittests References: Message-ID: <485093c5-a0f5-482e-b8fd-3cdd119020d1@r15g2000prd.googlegroups.com> Daniel wrote: > Does anyone know about a module that acts as a database stub for > python unittests? It's not database-specific, but the Mock module should help you here: http://python-mock.sourceforge.net/ There's even an example on that page for mocking a database. From mathieu.prevot at ens.fr Fri Aug 8 04:03:31 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Fri, 8 Aug 2008 10:03:31 +0200 Subject: kill thread In-Reply-To: <704879e6-1b21-4c91-99ce-f10e3866c8da@a8g2000prf.googlegroups.com> References: <704879e6-1b21-4c91-99ce-f10e3866c8da@a8g2000prf.googlegroups.com> Message-ID: <3e473cc60808080103y43a0593ev80fb7db198d55608@mail.gmail.com> 2008/8/8 Miki : > Hello, > >> I have a threading.Thread class with a "for i in range(1,50)" loop >> within. When it runs and I do ^C, I have the error [1] as many as >> loops. I would like to catch this exception (and if possible do some >> cleanup like in C pthreads) so the program finishes cleanly. Where and >> how can I do this ? in __run__ ? __init__ ? a try/except stuff ? > You can have a try/except KeyboardException around the thread code. > > HTH, > -- > Miki Of course, but I don't know where. I placed this inside loop, within called functions from the loop, I still have the problem. Mathieu From egbert.bouwman at hccnet.nl Sun Aug 3 05:26:19 2008 From: egbert.bouwman at hccnet.nl (egbert) Date: Sun, 3 Aug 2008 11:26:19 +0200 Subject: current week / weeks in year - best practice In-Reply-To: References: <6fdur9Fb0nvuU1@mid.uni-berlin.de> <2ac30ca6-554a-4b40-bdb8-a61f2311ab24@l42g2000hsc.googlegroups.com> Message-ID: <20080803092619.GA4148@hccnet.nl> On Sat, Aug 02, 2008 at 07:46:49PM -0700, Dennis Lee Bieber wrote: > > What is the meaning of ? e. -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From wuwei23 at gmail.com Fri Aug 8 03:08:03 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 8 Aug 2008 00:08:03 -0700 (PDT) Subject: benchmark References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> <4b4e4efb-4bb7-485d-a124-2e253356fca5@v1g2000pra.googlegroups.com> Message-ID: On Aug 8, 2:49?pm, Dhananjay wrote: > Is it that a question of time and effort, > or is there something that doesn't make it appropriate to python ? I don't think I've ever seen anyone who has raised concerns about the speed of python actually offer to contribute to resolving it, so I'm guessing it's the former. From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 20 05:11:29 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 20 Aug 2008 11:11:29 +0200 Subject: adding properties dynamically (how to?) In-Reply-To: <4cc8605c-9bc5-4cae-a995-7df85e683241@r15g2000prh.googlegroups.com> References: <4d8a0f68-f388-4127-b2ae-fc879690faf4@a70g2000hsh.googlegroups.com> <4cc8605c-9bc5-4cae-a995-7df85e683241@r15g2000prh.googlegroups.com> Message-ID: <48abdfb5$0$15608$426a34cc@news.free.fr> Rafe a ?crit : (snip) > > You can dynamically add properties to a class The OP was asking for *per instance* properties... > just before returning > the > instance using __new__(): > > class AClass(object): > def __new__(cls): > > setattr(cls,"propName", property(fget = ..., > fset = ..., > fdel = ..., > doc = ...) ) > > obj = super(AClass, cls).__new__(cls) > return obj Very bad idea IMHO. __new__ is called on each instanciation, which means the above code will uselessly modify the class each time you create an instance of it, overwriting the same properties again and again and again. If what you want is to automagically add properties (or whatever type of attributes) to a class and/or it's subclass, you'd be better using a custom metaclass. From bryanandedna at gmail.com Sun Aug 3 07:56:07 2008 From: bryanandedna at gmail.com (Huuuze) Date: Sun, 3 Aug 2008 04:56:07 -0700 (PDT) Subject: HELP with PIL and grainy text Message-ID: <73b859cc-50a0-4c2f-b067-bf757e7d48f8@f63g2000hsf.googlegroups.com> I could really use some help. Please take a look at the following image: http://img227.imageshack.us/img227/1346/grainynn3.png As you can see, the text in the image is fairly grainy. To get to that point, I converted an ArialBold TTF to a BDF using otf2bdf (http://crl.nmsu.edu/~mleisher/ttf2bdf.html) and then I used pilfont utility (http://www.pythonware.com/library/pil/handbook/pilfont.htm) to convert the file into a .PIL and .PBM file. I'd expect the font to be smooth, but no such luck. Any idea what could be happening here? For what it's worth, I'm using a Mac (OSX 10.5.4). Here is the PIL code as well: >> import Image, ImageDraw, ImageFont >> font = ImageFont.load("Arial.pil") >> im = Image.open("../images/image.png") >> dr = ImageDraw.Draw(im) >> dr.text((79,34), "Successfully used the Python Image Library", font=font) >> im.save("../images/grainy.png", "PNG") From pavlovevidence at gmail.com Fri Aug 15 11:03:23 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 15 Aug 2008 08:03:23 -0700 (PDT) Subject: negative numbers are not equal... References: <48A4932F.4010302@gmail.com> Message-ID: On Aug 14, 4:42?pm, Christian Heimes wrote: > Integers > between -5 and +256 are singletons as are some other objects like > strings with one element or empty tuples. Not quite. Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 'A' >>> b = "%c" % a >>> a 'A' >>> b 'A' >>> a is b False > You must not rely on the > optimization. Good advice. Carl Banks From fredrik at pythonware.com Wed Aug 13 04:27:07 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Aug 2008 10:27:07 +0200 Subject: PIL (etc etc etc) on OS X In-Reply-To: References: <489379A7.5060009@codebykevin.com> Message-ID: David C. Ullrich wrote: > Thanks. Sorry to be so dumb - yes, it's perfectly reasonable > for eff to assume that people using PIL are programmers. well, my only assumption is that people building PIL from basic building blocks must have some understanding of how that's done on their specific platform (and I don't have that knowledge myself for all platforms). And OS X can be something of a mess; search for "OS X" in the image-sig archives for a lot more on this. From steve at REMOVE-THIS-cybersource.com.au Thu Aug 14 00:34:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2008 04:34:55 GMT Subject: Using Timer or Scheduler in a Class References: Message-ID: <00b3b0f8$0$14351$c3e8da3@news.astraweb.com> Hi Justin, Does Professor Battersea know you're using his gmail account? *wink* On Wed, 13 Aug 2008 23:16:12 -0400, Prof. William Battersea wrote: > I'd like a class method to fire every n seconds. > > I tried this: > > class Timed: > def.__init__(self): > self.t = Timer(3, self.dothing) > def.start(self): > self.t.start() > > def.dothing(self): > print "Doing Thing" > > s = new Timed() > s.start() This can't be your actual code, because "s = new Timed()" gives a SyntaxError. So does "def.start(self)" etc. Also, what's Timer? > And: > > class Scheduled: > def.__init__(self): > self.s = sched.scheduler(time.time, time.sleep) > self.s.enter(3, 1, self.sync, ()) > > def.start(self): > self.t.start() > > def.dothing(self): > print "Syncing" > > s = new Scheduled() > s.start() When I fix the syntax errors and try to run the above code, I get this: AttributeError: Scheduled instance has no attribute 'sync' That's only the first of a number of errors. You waste our time when you post code that doesn't run. Very few people will bother spending the time and effort to fix your code if you don't respect their time, and those that do will rub your nose in the fact that you're wasting their time. > Both run once and end. I'm obviously missing something here. Let's start with some code that actually does run: >>> class Scheduled: ... def __init__(self): ... self.s = sched.scheduler(time.time, time.sleep) ... self.s.enter(3, 1, self.dothing, ()) ... def start(self): ... self.s.run() ... self.s.enter(3, 1, self.dothing, ()) ... self.start() ... def dothing(self): ... print "Syncing" ... >>> s = Scheduled() >>> s.start() Syncing Syncing Syncing Traceback (most recent call last): File "", line 1, in File "", line 8, in start File "", line 8, in start File "", line 8, in start File "", line 6, in start File "/usr/lib/python2.5/sched.py", line 108, in run delayfunc(time - now) KeyboardInterrupt This will run until you interrupt it (as I did) or you run out of space on the stack due to recursion. I imagine this is probably not the best way to do what you want. Hint for further explorations: the scheduler keeps a queue of events. If the queue becomes empty, it stops. You only need to restart the scheduler with run() if it stopped, otherwise it keeps going. -- Steven From thomasmallen at gmail.com Wed Aug 13 15:46:33 2008 From: thomasmallen at gmail.com (tmallen) Date: Wed, 13 Aug 2008 12:46:33 -0700 (PDT) Subject: An FTP Client...My first real program! References: <228e4214-01cf-4152-acdb-3743594f0581@e53g2000hsa.googlegroups.com> Message-ID: <89beabc9-52e2-46ea-9e6d-da5ca77bfafe@x35g2000hsb.googlegroups.com> On Aug 13, 3:27?pm, tmallen wrote: > Here's the code:http://pastebin.com/m21dfcc19 > > What could be improved? The script feels clumsy, and I have no > experience refactoring Python code. This will eventually be a GUI FTP > client. I'm mainly looking for design advice... Note that all it does right now is store account info and connect to the host, listing the contents of the pwd. Anonymous connections work, and the script is functionally sound. From tjreedy at udel.edu Mon Aug 25 12:36:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 25 Aug 2008 12:36:09 -0400 Subject: Python String Immutability Broken! In-Reply-To: <48B28F7A.9030006@seehart.com> References: <000b01c906f1$a493bb80$0d00a8c0@hendrik> <48B28F7A.9030006@seehart.com> Message-ID: Ken Seehart wrote: > Hendrik van Rooyen wrote: >> >> ... >> >> Actually, I am not complaining - I am asking for advice on the side >> effects of what I am doing, which is replacing a bunch of bits >> in what is essentially an output bit field with the corresponding >> input bits at the same addresses read back from a simulated i/o >> bus structure. And I would also like to know if there is a better >> way of doing this. >> > Yes, there is a better way. Use a character array instead of a string. > > http://python.net/crew/theller/ctypes/tutorial.html#arrays Which essentially is the bytearray type of 3.0. From luismi2050 at yahoo.es Tue Aug 26 11:25:53 2008 From: luismi2050 at yahoo.es (luismi) Date: Tue, 26 Aug 2008 08:25:53 -0700 (PDT) Subject: python portable installation? Message-ID: <00a851cf-4ca7-4d7e-b116-b3eda7b6a092@k36g2000pri.googlegroups.com> Hi, I have searched the online manuals, faqs and forums, but i haven't found a satisfactory explanation ... most probably my fault ;) I have found 2 projects, one commercial and another free, that deal with the installation and running of python code on portable/removable devices, my questions are: (1) Is this scenario not yet contemplated in the official releases, and (2) Why is such a big issue? Will appreciate your comments, Thanks in advance Luismi From riccardo at infis.univ.trieste.it Sat Aug 2 11:25:28 2008 From: riccardo at infis.univ.trieste.it (Riccardo Di Meo) Date: Sat, 02 Aug 2008 17:25:28 +0200 Subject: embedded python doesn't like socket.accept() and SegFaults Message-ID: <48947C68.7030604@infis.univ.trieste.it> Hi everyone, I'm practicing with embedding python into C code and i have encountered a very strange problem: I'm unable to call the "accept" method of a (correctly created) server socket without receiving a "Segmentation fault" (inside the PyObject_CallMethod). My code to be correct (at least it's correct enough for me to call .getsockname(), .fileno() and other methods without problems), I'm pretty new to this thing though, therefore I'm confident I'm doing something very dumb. Here is the C code: ------ extending.c #include PyObject *new_server(long port) { PyObject *pName,*pModule; PyObject *pFunction,*pArg; PyObject *pTuple,*pValue; // Import the module pName = PyString_FromString("extending"); pModule = PyImport_Import(pName); Py_DECREF(pName); // Get the function pFunction = PyObject_GetAttrString(pModule, "server_socket"); // Module not needed anymore Py_DECREF(pModule); // Build the arguments pArg=PyInt_FromLong(port); pTuple=PyTuple_New(1); PyTuple_SET_ITEM(pTuple,0,pArg); // Call the function pValue = PyObject_CallObject(pFunction, pTuple); // Release the references Py_DECREF(pFunction); Py_DECREF(pTuple); if(pValue==NULL) printf("Error: server socket not created!\n"); return pValue; } PyObject *accept(PyObject *server) { PyObject *pValue; // Code fails here (it does NOT return NULL: just crashes!) // Note that other calls work fine (e.g. fileno, getsockname ecc) pValue = PyObject_CallMethod(server, "accept", NULL); return pValue; } int main(int argc,char *argv[]) { PyObject *server,*connection; // Boot python Py_Initialize(); PySys_SetArgv(argc, argv); // Create the server server=new_server(23000); // Print it PyObject_Print(server,stderr,0); fprintf(stderr,"\n"); // Wait for a connection connection=accept(server); // See what we got PyObject_Print(connection,stderr,0); fprintf(stderr,"\n"); // We are done, hint the gc. Py_DECREF(connection); Py_DECREF(server); Py_Finalize(); return 0; } ---------- and this is the python script: ---------- extending.py import socket def server_socket(port): s=socket.socket() s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True) s.bind(("0.0.0.0",port)) s.listen(10) return s ------------ as already mentioned, replacing the "accept" string with "fileno" or something else doesn't crash the interpreter. Another thing worth mentioning, is that even inserting a s.accept() call in the python script (before the return) makes the bug appear (it doesn't seems related to my use of the PyObject_CallMethod function, then). I have tried posting the problem in IRC, searching google (no good matches) and debugging the code (however I'm afraid i don't have the python-lib with debugging syms. compiled in, therefore it was quite a useless attempt...). Any help about the code would be appreciated (even unrelated to the issue at hand: im quite new to this "embedding thing" and therefore i gladly accept hints). Thank you for your attention, Riccardo Di Meo PS: I'm also new to Usenet: is it fine to post the code in the body of the mail as i did (since it was small, i dared: however I'd like to know the correct etiquette)? From straton at lampsacos.demon.co.uk Fri Aug 29 05:09:20 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 29 Aug 2008 10:09:20 +0100 Subject: [1,2,3] exactly same as [1,2,3,] ? In-Reply-To: References: Message-ID: mh at pixar.com wrote: > x=[1,2,3] > and > x=[1,2,3,] > > are exactly the same, right? > > I'm generating some python data, and it's less error prone > to not treat the last element specially, but I want to be > sure I'm generating an equivalent data structure. > > Many TIA! > Mark > >>> x=[1,2,3,] >>> repr(x) [1,2,3] From paulo.jpinto at gmail.com Tue Aug 5 10:21:00 2008 From: paulo.jpinto at gmail.com (paulo.jpinto at gmail.com) Date: Tue, 5 Aug 2008 07:21:00 -0700 (PDT) Subject: interpreter vs. compiled References: <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <4rl294duo83eujnq6tjbk215mavpl87o9r@4ax.com> <43f519dd-6763-4cc0-a6d2-1e671da54c2c@d45g2000hsc.googlegroups.com> <1fdd10ae-581c-428d-9268-8fca8b99aff4@2g2000hsn.googlegroups.com> Message-ID: <5f742714-1d29-467e-82fe-d88253542657@79g2000hsk.googlegroups.com> On Aug 3, 1:26?am, castironpi wrote: > On Aug 2, 2:02 pm, Tim Roberts wrote: > > > castironpi wrote: > > > >And furthermore, I think I'm getting > > >confused about what exactly constitutes an interpreter: it is whether > > >there is a process that runs product instructions, or the product > > >instructions can run standalone. ?I would take 'compiler' to mean, > > >something that outputs an .EXE executable binary file, and I don't > > >just mean bundling up the python.exe executable with a file. > > > OK, let me give MY definition. ?I freely grant that my definition might be > > different from anyone elses, but perhaps this will help you understand the > > basis for my arguments. > > I understand that we're having a disagreement about terminology. ?I > further don't understand exactly what JIT languages are, so I can't > agree on that either. > > I will observe the certain amount of corporate hype behind, and worker > base morale riding on, the notion that JIT technology compiles code. > I suspect it's an exaggeration, not outright false, but I can't prove > it until I tell you what instructions run, one right after another, on > a concrete architecture I've held in my hand, like the x86 die. ?Nor > can I thoroughly believe that it's true either, though, until its > creators have told me what instructions they are. ?So I'll proclaim > ignorance and await facts... or consistent stories about them. > > > If I run three different CPython programs, the bytes of machine language > > that get executed are come from the same place: python24.dll. ?My user > > programs are just data. ?That, in my mind, makes the CPython implementation > > an interpreter. > > > If I compile and run three different C programs, the bytes of machine > > language will be come from three different places. ?That, in my mind, makes > > my C implementation a compiler. > > True. ?I agree on the facts and the terms. > > > If I compile and run three different C# programs, the JIT compiler makes > > new machine language for each one. ?The bytes of machine language will come > > from three different places. ?That, in my mind, makes the C# implementation > > a compiler. > > > If I compile and run three different IronPython programs, the JIT compiler > > makes new machine language for each one. ?The bytes of machine language > > will come from three different places. ?That, in my mind, makes the > > IronPython implementation a compiler. > > I don't know enough to attest to these for a fact, and you haven't > given enough details to corroborate them as facts. ?But when you do, > I'll be able to take and learn your terms for them (not that I will, > of course, but I can). > > > All four of those scenarios require run-time library support. ?Even the C > > progam does not run on its own. > > I disagree with this, if the C program is statically linked -- the OS > copies the binary (.EXE) from disk into memory, then jumps to a > specific offset in that block / address space. ?It runs all its own > bytes, then jumps back to an OS-specified point of return of control. > For the other three, though, this is true. > > > Execution starts in the run-time library, > > which sets up an environment before jumping to "main". ?The C# and > > IronPython situations are the same; it's just that there's more processing > > going on before jumping to "main". > > I want to give a concrete example of 'generating machine code' per se > (as such). > > I run this program: > > bin= open( 'abinary.exe', 'w' ) > bin.write( '\x09\x0f\x00\x00' ) > for x in range( 10 ): > ? ?bin.write( '\x04\xA0' + chr( x ) + '\x00' ) > bin.write( '\x01\x20\x00\x00' ) > > It outputs to 'abinary.exe': > > \x09\x0f\x00\x00 > \x04\xa0\x00\x00 > \x04\xa0\x01\x00 > \x04\xa0\x02\x00 > \x04\xa0\x03\x00 > \x04\xa0\x04\x00 > \x04\xa0\x05\x00 > \x04\xa0\x06\x00 > \x04\xa0\x07\x00 > \x04\xa0\x08\x00 > \x04\xa0\x09\x00 > \x01\x20\x00\x00 > > Which is 12 bytes long and runs in a millisecond. ?What it does is set > a memory address to successive integers 0..9, then yields. ?Due to the > nature of program flow control, while it runs its first steps on any > x86 machine, the yield only succeeds if on Windows 98+, and crashes > the machine, or otherwise loses control if not. ?(That part depends on > those OSses.) > > I can try something similar dynamically. > > char* mem= alloc( 48 ) > setpermission( mem, EXECUTE ) > memcpy( mem+ 0, "\x09\x0f\x00\x00", 4 ) > for( int x= 0; x< 10; ++x ) { > ? ?memcpy( mem+ 4* (x+ 1 ), '\x04\xA0\x00\x00', 4 ) > ? ?mem[ 4* (x+ 1 )+ 3 ]= (char) x > memcpy( mem+ 44, '\x01\x20\x00\x01', 4 ) > setjump > goto mem > > Which with some imagination produces the contents of 'abinary.exe' > above (one difference, last word) in a memory block, at address 'mem', > then jumps to it, which then jumps back, and then exits. > > I'll compare a C complation to the first example, 'abinary.exe', and a > JIT compilation to the second example, 'char* mem'. ?If the comparison > isn't accurate, say how, because these are places I can start from... > (yes, that is, instead of just repeating the claims). > > When does a JIT do this, and what does it do in the meantime? The JIT works like an assembler/linker that writes to memory. It will load the file(s) containing the bytecode and generate the required assembly instructions into memory. In the case there are dependencies to other modules, they will be loaded as well, and compiled. Then the linker will take care that cross references between modules are correct, like memory addresses and branch targets. A clever JIT might add instrumentation points, so that it can rewrite the code using profile guided optimizations, this means generating optimized code using as input the program behaviour. This makes JIT code usually faster than normal compiled code. Although normal native code is able to start executing faster, it only targets a specific set of processors. JIT code is independent of the processor, and a good JIT implementation is able to explore the processor better than a direct native compiler. There is however the time penalty on program startup. -- Paulo From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 13 08:40:24 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 13 Aug 2008 14:40:24 +0200 Subject: You advice please In-Reply-To: References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> Message-ID: <48a2d62b$0$3732$426a74cc@news.free.fr> ?lvaro G. Vicario a ?crit : > Hussein B escribi?: >> The sad fact (at least to me), Ruby is getting a lot of attention >> these days. >> Why Python isn't getting this attention although is a much more mature >> language and it is used by many big, big names? >> And do I dare to say it is much more charming? > > The opinion of a PHP developer who's playing with Python as well: > > I've come across Python almost everywhere. Many programs I use (or I've > evaluated) are written in Python or use it for scripting: source control > software (Subversion, Bazaar, Mercurial), IDEs (Komodo Edit), popular > web applications (Zope, Trac)... If you're looking for a script for > admin tasks your search results will probably contain something in > Python. If you want to build a Firefox extension you'll find a *.py file > sitting around. > > But I've never came across a Ruby app. Sure, I know Ruby exists and > people are very enthusiastic about it (though they often mistake it with > Ruby on Rails), but that's all. Redmine is a nice alternative to Trac. And Twitter is certainly a well-known app too. (Yes, RoR apps in both cases...). > Ruby is popular among bloggers but I'm not sure whether it's popular > among developers. Almost as much as Python, I'd say. But both languages fight for the same niches in languages/techno ecosystem, and Python, being older, tend to get more visibility. From vedrandekovic at yahoo.com Thu Aug 7 03:25:10 2008 From: vedrandekovic at yahoo.com (vedrandekovic at yahoo.com) Date: Thu, 7 Aug 2008 00:25:10 -0700 (PDT) Subject: .cpp to .pyd Message-ID: Hello, I want to build my C++ (.cpp) script to (.pyd) like this: http://en.wikibooks.org/wiki/Python_Programming/Extending_with_C%2B%2B I have installed "Microsoft Visual studio .NET 2003" and "Boost Python" and then after I run my setup script: python setup.py build I get this error: running build running build_ext building 'hello' extension D:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\cl.exe /c / nologo /Ox /MD /W3 /GX /DNDEBUG -IC:\Panda3D-1.5.2\python\include -IC: \Panda3D-1.5.2\pytho n\PC /Tphellomodule.cpp /Fobuild\temp.win32-2.5\Release \hellomodule.obj hellomodule.cpp hellomodule.cpp(9) : fatal error C1083: Cannot open include file: 'boost/python/ module.hpp': No such file or directory error: command '"D:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\cl.e xe"' failed with exit status 2 I think that my MS visual studio cannot find "boost python", if that's the problem then can you tell me how can I solve it. This is very begginer question,but I can't find answer nowhere, and I don't have any expirience with Microsoft products. Sorry for my bad english! Regards, Veki From __peter__ at web.de Wed Aug 27 13:35:51 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 27 Aug 2008 19:35:51 +0200 Subject: finding out the number of rows in a CSV file [Resolved] References: <3aaa109e-9a7e-4d02-8af5-0161251d7678@t54g2000hsg.googlegroups.com> <0bc6097f-af52-4951-a413-e9a983df93c7@79g2000hsk.googlegroups.com> Message-ID: John S wrote: > [OP] Jon Clements wrote: >> On Aug 27, 12:54 pm, SimonPalmer wrote: >>> after reading the file throughthe csv.reader for the length I cannot >>> iterate over the rows. How do I reset the row iterator? > > A CSV file is just a text file. Don't use csv.reader for counting rows > -- it's overkill. You can just read the file normally, counting lines > (lines == rows). Wrong. A field may have embedded newlines: >>> import csv >>> csv.writer(open("tmp.csv", "w")).writerow(["a" + "\n"*10 + "b"]) >>> sum(1 for row in csv.reader(open("tmp.csv"))) 1 >>> sum(1 for line in open("tmp.csv")) 11 Peter From sjmachin at lexicon.net Fri Aug 22 18:22:26 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 22 Aug 2008 15:22:26 -0700 (PDT) Subject: codecs, csv issues References: <8aafd67e-6633-4371-a880-805d07089400@k37g2000hsf.googlegroups.com> Message-ID: <12c6f5a0-544f-4121-a520-28de61b08a8a@v16g2000prc.googlegroups.com> On Aug 22, 11:52 pm, George Sakkis wrote: > I'm trying to use codecs.open() and I see two issues when I pass > encoding='utf8': > > 1) Newlines are hardcoded to LINEFEED (ascii 10) instead of the > platform-specific byte(s). > > import codecs > f = codecs.open('tmp.txt', 'w', encoding='utf8') > s = u'\u0391\u03b8\u03ae\u03bd\u03b1' > print >> f, s > print >> f, s > f.close() This is documented behaviour: """ Note Files are always opened in binary mode, even if no binary mode was specified. This is done to avoid data loss due to encodings using 8- bit values. This means that no automatic conversion of '\n' is done on reading and writing. """ From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 27 07:32:26 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 27 Aug 2008 13:32:26 +0200 Subject: Decorators using instance variables In-Reply-To: References: Message-ID: <48b53b13$0$1052$426a74cc@news.free.fr> Robert Kaplan a ?crit : > > > Bruno Desthuilliers a ?crit : > > <...> > >> 2/ don't bother reading anything from someone named 'castironpi', it's >> one of our currently active resident troll, and he is worse than >> clueless. >> > > Actually, I found his response to the point, his sample code helpful, > and his solution similar to yours. This _sometimes_ happens, yes, and that's why you just shouldn't trust him : unless you have a good knowledge of the topic, you just can't tell whether his answer is ok or total rubbish. From deets at nospam.web.de Fri Aug 29 12:59:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 29 Aug 2008 18:59:53 +0200 Subject: Python graphics question:pixel scrolling References: Message-ID: <6hqo8vFnnqcjU1@mid.uni-berlin.de> Raymond Luxury-Yacht wrote: > To learn python, I've been trying to write a simple graphics program > which displays a 1D cellular automaton's evolution. The last time I > wrote this program, it was in C for a CGA adaptor (!) in which the > display was mapped to two interlaced blocks of memory, and scrolling > up two lines of pixels was very simple and very smooth. The code > below works, and uses pygame for the graphics. But the scrolling is > quite flickery when using large windows. I'm sure that the code > contains various neophyte python errors, and I'd appreciate any > comments on that, but my main question is how I ought to have coded it > in order to have the scrolling be smooth. I did see a comment on a > pygame site saying that pygrame should not be used for side-scrollers, > to which this is similar. Is there a better way with python? You need to to double-buffering. Just as in the old days... http://www.pygame.org/docs/tut/intro/intro.html Look for pygame.display.flip() Diez From gminick at bzt.bzt Wed Aug 20 11:22:16 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 20 Aug 2008 15:22:16 +0000 (UTC) Subject: subprocess seems to "detach" / ignore wait() References: Message-ID: On Wed, 20 Aug 2008 15:09:11 +0200, Mathieu Prevot wrote: > flog = open(logfile, 'w') > fpid = open(pidfile, 'w') > try: > child = Popen(cmd.split(), stderr=flog) > print "Server running [PID %s]"%(child.pid) > fpid.write(child.pid) What happens if you change: fpid.write(child.pid) into: fpid.write('%d\n' % (child.pid)) I think that the problem here is that fpid.write() fails silently (probably TypeError), because it takes string as its first argument, not integer. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From mensanator at aol.com Sat Aug 9 11:19:07 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 9 Aug 2008 08:19:07 -0700 (PDT) Subject: How to round a floating point to nearest 10? References: Message-ID: On Aug 9, 6:31?am, Will Rocisky wrote: > I want my 76.1 to be rounded to decimal 80 and 74.9 to decimal 70. > How can I achieve that? >>> print '%.0e' % 74.9 7e+01 >>> print '%.0e' % 76.1 8e+01 From lists at cheimes.de Tue Aug 5 19:09:19 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 06 Aug 2008 01:09:19 +0200 Subject: Finding IP address of localhost via socket API (or other API) In-Reply-To: <38c9cdb10808051450q3912f70evdae9fd61950e09d2@mail.gmail.com> References: <38c9cdb10808051450q3912f70evdae9fd61950e09d2@mail.gmail.com> Message-ID: David York wrote: > How do I find out my machine's IP address as visible to the outside world? > Thanks a lot. Most modern routers home routers support the IGD part of UPnP (http://en.wikipedia.org/wiki/Internet_Gateway_Device_Protocol). You can use an UPnP client software to query the router for its WAN IP, connection state and upload / download speed. You may even be able to modify the port forwarding rules with UPnP. I suggest Miniupnpc, because it has nice Python bindungs. Another option is dyndns.org. You can register a new DDNS host, update it with a DDNS client and then query the IP with socket.gethostbyname(). Most modern routers have a builtin DDNS client, too. Christian From Edwin.Madari at VerizonWireless.com Wed Aug 6 22:21:38 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Wed, 6 Aug 2008 22:21:38 -0400 Subject: A question about string and float number In-Reply-To: Message-ID: <20080807022149.088391E400D@bag.python.org> type(s) == type(float()) -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org]On Behalf Of Wei Guo Sent: Wednesday, August 06, 2008 9:23 PM To: python-list at python.org Subject: A question about string and float number Hi all, I am new of python. Could anyone help me a question as below? Is there any function that can judge a string s is a float number or not? FOr example, if s = '1.232' or s='1e+10', then it returns true, otherwise, it will return false. isdigit() in string doesn't work. float() will throw an exception and I just need true or false as result. Thanks a lot in advance, Wei The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From danielk at featherbrain.net Sat Aug 9 08:42:53 2008 From: danielk at featherbrain.net (Daniel Klein) Date: Sat, 09 Aug 2008 08:42:53 -0400 Subject: How to round a floating point to nearest 10? References: Message-ID: On Sat, 9 Aug 2008 04:31:38 -0700 (PDT), Will Rocisky wrote: >I want my 76.1 to be rounded to decimal 80 and 74.9 to decimal 70. >How can I achieve that? >>> for n in (74.9, 76.1): print int((n+5)/10)*10 70 80 Dan From lfrogerscobalt at gmail.com Tue Aug 26 20:10:07 2008 From: lfrogerscobalt at gmail.com (Albertos) Date: Tue, 26 Aug 2008 17:10:07 -0700 (PDT) Subject: Free huge source codes collection Message-ID: Hello, I've collected huge source codes collection of any kinds : work with text files, database, GUI etc. You can download it here http://freactor.com/get.php?file=Python From bdesth.quelquechose at free.quelquepart.fr Tue Aug 19 14:51:20 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 19 Aug 2008 20:51:20 +0200 Subject: AOP in Python In-Reply-To: References: Message-ID: <48ab321a$0$28448$426a74cc@news.free.fr> Hussein B a ?crit : > Hey, > AOP is build in Groovy language via many means, does Python support > AOP out of the box without the need for such tools: > http://pythonsource.com/open-source/aspect-oriented-frameworks > Thanks. See the use of @decorators in most Python frameworks. When functions are first-class citizens, "AOP" starts to look like a kludgy workaround... From steve at REMOVE-THIS-cybersource.com.au Wed Aug 20 14:04:37 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2008 18:04:37 GMT Subject: Bizarre method keyword-arg bug. References: <73104fb9-3f05-445e-83e6-2b1939316f15@d77g2000hsb.googlegroups.com> <00b981ba$0$20315$c3e8da3@news.astraweb.com> Message-ID: <00bc578e$0$20315$c3e8da3@news.astraweb.com> On Wed, 20 Aug 2008 13:09:21 -0400, Robert Brown wrote: > In any case, chances are high that Lisp's way of handling default > arguments would have been changed had it been shown to cause performance > problems. But nobody is suggesting that it would cause performance problems in *Lisp*. It might, or it might not. Who cares? We're not talking about Lisp, we're talking about *Python*, and evaluating default arguments every time the function is called would certainly cause a performance hit in Python. -- Steven From grante at visi.com Fri Aug 29 10:45:00 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 29 Aug 2008 09:45:00 -0500 Subject: [1,2,3] exactly same as [1,2,3,] ? References: Message-ID: On 2008-08-29, Roy Smith wrote: > Exactly. This is one of those little pieces of syntactic > sugar which makes python so nice to work with. The > alternative is (in C, for example) abominations like this: > > const char* l[] = {"foo" > , "bar" > , "baz" > }; > > and even those are not quite as good because you still have to > special-case the first entry. It's probably a spec violation, but I've never seen a C compiler that objected to a comma after the last item in an initializer list. (At least not at the warning levels I use, which tend to be on the picky side.) -- Grant Edwards grante Yow! There's enough money at here to buy 5000 cans of visi.com Noodle-Roni! From ken at seehart.com Mon Aug 25 06:54:50 2008 From: ken at seehart.com (Ken Seehart) Date: Mon, 25 Aug 2008 03:54:50 -0700 Subject: Python String Immutability Broken! In-Reply-To: <000b01c906f1$a493bb80$0d00a8c0@hendrik> References: <000b01c906f1$a493bb80$0d00a8c0@hendrik> Message-ID: <48B28F7A.9030006@seehart.com> Hendrik van Rooyen wrote: > > ... > > Actually, I am not complaining - I am asking for advice on the side > effects of what I am doing, which is replacing a bunch of bits > in what is essentially an output bit field with the corresponding > input bits at the same addresses read back from a simulated i/o > bus structure. And I would also like to know if there is a better > way of doing this. > Yes, there is a better way. Use a character array instead of a string. http://python.net/crew/theller/ctypes/tutorial.html#arrays > ... - Ken From richardjones at optushome.com.au Sun Aug 31 22:51:45 2008 From: richardjones at optushome.com.au (Richard Jones) Date: Mon, 1 Sep 2008 12:51:45 +1000 Subject: Roundup Issue Tracker version 1.4.6 released Message-ID: <200809011251.46126.richardjones@optushome.com.au> I'm proud to release version 1.4.6 of Roundup. 1.4.6 is a bugfix release: - Fix bug introduced in 1.4.5 in RDBMS full-text indexing - Make URL matching code less matchy If you're upgrading from an older version of Roundup you *must* follow the "Software Upgrade" guidelines given in the maintenance documentation. Roundup requires python 2.3 or later for correct operation. To give Roundup a try, just download (see below), unpack and run:: roundup-demo Release info and download page: http://cheeseshop.python.org/pypi/roundup Source and documentation is available at the website: http://roundup.sourceforge.net/ Mailing lists - the place to ask questions: http://sourceforge.net/mail/?group_id=31577 About Roundup ============= Roundup is a simple-to-use and -install issue-tracking system with command-line, web and e-mail interfaces. It is based on the winning design from Ka-Ping Yee in the Software Carpentry "Track" design competition. Note: Ping is not responsible for this project. The contact for this project is richard at users.sourceforge.net. Roundup manages a number of issues (with flexible properties such as "description", "priority", and so on) and provides the ability to: (a) submit new issues, (b) find and edit existing issues, and (c) discuss issues with other participants. The system will facilitate communication among the participants by managing discussions and notifying interested parties when issues are edited. One of the major design goals for Roundup that it be simple to get going. Roundup is therefore usable "out of the box" with any python 2.3+ installation. It doesn't even need to be "installed" to be operational, though a disutils-based install script is provided. It comes with two issue tracker templates (a classic bug/feature tracker and a minimal skeleton) and four database back-ends (anydbm, sqlite, mysql and postgresql). From timr at probo.com Sat Aug 2 15:07:19 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 02 Aug 2008 19:07:19 GMT Subject: Newbie Python questions References: <12p2941fee0nnimqmraqt9cm1vml7ra2kt@4ax.com> <706f52bb-c206-4021-9a2f-2e52f6e3429b@u6g2000prc.googlegroups.com> Message-ID: binaryjesus wrote: > >One great open source GUI package that you left out is GTK ie. pygtk. >i cant compare it with wx as i have never used it but isay its much >better than QT. > >Anyway for ur q if u want to compair qt n wx. QT should be faster coz >it has a better documentation. Holy moly, did you send this from your cell phone? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From deets at nospam.web.de Wed Aug 27 05:06:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 27 Aug 2008 11:06:27 +0200 Subject: Inspecting the Instance Vars in a class/object - How? References: <1efcc029-17cc-4d5e-b70b-2a2e25dfd214@k36g2000pri.googlegroups.com> Message-ID: <6hkjpiFmjjevU1@mid.uni-berlin.de> BrendanC wrote: > I'm trying to understand reflection/introspection in Python. How can I > identify the the type of attribute (e.g. instance var) in a class? > The following returns all the class attributes (methods and instance > vars). > > However I'm interested in identifying the type of value for each case > - (e.g. I'd like to identify the instance variables separately). (The > Inspect module has an ismethod method, but not an isinstancevariable > method). Because there is no such thing, as it is not a *type*. It's a question on where the value is stored. Every *instance* has a dictionary holding it's data. You can normally access it using __dict__. But it's not "pure" in the sense that only the variables you created yourself are contained. It also contains the reference to the class. On the class, there is also a __dict__, which contains the method-descriptors and class-variables. In the face of multi-inheritance, things get even more complicated, as then the values are acquired through MRO-lookup. > e.g. In the following example I'd like to extract the class vars > strvar and intNum and ignore the methods/other attribute types. > > What is the best way to do this? > > class test: > # Dummy Class for reflection testing > strVar = '1234' > intNum = 0 > > def nullmethod(): > pass > > def addmethod(self,v1, v2): > v = v1 + v2 > return v > > if __name__ == "__main__": > mytest = test() > for key in dir(mytest): > value = getattr(object, key) > print 'Key: %s ; Value %s ' % (str(key) ,str(value)) if name in mytest.__dict__: print "instance variable" From ptmcg at austin.rr.com Mon Aug 18 10:59:07 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 18 Aug 2008 07:59:07 -0700 (PDT) Subject: Good python equivalent to C goto References: <48a744b6$0$299$7a628cd7@news.club-internet.fr> Message-ID: On Aug 17, 1:09?pm, Matthew Fitzgibbons wrote: > Kurien Mathew wrote: > > Hello, > > > Any suggestions on a good python equivalent for the following C code: > > > while (loopCondition) > > { > > ? ? if (condition1) > > ? ? ? ? goto next; > > ? ? if (condition2) > > ? ? ? ? goto next; > > ? ? if (condition3) > > ? ? ? ? goto next; > > ? ? stmt1; > > ? ? stmt2; > > next: > > ? ? stmt3; > > ? ? stmt4; > > ?} > > > Thanks > > Kurien > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I would not be too happy if I saw C code like that in my repository. > This is equivalent: > > while (loopCondition) { > ? ? ?if (!(condition1 || condition2 || condition3)) { > ? ? ? ? ?stmt1; > ? ? ? ? ?stmt2; > ? ? ?} > ? ? ?stmt3; > ? ? ?stmt4; > > } > > In Python: > > while (loopCondition): > ? ? ?if not (condition1 or condition2 or condition3): > ? ? ? ? ?stmt1 > ? ? ? ? ?stmt2 > ? ? ?stmt3 > ? ? ?stmt4 > > If stmt3 and stmt4 are error cleanup code, I would use try/finally. > > while loopCondition: > ? ? ?try: > ? ? ? ? ?if condition1: > ? ? ? ? ? ? ?raise Error1() > ? ? ? ? ?if condition2: > ? ? ? ? ? ? ?raise Error2() > ? ? ? ? ?if condition3: > ? ? ? ? ? ? ?raise Error3() > ? ? ? ? ?stmt1 > ? ? ? ? ?stmt2 > ? ? ?finally: > ? ? ? ? ?stmt3 > ? ? ? ? ?stmt4 > > This will also bail out of the loop on and exception and the exception > will get to the next level. If you don't want that to happen, put an > appropriate except block before the finally. > > -Matt- Hide quoted text - > > - Show quoted text - Close, but there is no reason for the conditions to raise anything, they can just use the continue statement: i = 20 while i > 0: try: if i % 2: continue if i % 3: continue print i, "is even and a multiple of 3" finally: i -= 1 Prints: 18 is even and a multiple of 3 12 is even and a multiple of 3 6 is even and a multiple of 3 I think this is closest to the OP's stated requirements. -- Paul From fredrik at pythonware.com Sat Aug 23 18:28:55 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 24 Aug 2008 00:28:55 +0200 Subject: dropwhile question In-Reply-To: References: <84bdef3c0808231454v3e6f347eucae1f7abeabe193d@mail.gmail.com> Message-ID: Fredrik Lundh wrote: > maybe you meant to use itertools.ifilter? > > >>> help(itertools.ifilter) > Help on class ifilter in module itertools: > > class ifilter(__builtin__.object) > | ifilter(function or None, sequence) --> ifilter object > | > | Return those items of sequence for which function(item) is true. > | If function is None, return the items that are true. > > >>> list(itertools.ifilter(lambda x: x<5,range(10))) > [0, 1, 2, 3, 4] > >>> list(itertools.ifilter(lambda x: 2 [3, 4] or, more likely, ifilterfalse: >>> list(itertools.ifilterfalse(lambda x: x<5,range(10))) [5, 6, 7, 8, 9] >>> list(itertools.ifilterfalse(lambda x: 2 From jr9445 at ATT.COM Wed Aug 6 14:01:49 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Wed, 6 Aug 2008 13:01:49 -0500 Subject: Monitor and compare two log files in real time In-Reply-To: <6f11115b-6f19-4ca4-97e6-0a0781ed617c@b30g2000prf.googlegroups.com> References: <6f11115b-6f19-4ca4-97e6-0a0781ed617c@b30g2000prf.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of m > Sent: Wednesday, August 06, 2008 1:25 PM > To: python-list at python.org > Subject: Monitor and compare two log files in real time > > I have a script I would like to write but I am not sure of where to > start / approach. Perhaps someone could help direct me in the right > direction. Any advice is appreciated. > > I would like to write a python script that monitors two log files. > If a certain string, lets say string1 shows up in logfile-A, I want to > check if that same string shows up in log file-B within 8 minutes. If > it does not show up within 8 minutes, send an email ( using sendmail > or postfix). > > Do you have any suggestions? > -- Google on "python tail" to get a python implementation of the unix tail command. The rest should be easy. http://code.activestate.com/recipes/157035/ ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA622 From mtobis at gmail.com Sun Aug 31 23:03:04 2008 From: mtobis at gmail.com (Michael Tobis) Date: Sun, 31 Aug 2008 20:03:04 -0700 (PDT) Subject: How Compute # of Days between Two Dates? References: Message-ID: <28c7258c-4522-4fce-b68e-1fa0cf227237@a70g2000hsh.googlegroups.com> from datetime import datetime # batteries included today = datetime.now() xmas = datetime(today.year,12,25) if (xmas - today).days > 1: print "%d days until Christmas" % (xmas - today).days else: print "Merry Christmas!" From jeremy+complangpython at jeremysanders.net Fri Aug 8 08:43:08 2008 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Fri, 08 Aug 2008 13:43:08 +0100 Subject: random numbers according to user defined distribution ?? References: Message-ID: Alex wrote: > I wonder if it is possible in python to produce random numbers > according to a user defined distribution? > Unfortunately the random module does not contain the distribution I > need :-( Have you looked at the numpy random number module? It seems to have quite a lot of distributions. See help(numpy.random). Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From saptarshi.guha at gmail.com Sat Aug 16 23:31:02 2008 From: saptarshi.guha at gmail.com (sapsi) Date: Sat, 16 Aug 2008 20:31:02 -0700 (PDT) Subject: sqlite empty inserts References: <9c28ccd0-ba04-4e21-8cbb-ff8959c4801e@m44g2000hsc.googlegroups.com> <72373c22-33dc-45dd-aea7-b31e36ac6169@b1g2000hsg.googlegroups.com> Message-ID: <2b8a6d90-4b1b-4a68-a6cc-c3f031c2ac44@y38g2000hsy.googlegroups.com> On Aug 16, 11:20?am, Peter Otten <__pete... at web.de> wrote: > sapsi wrote: > > [please don't top-post] > > > > > Thank you for the tip, you're absolutely right.I;m getting an > > exception ?that the name must not be null. However, this is some debug > > output > > --- logging.debug(" %s %s %s" % ?(vdbname, foldername,where_query)) > > OUTPUT: TestVDB test_b title regexp 'tit' > > --- print ?vdbname.__class__, > > foldername.__class__,where_query.__class__ > > OUTPUT: > > > --- self.cursor.execute( "insert into __saved_query__(vdb_name, > > query_table_name, query) values (?,?,?)", (vdbname, > > foldername,where_query)) > > > OUTPUT: __saved_query__.vdb_name may not be NULL > > > I honestly don't get it!. Why should this occur? > > Because vbdname is None? > > Seriously, it's hard for us to tell what's going on without the relevant > code. If you don't provide enough context you are on your own. > > Peter Actualy, vdbname is not none. I checked the value before entering. I found out that by closing the connection and reopening after creating VIEW solved the problem. Not a nice solution but it works and not a hassle given the low frequency of the operation. Regards Saptarshi --code self.cursor.execute( "insert into __smartfolder__ values (?,?,?,?)", (vdbname, foldername,where_query,hrform)) self.conn.commit() self.cursor.execute("CREATE VIEW %s AS %s" % (foldername, query) ) self.conn.close() self.connect_to_db() --- If i didn't close and reopen, the second time i try inserting i get the aforementioned error From daniel.watrous at gmail.com Tue Aug 26 17:35:20 2008 From: daniel.watrous at gmail.com (Daniel) Date: Tue, 26 Aug 2008 14:35:20 -0700 (PDT) Subject: Python and database unittests Message-ID: Hello, I'm writing an application that interacts with a database. As I think about how to write the unittests, I want them to be able to run without actually having to access a live database. The pattern that best describes this is here: http://martinfowler.com/eaaCatalog/serviceStub.html I have found http://qualitylabs.org/pdbseed/, which helps with unittests for a live database. This isn't what I'm after. Does anyone know about a module that acts as a database stub for python unittests? Thanks, Daniel From steve at REMOVE-THIS-cybersource.com.au Mon Aug 4 18:52:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2008 22:52:43 GMT Subject: very large dictionary References: <5c5e6d6e-04ef-4340-963f-d3825875b32c@e39g2000hsf.googlegroups.com> <6fftjvFb7ktoU2@mid.uni-berlin.de> <60FCF960-D1CD-4885-9F46-B5D7B798A9FF@gmail.com> <20080803224254.GG11163@tuva.opensoft.se> <6b690d0c-d817-4582-9dd1-9309b2d5cda1@e39g2000hsf.googlegroups.com> Message-ID: <00a78388$0$20302$c3e8da3@news.astraweb.com> On Mon, 04 Aug 2008 07:02:16 -0700, Simon Strobl wrote: > I created a python file that contained the dictionary. The size of this > file was 6.8GB. Ah, that's what I thought you had done. That's not a dictionary. That's a text file containing the Python code to create a dictionary. My guess is that a 7GB text file will require significantly more memory once converted to an actual dictionary: in my earlier post, I estimated about 5GB for pointers. Total size of the dictionary is impossible to estimate accurately without more information, but I'd guess that 10GB or 20GB wouldn't be unreasonable. Have you considered that the operating system imposes per-process limits on memory usage? You say that your server has 128 GB of memory, but that doesn't mean the OS will make anything like that available. And I don't know how to even start estimating how much temporary memory is required to parse and build such an enormous Python program. Not only is it a 7GB program, but it is 7GB in one statement. > I thought it would be practical not to create the > dictionary from a text file each time I needed it. I.e. I thought > loading the .pyc-file should be faster. Yet, Python failed to create a > .pyc-file Probably a good example of premature optimization. Out of curiosity, how long does it take to create it from a text file? -- Steven From eliben at gmail.com Thu Aug 21 08:33:15 2008 From: eliben at gmail.com (eliben) Date: Thu, 21 Aug 2008 05:33:15 -0700 (PDT) Subject: exception handling in complex Python programs References: <00bd3cc9$0$20315$c3e8da3@news.astraweb.com> Message-ID: <5ed98500-9b5e-4d2e-b34f-b20c946025f8@z72g2000hsb.googlegroups.com> > >http://eli.thegreenplace.net/2008/08/21/robust-exception-handling/ > > Just a few random points. You say: > > "Exceptions are better than returning error status codes. Some languages > (like Python) leave you with no choice as the whole language core and > standard libraries throw exceptions." > > Of course you have a choice. Your function can return anything you want: > Of course. I didn't mean that the language prohibits returning error codes, just that you can't use it without employing exception handling. I've fixed the wording to make it clearer. > You also wrote: > > "Exceptions exist for exceptional situations: unanticipated events that > are not a part of normal execution." > > Exceptions can and often are anticipated. E.g. if you write code that > opens a URL, you better anticipate that the server might reject your > connection. You better expect to be asked for a cookie, or > authentication. If you check for robots.txt, you better expect that it > might not exist. That's all normal execution. This is a point I'm not 100% in accord with. I still think that exceptions are for exceptional situations. I've removed the word "unanticipated" though, because it probably has no place in that sentence. However, I think that if one of your valid execution paths is w/o robots.txt, you should not use an exception to check whether it's there. This indeed uses the "bad side" of exceptions, splitting the exetution to two paths. Check if robots.txt is there. If it is, open it. If you can't open it, *that* is an exception, but if it's just not there, well it's part of your application logic. I believe this isn't against EAFP. I'm not sure I'm making the distinction clear here, it's a fine point. > > "When a programmer calls str.find('substring') he doesn?t expect an > exception to be thrown if the substring isn?t found." > > But if he called str.index() then he does expect an exception to be > thrown, just like for list.index() and dict[key] can raise exceptions. > They are neither bugs nor unexpected. > But why are there two versions that are the same except for the behavior in case it wasn't found ? My wishful imagination is precisely because of the reasons I've named. If you *know* it's there, use .index() - then, if it fails, it's an exception, but if a part of your logic is finding an item that might be missing, use a special value because you want to keep the logic in a single path. > "When used for flow-control, exceptions are like goto. There might be a > few esoteric cases in which they?re appropriate, but 99.99% of the time > they are not." > > I strongly disagree. try...except is like break or continue. Yes, it > breaks the linear flow of control, but not in a wild, dangerous way like > goto. > try...except can 'exit' to several 'catch points', unlike break/ continue. Furthermore, try...except can bring execution to another hierarchy level if it's not caught where it's thrown, so it's much more like goto in these senses. To find where the execution may go you'll find yourself searhching for the exception name over your source files, looking for the exception class name in some "except" clause. Sounds like looking for a goto label. P.S. Thanks a lot for taking the time to comment Eli From malaclypse2 at gmail.com Tue Aug 12 11:04:24 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 12 Aug 2008 11:04:24 -0400 Subject: python interpreter In-Reply-To: <29e59f7a-af87-40b4-9c5e-58abe1a28721@t1g2000pra.googlegroups.com> References: <29e59f7a-af87-40b4-9c5e-58abe1a28721@t1g2000pra.googlegroups.com> Message-ID: <16651e80808120804h53bb09b7sc5583ae6454db23b@mail.gmail.com> On Tue, Aug 12, 2008 at 10:49 AM, Alexandru Mosoi wrote: > I'm using python's interpreter's to run various commands (like a > normal shell). However if sources are modified changes are not > reflected so I have to restart interpreter. Is there any way to avoid > restarting this? > > example: > import blah reload(blah) Please see the documentation (http://docs.python.org/lib/built-in-funcs.html) for reload, though. There are lots of caveats to keep in mind. In particular, reload does not work if you import using the 'from ... import ...' construct, and it doesn't do anything magical about existing instances of classes that have now been redefined. Using reload() can be a useful tool when you are prototyping things and using them in the interactive interpreter, but probably should not be relied on in production code. -- Jerry From john.sasil at gmail.com Thu Aug 14 03:44:07 2008 From: john.sasil at gmail.com (john.sasil at gmail.com) Date: Thu, 14 Aug 2008 00:44:07 -0700 (PDT) Subject: i want to control python using keyboard Message-ID: <5bab4be9-4abc-4b42-84bc-e7e441b35120@v39g2000pro.googlegroups.com> hi i want to play alarm sound when i press a particular key in keyboard.so someone help me in doing it. Thanks and Regards Sasil.G From martin at see.sig.for.address.invalid Sun Aug 24 08:28:01 2008 From: martin at see.sig.for.address.invalid (Martin Gregorie) Date: Sun, 24 Aug 2008 12:28:01 +0000 (UTC) Subject: The Importance of Terminology's Quality References: <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> <48af8cc4$0$20919$607ed4bc@cv.net> <48b0b81f$0$7353$607ed4bc@cv.net> Message-ID: On Sat, 23 Aug 2008 21:22:05 -0400, John W Kennedy wrote: > Martin Gregorie wrote: >> On Sat, 23 Aug 2008 00:06:28 -0400, John W Kennedy wrote: >> >>> Martin Gregorie wrote: >>>> Not necessarily. An awful lot of CPU cycles were used before >>>> microcode was introduced. Mainframes and minis designed before about >>>> 1970 didn't use or need it >>> No, most S/360s used microcode. >> >> I never used an S/360. >> >> I thought microcode came into the IBM world with S/370 and Future >> Series (which later reappeared as the AS/400, which I did use). Didn't >> the S/370 load its microcode off an 8 inch floppy? > > Some did, but not all. The 370/145 was the first, and made a big splash > thereby. > ..snip... Thanks for that. As I said, during most of that era I was using ICL kit. Microcode was never mentioned in the 1900 contect. Hoiwever, they had a very rough approximation called extracodes. though they were closer to software traps than microcode: if hardware didn't implement an op code the OS intercepted it and ran equivalent code. This was used for i/o operations and for FP instructions on boxes that didn't have FP hardware. As a result all boxes executed the same instruction set. Some opcodes might be very slow on some hardware but it would execute. The 2900 series had huge amounts of microcode - it even defined both memory mapping and opcodes. You could run 1900 code (24 bit words, fixed length instructions, ISO character codes) simultaneously with 'native' code (8 bit bytes, v/l instructions, EBCDIC) with each program running under its usual OS (George 3 for 1900, VME/B for 1900). The only other systems I'm aware of that could do this were the big Burroughs boxes (6700 ?), which used a byte-based VM for COBOL and a word- based VM for FORTRAN and Algol 60) and IBM AS/400 (OS/400 could run S/34 code alongside S/38 and AS/400 code). AFAICT Intel virtualisation doesn't do this - all code running under VMware or any of the other VMs is still running in a standard Intel environment. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From smbaker at gmail.com Wed Aug 13 15:31:42 2008 From: smbaker at gmail.com (Scott) Date: Wed, 13 Aug 2008 12:31:42 -0700 (PDT) Subject: getting full exception information from an xmlrpc server Message-ID: <1091f512-7b47-4bec-93f5-32f4e6516505@o40g2000prn.googlegroups.com> I'm debugging an xmlrpc client/server application. Often when an exception occurs in the server, I receive only a very short error message on the client. For example: xmlrpclib.Fault: :"> Presumably this is because xmlrpclib on the server is catching the exception, and only sending the exception name to the client, not the server's stack trace. What I would like is the full stack trace of what went wrong on the server (i.e. the junk python usually dumps to the console when an exception occurs). I don't care which side I see the dump on (client or server), but I need to see the whole trace so I can figure out what the problem is. Is there an easy way to do this? Thanks, Scott From mathieu.prevot at ens.fr Thu Aug 21 05:17:58 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Thu, 21 Aug 2008 11:17:58 +0200 Subject: subprocess seems to "detach" / ignore wait() In-Reply-To: References: <3e473cc60808202241j2825bc3cl7f1050f1ec68563b@mail.gmail.com> <3e473cc60808202246r48e2b692q3e82efa1fbbd6c78@mail.gmail.com> Message-ID: <3e473cc60808210217i187ad991ye98d4540ca2f5398@mail.gmail.com> 2008/8/21 Gabriel Genellina : > En Thu, 21 Aug 2008 02:46:06 -0300, Mathieu Prevot escribi?: > >>> So what is the right thing to do so my script >>> returns 1 or 0 depending on its state and success ? > > I use something like this: > > def main(argv): > try: > try: > do_things() > return 0 > finally: > do_cleanup() > except: > log_exception() > return 1 > > if __name__=='__main__': > import sys > sys.exit(main(sys.argv)) > >> PS: BTW how can I detach my process ie have an equivalent to >> `myscript.py&` from the python script ? > > There are a few recipes in the Python CookBook at http://code.activestate.com/recipes/langs/python/ The return from main()... it was my thought too. Thank you Gabriel :) Mathieu From gminick at bzt.bzt Sun Aug 31 13:20:43 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Sun, 31 Aug 2008 17:20:43 +0000 (UTC) Subject: How can we get to the end of a quote inside a string References: Message-ID: On Sun, 31 Aug 2008 07:29:26 -0700 (PDT), rajmohan.h at gmail.com wrote: > Suppose I have a string which contains quotes inside quotes - > single and double quotes interchangeably - > s = "a1' b1 " c1' d1 ' c2" b2 'a2" >>> s = "a1' b1 " c1' d1 ' c2" b2 'a2" File "", line 1 s = "a1' b1 " c1' d1 ' c2" b2 'a2" ^ SyntaxError: invalid syntax >>> Writing a small parser for your needs shouldn't be that hard. To some extent you can use regular expressions: >>> re.findall(re.compile("\".*?\""), s) ['" c1\' d1 \' c2"'] >>> re.findall(re.compile("\'.*?\'"), s) ['\' b1 " c1\'', '\' c2" b2 \''] >>> but it won't work in all cases. You can read more here: http://www.gnosis.cx/TPiP/ -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From gandalf at shopzeus.com Fri Aug 8 05:25:14 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 08 Aug 2008 11:25:14 +0200 Subject: Fastest way to store ints and floats on disk In-Reply-To: References: <489B41CE.8080909@shopzeus.com> Message-ID: <489C10FA.3000005@shopzeus.com> > > Hmm... I wrote an browser based analysis tool and used the working > name pyvot... Is this for the public domain? > > I found Numeric to provide the best balance of memory footprint and > speed. I also segregated data prep into a separate process to avoid > excessive memory use at run time. Turns out python Do you mean numpy? (Numeric is not actively supported, numarray is deprecated.) > > For the site I'm at, I've got 10 years sales history recapped from > 4327846 detail records into 458197 item by customer by month records > and top shows a 240Mb memory footprint. I've got 21 cross indexed > selection fields, and can display up to six data types (qty, price, > sqft, cost, gp%, avg). At another site I've got approx 8.5M records > recapped into 1M records with 15 indexes and 5 years monthly history > living in a 540Mb memory footprint. > > It's reasonably quick: a query like 'select san mateo, foster city and > san carlos accounts, sort by customer and product category and display > this year's sales by month' selects 260 records and renders in the > browser in about 2 seconds. Or on the larger installation 'Show sales > for the past five years for product group 12 sorted by city within > route' selects 160 records and renders in about 3 seconds. Incredible. :-) > My objective was to keep the info in memory for fast response times. Permature optimalization is the root of all evil. (Who said that?) All right, first I'll try to keep it in memory and come back if that doesn't work out. > I played a lot of games getting this all to work well, including some > c extensions, but Numeric's take, sum, tostring and fromstring ended > up with 'pivotal' roles. :) Thank you, Laszlo From castironpi at gmail.com Wed Aug 6 00:55:10 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 5 Aug 2008 21:55:10 -0700 (PDT) Subject: string to type object (C) References: <4477a269-f189-4ae1-9c97-e78633bb3d27@2g2000hsn.googlegroups.com> Message-ID: <6a725a88-5407-455d-a9e3-d63aff64eddf@t54g2000hsg.googlegroups.com> On Aug 5, 7:59?pm, Miles wrote: > On Tue, Aug 5, 2008 at 2:30 AM, castironpi wrote: > > I'm looking for a one-to-one function from strings to the built-in > > data types in C. ?I will be keeping the string in a file. ?I need the > > PyTypeObject* back from it. ?If nothing else I'll just do a bunch of > > strcmp( "tuple" ) { return &PyTuple_Type; } commands, provided > > &PyTuple_Type; will be linking the right address. > > Something along the lines of this? > b = PyImport_Import("__builtin__"); > return PyObject_GetAttrString(b, typestring); > > -Miles Miles, That's what I was looking for. I wanted to avoid the heavy Import but I thought I remembered that imports are free after the first time. Import needed a PyString. PyObject* s= PyString_FromString( "__builtin__" ); PyObject* b= PyImport_Import(s); return PyObject_GetAttrString(b, "str"); I expect I need a Py_DECREF on s and b. Do you know if uncooperative (not necc'ly malicious) code could interfere: >>> __builtin__.int= None >>> __builtin__.int >>> __builtin__.int= type( 0 ) >>> __builtin__.int ? Or would PyImport_Import(s) create a namespace that had the int type in it from scratch? From jwkenne at attglobal.net Sat Aug 23 00:18:29 2008 From: jwkenne at attglobal.net (John W Kennedy) Date: Sat, 23 Aug 2008 00:18:29 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: <0-SdnROBHqDbVDHVnZ2dnUVZ_jWdnZ2d@speakeasy.net> References: <48a782e9$0$20913$607ed4bc@cv.net> <48a8df27$0$7362$607ed4bc@cv.net> <0-SdnROBHqDbVDHVnZ2dnUVZ_jWdnZ2d@speakeasy.net> Message-ID: <48af8f95$0$29518$607ed4bc@cv.net> Rob Warnock wrote: > What was the corresponding 1401 boot sequence? The 1401 had a boot-from-tape-1 button on the console, and a boot-from-card button on the card reader. You couldn't truly boot from a disk; you loaded a little starter deck of about 20 cards on the card reader. On the 1401, the typewriter was an optional luxury, mainly used in long batch jobs to do ad-hoc on-line queries. On the compatible 1460, the typewriter was somewhat more common, because the console the typewriter mounted on was a standard part of the system, so only the typewriter had to be added. -- John W. Kennedy "You can, if you wish, class all science-fiction together; but it is about as perceptive as classing the works of Ballantyne, Conrad and W. W. Jacobs together as the 'sea-story' and then criticizing _that_." -- C. S. Lewis. "An Experiment in Criticism" From james7047276 at googlemail.com Sun Aug 24 11:22:29 2008 From: james7047276 at googlemail.com (james7047276 at googlemail.com) Date: Sun, 24 Aug 2008 08:22:29 -0700 (PDT) Subject: aec kontaktanzeigen in Bad Hersfeld internet kontaktanzeigen erotik kontaktanzeigen net fremdgehen * kontaktanzeigen paar singletreff aachen kontaktanzeigen bielefeld fremd gehen single treff erotische kontaktanzeigen bielefeld Message-ID: <54ff2f88-d158-4d51-93f8-7e54603937b0@b1g2000hsg.googlegroups.com> aec kontaktanzeigen in Bad Hersfeld internet kontaktanzeigen erotik kontaktanzeigen net fremdgehen * kontaktanzeigen paar singletreff aachen kontaktanzeigen bielefeld fremd gehen single treff erotische kontaktanzeigen bielefeld + + EROTIK KONTAKTE - EROTISCHE KONTAKTANZEIGEN http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ + + + + + + + + + + + singletreff g?ttingen in Oschatz lustige sex kontaktanzeigen in G?nzburg kontaktanzeigen schwerin in Landsberg schwule kontaktanzeigen in Hildesheim fremdgehen macht in Prenzlau single erotische kontaktanzeigen in Bad erotik kontaktanzeigen thueringen in Aue kontaktanzeigen mainz in Ruppin private kontakt anzeigen in Eisleben kontaktanzeigen schwul in Koethen www single erotik kontaktanzeigen org in Wolfratshausen single kontaktanzeigen in Bergen sex kontaktanzeigen niedersachsen in Waldeck http://www.bebin.tv/forum/showthread.php?t=31454 - christliche kontaktanzeigen in F?rth http://www.bloglines.com/forums/read.php?21,71919 - sex kontaktanzeigen thueringen in Freiburg http://www.gamesforum.ca/showthread.php?t=317057 - sex kontaktanzeigen osteuropa in Kamenz http://www.bebin.tv/forum/showthread.php?t=31384 - kontaktanzeigen f?r schwule in Delitzsch http://www.meinews.net/jedes-t226215.html - kontaktanzeigen thueringen in Dieburg http://www.meinews.net/cialis-t244424.html - aec erotik kontaktanzeigen in Meiningen http://billige-autoreifen.mirror-server.net Billige Autoreifen - kontaktanzeigen niedersachsen in Sta?furt http://draconian.com/dragon-forum/showthread.php?t=17742 - single treff siegen in Boeblingen http://www.gamesforum.ca/showthread.php?t=319660 - erotik kontaktanzeigen cottbus in Gro?-Gerau http://www.meinews.net/cialis-t244251.html - erotik kontaktanzeigen fuer dicke in Waldeck http://www.gamesforum.ca/showthread.php?t=319638 - sex kontaktanzeigen aachen in Wesel http://www.bloglines.com/forums/read.php?10,71529 - FilipinoFriendFinder.com in Weilburg http://draconian.com/dragon-forum/showthread.php?t=20493 - kostenlose singletreff in Gie?en http://www.meinews.net/erotik-t245288.html - sex kontaktanzeigen heidelberg in Beeskow From castironpi at gmail.com Wed Aug 27 14:12:37 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 27 Aug 2008 11:12:37 -0700 (PDT) Subject: Python multimap References: Message-ID: <4d2f1ac5-c21c-42d9-977e-6493f0c23573@d77g2000hsb.googlegroups.com> On Aug 27, 12:52?pm, brad wrote: > Mike Kent wrote: > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> k = {} > >>>> k['1'] = [] > >>>> k['1'].append('Tom') > >>>> k['1'].append('Bob') > >>>> k['1'].append('Joe') > > >>>> k['1'] > > ['Tom', 'Bob', 'Joe'] > > There is only one '1' key in your example. I need multiple keys that are > all '1'. I thought Python would have something built-in to handle this > sort of thing. > > I need a true multimap: > > k['1'] = 'Tom' > k['1'] = 'Tommy' > > without Tommy overwriting Tom and without making K's value a list of > stuff to append to. That's still just a regular map. I don't understand what a multimap does that a map of lists doesn't do. From wuwei23 at gmail.com Sat Aug 9 12:10:27 2008 From: wuwei23 at gmail.com (alex23) Date: Sat, 9 Aug 2008 09:10:27 -0700 (PDT) Subject: internet searching program References: <304d52cb-a8a8-46d5-81be-4eb01c73d479@26g2000hsk.googlegroups.com> Message-ID: On Aug 9, 12:59 pm, KillSwitch wrote: > Is it possible to make a program to search a site on the internet, > then get certain information from the web pages that match and display > them? Like, you would put in keywords to be searched for on > youtube.com, then it would search youtube.com, get the names of the > videos, the links, and the embed information? Or something like that. You might find the mechanize module handy: http://wwwsearch.sourceforge.net/mechanize/ And possibly BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/ From ktenney at gmail.com Fri Aug 8 17:13:36 2008 From: ktenney at gmail.com (Kent Tenney) Date: Fri, 8 Aug 2008 21:13:36 +0000 (UTC) Subject: sending to an xterm References: <20080808205821.GJ23567@dragontoe.org> Message-ID: Derek Martin pizzashack.org> writes: > > On Fri, Aug 08, 2008 at 08:25:19PM +0000, Kent Tenney wrote: > > Howdy, > > > > I want to open an xterm, send it a command and have it execute it. > > You can't do that. xterm doesn't execute shell commands passed on > stdin... It can, however, execute one passed on the command line. > > Instead of just running xterm, you can run "xterm -e 'cmd foo bar'" > where cmd is the program to run and foo and bar are its arguments. > The problem is that as soon as the program exits, xterm will exit > also. > OK, I see that. (getting off topic) any chance of keeping the xterm open after running the command? Thanks, Kent From timothy.grant at gmail.com Mon Aug 4 18:45:57 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Mon, 4 Aug 2008 15:45:57 -0700 Subject: Why doesn't import work? In-Reply-To: <9ff8bc40-3cc7-4d01-a577-bce3f7b9b557@e39g2000hsf.googlegroups.com> References: <9ff8bc40-3cc7-4d01-a577-bce3f7b9b557@e39g2000hsf.googlegroups.com> Message-ID: On Mon, Aug 4, 2008 at 3:34 PM, ssecorp wrote: > I have in Lib/site-packages a module named pdfminer. when I do import > pdfminer it complains: > >>>> import pdfminer > > Traceback (most recent call last): > File "", line 1, in > import pdfminer > ImportError: No module named pdfminer > > > I created a file pdfminer.py and put it in site-packages and that > works. > > so I apparently can't import a directory pdfminer. In the directory > pdfminer there are 3 other directoriees and inside them python-files. > > how would I import them? > -- > http://mail.python.org/mailman/listinfo/python-list > set your PYTHONPATH environment to include the directory where your module is. -- Stand Fast, tjg. [Timothy Grant] From weiguo6 at gmail.com Thu Aug 7 19:39:09 2008 From: weiguo6 at gmail.com (Wei Guo) Date: Thu, 7 Aug 2008 16:39:09 -0700 Subject: A question about string and float number In-Reply-To: References: <489A8A01.1050908@linkline.com> Message-ID: Hi Grant, I am using the try/exception and just curious why function type doesn't work. Best regards, Wei On 8/7/08, Timothy Grant wrote: > > That's because s IS a string. It's not been converted to a float. > > In [1]: s = '3.1415' > In [2]: n = float(s) > In [3]: type(s) > Out[3]: > In [4]: type(n) > Out[4]: > > Why are you avoiding the very simple try:/except: solution to this problem? > > On Thu, Aug 7, 2008 at 1:28 PM, Wei Guo wrote: > > Hi I tried the first type method but it seens that it doesn't work. Could > > anyone help me about it? > > > >>>> s = '3.145' > >>>> type(s) == type(float()) > > False > >>>> type(s) > > > >>>> type(float()) > > > >>>> > > > > Best regards, > > > > Wei > > > > > > On 8/7/08, Wei Guo wrote: > >> > >> Hi Thanks for Tyler and Edwin's help. > >> > >> For my questions, I need to import some xml file and there are floating > >> number and strings in it. I need to process string and number > differently. > >> This is reason that I am asking question here. Is this background > >> information we need for this quesions. > >> > >> Btw, which way is better? type or with exception ValueError? > >> > >> Thanks, > >> > >> Wei > >> > >> > >> On 8/6/08, Tyler Breisacher wrote: > >>> > >>> It's generally a bad idea to use "except" without naming a specific > >>> exception. The exception you might expect in this case is ValueError. > Any > >>> other exception *should* be uncaught if it happens. By the way, this > method > >>> will return true for integers as well as floats. For example, > isFloat('3') > >>> will return 3.0. So make sure this is what you want, since it wasn't > 100% > >>> clear from the original message. > >>> > >>> > >>> Wei Guo wrote: > >>>> > >>>> #this is a better way of testing a string for float > >>>> def isFloat(s): > >>>> try: > >>>> s = float(s) > >>>> except: > >>>> return False > >>>> return True > >>> > >>> > >>> -- > >>> http://mail.python.org/mailman/listinfo/python-list > >> > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > Stand Fast, > tjg. [Timothy Grant] > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rpw3 at rpw3.org Thu Aug 21 10:11:48 2008 From: rpw3 at rpw3.org (Rob Warnock) Date: Thu, 21 Aug 2008 09:11:48 -0500 Subject: The Importance of Terminology's Quality References: <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: sln at netherlands.com> wrote: +--------------- | rpw3 at rpw3.org (Rob Warnock) wrote: | >In the LGP-30, they used hex addresses, sort of[1], but the opcodes | >(all 16 of them) had single-letter mnemonics chosen so that the | >low 4 bits of the character codes *were* the correct nibble for | >the opcode! ;-} ... | >[1] The LGP-30 character code was defined before the industry had | > yet standardized on a common "hex" character set, so instead of | > "0123456789abcdef" they used "0123456789fgjkqw". [The "fgjkqw" | > were some random characters on the Flexowriter keyboard whose low | > 4 bits just happened to be what we now call 0xa-0xf]. Even worse, | > the sector addresses of instructions were *not* right-justified | > in the machine word (off by one bit), plus because of the shift- | > register nature of the accumulator you lost the low bit of each | > machine word when you typed in instructions (or read them from | > tape), so the address values you used in coding went up by *4*! | > That is, machine locations were counted [*and* coded, in both | > absolute machine code & assembler] as "0", "4", "8", "j", "10", | > "14", "18", "1j" (pronounced "J-teen"!!), etc. | | Whats os interresting about all this hullabaloo is that nobody has | coded machine code here, and know's squat about it. +--------------- Think again! *BOTH* of the two examples I gave -- for the LGP-30 & the IBM 1410 -- *WERE* raw machine code, *NOT* assembler!!! Please read again what I wrote about the character codes for the instruction mnemonics *BEING* the machine instruction codes. For the IBM 1410, the bootstrap code that ones types in: v v L%B000012$N *IS* raw machine code, *NOT* assembler!! [See my previous post for the meaning of the fields of that instruction.] The IBM 1410 is a *character* machine, not a binary machine, so each memory location is a (6+1 bit) character. As a result, one can [and *must*, during bootup!] type absolute machine code directly into memory using the console typewriter [an only-slightly-modified IBM Selectric, as it happens]. The fact that -- for the sake of user convenience -- the hardware supports manual entry of machine code into memory by the operator in a form that closely *resembles* assembler (but *ISN'T*!) was a deliberate design feature. Similarly, the characters you type for the LGP-30's opcodes *ARE* the opcodes, at least by the time they get into the machine, since when typing in code (or reading it from paper tape) one sets the I/O system to "4-bit input mode", in which the upper bits of the characters are stripped off by the I/O hardware during input. Thus when you type a "Bring" (load) instruction such as this ["Bring" (load) location 0xd7c (track 0xd, sector 0x31)]: b0q7j you're typing *RAW* machine code, *NOT* assembler!! You see, the lower 4 bits of character "b" -- the "mnemonic" for "Bring" -- were binary 0001, the *same* as the lower 4 bits of the digit "1" (and two other characters as well). So when you typed a "b" in that position in "4-bit input mode" you were typing the same thing as the character "1" which was the same thing as *binary* 0001 which was the absolute machine opcode for the ""Bring" instruction!! "No assembler required" (pardon the pun). +--------------- | I'm not talking assembly language. +--------------- Neither was I. The fact that for the two machines I mentioned absolute machine code was somewhat readable to humans seems to have confused you, but that's the way some people liked to design their hardware back in those days -- with clever punning of character codes with absolute machine opcodes (for the convenience of the user). +--------------- | Don't you know that there are routines that program machine code? +--------------- What do you mean "routines"?!? For the above two machines, you can enter machine code with *no* programs ("routines?") running; that is, no boot ROM is required (or even available, as it happened). +--------------- | Yes, burned in, bitwise encodings that enable machine instructions? +--------------- The two machines mentioned above did not *HAVE* a "boot ROM"!! You had to *manually* type raw, absolute machine code into them by hand every time you wanted to boot them up [at least a little bit, just enough to load a larger bootstrap program]. +--------------- | Nothing below that. +--------------- You're assuming that all machines *have* some sort of "boot ROM". Before the microprocessor days, that was certainly not always the case. The "boot ROM", or other methods of booting a machine without manually entering at least a small amount of "shoelace" code [enough the *load* the real bootstrap], was a fairly late invention. -Rob p.s. Similarly, the DEC PDP-8 & PDP-11 were also originally booted by manually toggling the console switches in order to deposit a few instructions into memory, and then the starting address was toggled in and "Start" was pushed. It was only later that a boot ROM became available for the PDP-11 (as an expensive option!) -and only much later still for the PDP-8 series (e.g., the MI8E for the PDP-8/E). ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From paul at boddie.org.uk Thu Aug 21 08:44:58 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 21 Aug 2008 05:44:58 -0700 (PDT) Subject: Is my thinking Pythonic? References: <638bf217-3eaf-43af-8604-4145aa156afe@m73g2000hsh.googlegroups.com> Message-ID: <7d708fec-4b7d-4283-9406-8365d15af108@z66g2000hsc.googlegroups.com> On 21 Aug, 14:21, Hussein B wrote: > If you have a huge class, you can't figure the instance variables of > each object. > So, I created this constructor: > -- > def __init__(self): > ? self.speed = None > ? self.brand = None > -- > This way, I can figure the instance variables by just reading the > __init__ method. > What do you think of my approach? is it considered Pythonic? I don't like to use the term "Pythonic", but I think it's reasonable to initialise the attributes in this way. In effect, what you're doing is to ensure that the attributes have some well-defined state at each point in the lifetime of the instance, and I find myself doing this a lot. My __init__ methods typically consist of any calls to superclass __init__ methods followed by the explicit initialisation of any additional attributes defined for the instance in the class. Some people might advocate not bothering defining the attributes until they are actually set with some value, but then you have to deal with situations where the attributes are missing. Generally, handling missing attributes isn't worth the bother unless you have a large number of attributes which could only *potentially* be present: a situation which occurs when wrapping "foreign" libraries, for example, where properties or use of __getattr__ seem more essential than the luxury they might otherwise appear to be. Paul From larry.bates at websafe.com` Sat Aug 2 11:28:28 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 02 Aug 2008 10:28:28 -0500 Subject: Searching for some kind of data type In-Reply-To: <33d13c77-e710-4951-a559-7ea8b6e15287@26g2000hsk.googlegroups.com> References: <33d13c77-e710-4951-a559-7ea8b6e15287@26g2000hsk.googlegroups.com> Message-ID: Giampaolo Rodola' wrote: > Hi, > for an FTP server I wrote I'd need to group the FTP commands in one > table that defines the command itself, the syntax string, required > permission, whether it requires authorization, whether it takes > argument and whether there's a need to validate the path from the > argument. > The more obvious way I found to do that is something like this: > > class CommandProperty: > def __init__(self, perm, auth_needed, arg_needed, check_path, > syntax): > self.perm = perm > self.auth_needed = auth_needed > self.arg_needed = arg_needed > self.check_path = check_path > self.syntax = syntax > > ftp_cmds = { > "ABOR" : CommandProperty(perm=None, auth_needed=True, > arg_needed=False, check_path=False, syntax="ABOR (abort transfer)."), > "APPE" : CommandProperty(perm='a', auth_needed=True, > arg_needed=True, check_path=True, syntax="APPE file-name > (append data to an existent file)."), > "CDUP" : CommandProperty(perm='e', > auth_needed=True,arg_needed=False, check_path=False, syntax="CDUP (go > to parentdirectory)."), > ... > ... > ... > } > > ...but I find it somewhat redundant and... "ugly". > I was wondering if there was some kind of data type which could better > fit such purpose or if someone could suggest me some other approach to > do this same thing. Maybe using a dictionary is not the better choice > here. > > > Thanks in advance > > > --- Giampaolo > http://code.google.com/p/pyftpdlib/ Seems completely reasonable to me. You might just consider using keyword arguments in the __init__ method and eliminate the dictionary altogether. Not tested, but you will get the idea: class CommandProperty: def __init__(self, perm = perm, auth_needed = True, arg_needed = True, check_path = False, syntax = syntax): self.perm = perm self.auth_needed = auth_needed self.arg_needed = arg_needed self.check_path = check_path self.syntax = syntax ftpCommands = dict( ABOR = CommandProperty(perm = None, arg_needed = False, syntax="ABOR (abort transfer)."), APPE = CommandProperty(perm = 'a', check_path=True, syntax = "APPE file-name (append data to" \ "an existent file)."), CDUP = CommandProperty(perm= 'e', arg_needed = False, syntax="CDUP (go> to parentdirectory)."), ... ... ... ) IMHO this is a "little" easier to manage because you can take advantage of the default values for keyword arguments to eliminate some of the arguments. Hope this helps, Larry From hniksic at xemacs.org Tue Aug 19 09:41:37 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 19 Aug 2008 15:41:37 +0200 Subject: optparse escaping control characters References: <4001fcc2-e595-4bd6-9baf-c71db3761d36@m3g2000hsc.googlegroups.com> <877iad9nrm.fsf@mulj.homelinux.net> <6a650558-b9d4-4833-a909-147df44155f9@m45g2000hsb.googlegroups.com> Message-ID: <873al19l66.fsf@mulj.homelinux.net> Dan Halligan writes: > How would I pass a control character to python on the command line? It depends on which command line you are using. Most Unix-like shells will allow you to input a control character by preceding it with ^V. Since \t is the TAB character, you should be able to input it like this: $ python -c 'import sys; print sys.argv' '^V' ['-c', '\t'] # note single backslash From prologic at shortcircuit.net.au Thu Aug 28 21:57:02 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 29 Aug 2008 11:57:02 +1000 Subject: Fastest way to write huge files In-Reply-To: <538050a90808281735u51ce90d0o3db3945a6ed2b591@mail.gmail.com> References: <538050a90808281735u51ce90d0o3db3945a6ed2b591@mail.gmail.com> Message-ID: Hi, You could use generators connected via a pipe or tcp socket ... cheers James On Fri, Aug 29, 2008 at 10:35 AM, Mohamed Yousef wrote: > Hello , > > let's say , I'm moving large files through network between devices > what is the fastest way to do this ? > what i came up with :- > > 1) using regular file operations with an in memory limit of 4MB which > when filled written to disk and re-filled again > > 2) using memory mapped files in the following way , map first 20MB of > file and after finishing them flush and map next 20MB > ------ > which of them should be faster in writting to disk ? and less memory consuming > > or is there faster ways ? > > Thanks, > > Regards , > Mohamed Yousef > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From emanuele.nespolo at gmail.com Thu Aug 28 02:39:56 2008 From: emanuele.nespolo at gmail.com (nisp) Date: Wed, 27 Aug 2008 23:39:56 -0700 (PDT) Subject: unexpected from/import statement behaviour References: <42780654-8a54-470e-a494-ca53fd0504f5@p25g2000hsf.googlegroups.com> <7dbab131-7f7b-4266-b706-fff52670e9e1@l64g2000hse.googlegroups.com> Message-ID: <3196d355-9096-4ba1-9485-28ce03935e92@a1g2000hsb.googlegroups.com> On Aug 27, 3:35 pm, Peter Otten <__pete... at web.de> wrote: > nisp wrote: > > Thanks first of all ! I read the interesting Diez's link but something > > still remains to me unclear, on the other hand it's clear the my > > problem is concentrated there and on symbols. > > Read it again. If you have two modules > > module1.py > from sys import stderr > > module2.py > from module1 import stderr > > you get three names 'stderr' in three different namespaces, and each name > may bind a different object. > > > > > Here is what I'm trying to do > > > HelloWorld.py: this is a real simplification of my external module > > though still reflecting its structure (commented out is the version > > that, let's say, works) > > > from sys import stderr > > #import sys > > > class Cheers: > > def __init__(self): > > self.cheersMsg = 'Hello World !!' > > print "Cheers stderr %s" % stderr > > #print "Cheers stderr %s" % sys.stderr > > def _putCheers(self): > > print>>stderr, 'Here is my msg:', self.cheersMsg > > print>>stderr, 'This is a nice day today !!' > > #print>>sys.stderr, 'Here is my msg:', self.cheersMsg > > #print>>sys.stderr, 'This is a nice day today !!' > > def doSomeStuff(self): > > self._putCheers() > > > And below there is the module that uses the above one (mymodule.py): > > > #!/usr/bin/python > > > import sys > > This imports HelloWorld.stderr: > > > from HelloWorld import * > > You now have a global variable 'stderr' in module __main__, initialized to > the same value as HelloWorld.stderr. > > > class StderrCatcher: > > def __init__(self): > > self.data = '' > > def write(self,stuff): > > self.data = self.data + "\t" + stuff > > > def main(): > > > print "mymodule stderr: %s" % sys.stderr > > This rebinds sys.stderr and a local 'stderr' in main() > > > sys.stderr = stderr = StderrCatcher() > > but both HelloWorld.stderr and __main__.stderr are unaffected. What you need > is > import HelloWorld > sys.stderr = HelloWorld.stderr = StderrCatcher() > > > m = Cheers() > > m.doSomeStuff() > > print "stderr: \n%s" % sys.stderr.data > > > if __name__ == '__main__': > > main() > > > Below there is the output when it doesn't work: > > > mymodule stderr: ', mode 'w' at 0xb7d160b0> > > Cheers stderr ', mode 'w' at 0xb7d160b0> > > Here is my msg: Hello World !! > > This is a nice day today !! > > stderr: > > > And here when it works: > > > mymodule stderr: ', mode 'w' at 0xb7dc40b0> > > Cheers stderr <__main__.StderrCatcher instance at 0xb7d8bd4c> > > stderr: > > Here is my msg: Hello World !! > > This is a nice day today !! > > > Thanks again! > > > PS Sorry for having probably replied to somone of you directly :-( Hi Peter! Definitely you are right ! May be this time I understood completely the topic (or may be not ?... gosh !) ... I didn't considered well the "from HelloWolrd import *" in mymodule.py. Now my module is: import sys import HelloWorld class StderrCatcher: def __init__(self): self.data = '' def write(self,stuff): self.data = self.data + "\t" + stuff def main(): print "mymodule stderr: %s" % sys.stderr mystderr = sys.stderr = HelloWorld.stderr = StderrCatcher() m = HelloWorld.Cheers() m.doSomeStuff() print >>sys.stderr, "mymodule prints something" print "stderr: \n%s" % mystderr.data if __name__ == '__main__': main() and its output is: mymodule stderr: ', mode 'w' at 0xb7d2d0b0> Cheers stderr <__main__.StderrCatcher instance at 0xb7cf4e4c> stderr: Here is my msg: Hello World !! This is a nice day today !! mymodule prints something now it works perfectly ! Great ! Thanks to all of you ! Nisp From larry.bates at websafe.com` Mon Aug 4 16:56:15 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 04 Aug 2008 15:56:15 -0500 Subject: Trying to fix Invalid CSV File In-Reply-To: <42134ad4-ae35-4d25-94fc-2504d29003e6@r15g2000prh.googlegroups.com> References: <0427191c-d493-442d-ba26-94802bc6062b@v13g2000pro.googlegroups.com> <078f7aad-3bba-49b4-8978-18ac5bfaa6f7@r15g2000prd.googlegroups.com> <6bade254-5001-4ae2-a000-003b84437a76@w1g2000prk.googlegroups.com> <42134ad4-ae35-4d25-94fc-2504d29003e6@r15g2000prh.googlegroups.com> Message-ID: Ryan Rosario wrote: > On Aug 4, 8:30 am, Emile van Sebille wrote: >> John Machin wrote: >>> On Aug 4, 6:15 pm, Ryan Rosario wrote: >>>> On Aug 4, 1:01 am, John Machin wrote: >>>>> On Aug 4, 5:49 pm, Ryan Rosario wrote: >>>>>> Thanks Emile! Works almost perfectly, but is there some way I can >>>>>> adapt this to quote fields that contain a comma in them? >> >> >>> Emile's snippet is pushing it through the csv reading process, to >>> demonstrate that his series of replaces works (on your *sole* example, >>> at least). >> Exactly -- just print out the results of the passed argument: >> >> >>> >> rec.replace(',"',",'''").replace('",',"''',").replace('"','""').replace("'''",'"') >> >> '123,"Here is some, text ""and some quoted text"" where the quotes >> should have been doubled",321' >> >> Where it won't work is if any of the field embedded quotes are next to >> commas. >> >> I'd run it against the file. Presumably, you've got a consistent field >> count expectation per record. Any resulting record not matching is >> suspect and will identify records this approach won't address. >> >> There's probably better ways, but sometimes it's fun to create >> executable line noise. :) >> >> Emile > > Thanks for your responses. I think John may be right that I am reading > it a second time. I will take a look at the CSV reader documentation > and see if that helps. Then once I run it I can see if I need to worry > about the comma-next-to-quote issue. This is a perfect demonstration of why tab delimited files are so much better than comma and quote delimited. Virtually all software can handle table delimited as well as comma and quote delimited, but you would have none of these problems if you had used tab delimited. The chances of tabs being embedded in most data is virtually nil. -Larry From nagle at animats.com Sun Aug 17 13:15:47 2008 From: nagle at animats.com (John Nagle) Date: Sun, 17 Aug 2008 10:15:47 -0700 Subject: urllib getting SSL certificate info In-Reply-To: References: <200808160234.28304.ghirai@ghirai.com> Message-ID: <48a85819$0$17204$742ec2ed@news.sonic.net> Fredrik Lundh wrote: > Ghirai wrote: > >> Using urllib, is there any way i could access some info about the SSL >> certificate (when opening a https url)? >> >> I'm really interested in the fingerprint. >> >> I haven't been able to find anything so far. > > you can get some info via (undocumented?) attributes on the file handle: > > >>> import urllib > >>> f = urllib.urlopen("https://mail.google.com/") > >>> f.fp > > ['issuer', 'read', 'server', 'write'] > >>> f.fp._ssl.issuer() > '/C=ZA/O=Thawte Consulting (Pty) Ltd./CN=Thawte SGC CA' > >>> f.fp._ssl.server() > '/C=US/ST=California/L=Mountain View/O=Google Inc/CN=mail.google.com' > > If you really need details from the SSL cert, you usually have to use M2Crypto. The base SSL package doesn't actually do much with certificates. It doesn't validate the certificate chain. And those strings of attributes you can get are ambiguious; data fields may contain unescaped "/", which is the field separator. I went through this last year and had to use M2Crypto, which is something of a headache but more or less works. John Nagle From gordyt at gmail.com Tue Aug 26 18:12:53 2008 From: gordyt at gmail.com (gordyt) Date: Tue, 26 Aug 2008 15:12:53 -0700 (PDT) Subject: Python and database unittests References: Message-ID: <906bf68d-2727-429b-a4f5-99cdf4461d86@k13g2000hse.googlegroups.com> Daniel I don't know if it would work for your situation or not, but if you are using Python 2.5, you could use the now built-in sqlite3 module. If you didn't even want to create a temporary database file you could use the special memory-only syntax like this: >>> import sqlite3 >>> conn =sqlite3.connect(":memory:") >>> # use the connection >>> conn.close() --gordy From notvalid2 at sbcglobal.net Tue Aug 26 20:21:02 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Tue, 26 Aug 2008 17:21:02 -0700 Subject: Date Comparison and Manipulation Functions? In-Reply-To: References: Message-ID: zuul at ferg.org wrote: > check out Pyfdate: http://www.ferg.org/pyfdate > > from pyfdate import * > > t = Time().add(hours=14) > print "It is now", t.wdt > > datestring1 = "2005/10/05" #year,month,day > datestring2 = "2002/09/22" #year,month,day > datestring3 = "2007/11/11" #year,month,day > > year,month,day = numsplit(datestring1) # split into integers > t1 = Time(year,month,day) > for datestring in (datestring2,datestring1,datestring3): > year,month,day = numsplit(datestring) > t2 = Time(year,month,day) > > if t1 > t2: > print t1.isodate, "is later than ", t2.isodate > elif t1 == t2: > print t1.isodate, "is the same as ", t2.isodate > elif t1 < t2: > print t1.isodate, "is earlier than", t2.isodate > > print > > t1 = Time(2000,2,28) > print "The date after", t1.d, "is", t1.plus(day=1).d > t1 = Time(2001,2,28) > print "The date after", t1.d, "is", t1.plus(day=1).d > t1 = Time(2004,2,28) > print "The date after", t1.d, "is", t1.plus(day=1).d > > print > datestring1 = "2005/10/05 20:10:08" > datestring2 = "2005/10/05 20:10:06" > datestring3 = "2005/10/05 20:10:09" > > t1 = Time(*numsplit(datestring1)) > for datestring in (datestring2,datestring1,datestring3): > t2 = Time(*numsplit(datestring)) > > if t1 > t2: > print t1.d, t1.civiltime2, "is later than ", t2.d, t2.civiltime2 > elif t1 == t2: > print t1.d, t1.civiltime2, "is the same as ", t2.d, t2.civiltime2 > elif t1 < t2: > print t1.d, t1.civiltime2, "is earlier than", t2.d, t2.civiltime2 I'm using IDLE for Python 2.4, and put pfydate distribution in C:\Python24\Lib\site-packages\pfydate, as required by the page. How to install pyfdate. Save pyfdate.py into your PythonNN/Lib/site-packages directory. I copied it into C:\Python24\Lib\site-packages\pfydate Execution in IDLE produced: --------------------------------- Traceback (most recent call last): File "C:\Sandia_Meteors\Improved_Sentinel\Sentinel_Playground\date_example.py", line 1, in ? from pyfdate import * ImportError: No module named pyfdate --------------------------------- Looking in the Path Browser, I don't see pyfdate. I see PIL package and scipy package. Comments? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From deets at nospam.web.de Mon Aug 25 18:44:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Aug 2008 00:44:39 +0200 Subject: python - firefox dom/xpath question/issue In-Reply-To: References: Message-ID: <6hgqunFlobm0U2@mid.uni-berlin.de> bruce schrieb: > Hi. > > Got a test web page, that basically has two " the page via Firefox/Dom Inspector, I can create a test xpath query > "/html/body/form" which gets the target form for the test. > > The issue comes when I examine the page's source html. It looks like: > > > > > > > > . > . > . > > > > I've simplified things a bit... but basically, the 1st "html/body" is empty, > with the 2nd containing the data/nodes I need. If that's your document, it is invalid XML - XML only allows *one* root. Thus the parsers failure isn't too suprising. Try & wrap the whole document under an arbitrary root-tag, and included that as first part of the xpath. See if that helps. Diez From brtzsnr at gmail.com Wed Aug 13 17:29:07 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Wed, 13 Aug 2008 14:29:07 -0700 (PDT) Subject: callbacks in python References: <2b3a25c6-9985-4d05-8721-5a57a020e845@w7g2000hsa.googlegroups.com> Message-ID: <01a616b8-ae21-4dcc-a2cf-1a51af909634@m3g2000hsc.googlegroups.com> On Aug 14, 12:02?am, Fredrik Lundh wrote: > your use of the word "callback" is a bit unusual, and your example isn't > valid Python code, but it looks as if functools.partial might be what > you need: > > ? ? ?http://docs.python.org/lib/module-functools.html my current implementation is very similar to partial() :) (10x, i'll use partial from now on). however it seems that I don't understand very well positional and keyword arguments in python because I got the error described here: http://docs.python.org/ref/calls.html#calls (TypeError: f() got multiple values for keyword argument 'a') which confused me even more. so if you pass positional and keyword arguments to both partial() and function returned the order of passed arguments might be different than expected. i was looking for an implementation that somehow avoids this confusion. From rustompmody at gmail.com Sun Aug 17 12:19:21 2008 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 17 Aug 2008 21:49:21 +0530 Subject: python-mode errors Message-ID: When I start python mode I get the error: idle error: # -Wrong number of arguments : # 2" The Python mode version is 4.78 Is this a known problem? Thanks From michael at stroeder.com Thu Aug 14 14:20:22 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 14 Aug 2008 20:20:22 +0200 Subject: Fixed-length text file to database script In-Reply-To: References: Message-ID: <8k9en5-8i8.ln1@nb2.stroeder.com> Larry Bates wrote: > While you are correct, that is not what the OP asked. There is no > reference to processing data prior to insertion into MySQL database. > Also the OP said they had a 1 day deadline. Larry, having a bad day? I'm confident that the OP is able to sort out *himself* what he needs. Also the 1 day deadline would not be an obstacle. Would it for you? Ciao, Michael. From steven at REMOVE.THIS.cybersource.com.au Tue Aug 5 05:47:57 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 05 Aug 2008 09:47:57 GMT Subject: very large dictionary References: <5c5e6d6e-04ef-4340-963f-d3825875b32c@e39g2000hsf.googlegroups.com> <6fftjvFb7ktoU2@mid.uni-berlin.de> <60FCF960-D1CD-4885-9F46-B5D7B798A9FF@gmail.com> <20080803224254.GG11163@tuva.opensoft.se> <6b690d0c-d817-4582-9dd1-9309b2d5cda1@e39g2000hsf.googlegroups.com> <00a78388$0$20302$c3e8da3@news.astraweb.com> <7ef44808-5f88-4860-8f3b-dcad586f6f53@i76g2000hsf.googlegroups.com> Message-ID: On Tue, 05 Aug 2008 01:20:08 -0700, Simon Strobl wrote: >> > I thought it would be practical not to create the dictionary from a >> > text file each time I needed it. I.e. I thought loading the .pyc-file >> > should be faster. Yet, Python failed to create a .pyc-file >> >> Probably a good example of premature optimization. > > Well, as I was using Python, I did not expect to have to care about the > language's internal affairs that much. I thought I could simply do > always the same no matter how large my files get. In other words, I > thought Python was really scalable. Yeah, it really is a pain when abstractions leak. http://www.joelonsoftware.com/articles/LeakyAbstractions.html >> Out of curiosity, how >> long does it take to create it from a text file? > > I do not remember this exactly. But I think it was not much more than an > hour. Hmmm... longer than I expected. Perhaps not as premature as I thought. Have you tried the performance of the pickle and marshal modules? -- Steven From castironpi at gmail.com Thu Aug 14 23:44:32 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 14 Aug 2008 20:44:32 -0700 (PDT) Subject: negative numbers are not equal... References: <48A4932F.4010302@gmail.com> Message-ID: <2e66b313-d2b1-4ca1-804f-6af79b252739@j22g2000hsf.googlegroups.com> On Aug 14, 4:31?pm, Wojtek Walczak wrote: > On Thu, 14 Aug 2008 18:23:21 -0300, ariel ledesma wrote: > > i see now, so i guess that's also why id() returns the same address for > > them as well... > > It just have to work like this. > > a is b > > is actually equal to: > > id(a) == id(b) > > so there is no other way for id() in such case. > > Hope this helps. > > -- > Regards, > Wojtek Walczak,http://www.stud.umk.pl/~wojtekwa/ For a= 6 b= a the test a is b should clearly return true. Python distinguishes what mathematics does not, between identity and equality. Clearly 5+4 and 6+3 - evaluate- to the same, but math doesn't define whether they are the same, and in some sense the question isn't asked ordinarily, or isn't debated. I want to infer that math doesn't define the 'is' relation as Python knows it. I feel the documentation should state, 'the interpreter is free to return a -new- equivalent non-identical object in the case of immutables.' My tests: >>> a= -6 >>> a is -6 False >>> -6 is -6 True I don't know a convincing argument for the truth of Is( -6, -6 ). Perhaps you could make one, or one for the permissibility of Is( a, b ) & ~Equal( a, b )... identical non-equivalent. From ckumwaka at googlemail.com Wed Aug 13 01:59:11 2008 From: ckumwaka at googlemail.com (kumwaka) Date: Tue, 12 Aug 2008 22:59:11 -0700 (PDT) Subject: gasp Message-ID: <65dba773-6441-424e-a019-dc1e493dddb7@v57g2000hse.googlegroups.com> I am a beginner in Python. Please tell me how to go about in downloading and installing the module gasp.I am using Python 2.5.2. From lists at cheimes.de Thu Aug 14 13:42:45 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 14 Aug 2008 19:42:45 +0200 Subject: Getting stdout using ctypes. In-Reply-To: References: Message-ID: <48A46E95.6000206@cheimes.de> Grant Edwards wrote: > If he's running Unix, he needs to replace the stdout file > descriptor (fd 1), with something that's connected to the > "write" end of a pipe. Then he needs to read the other > ("read") end of the pipe in his application. > > You do that using the dup2() system call: It's dangerous to mix streams and descriptors. Traditionally freopen() is used to redirect a standard stream to a file: http://www.gnu.org/software/libc/manual/html_mono/libc.html#Standard-Streams ? Function: FILE * freopen (const char *filename, const char *opentype, FILE *stream) This function is like a combination of fclose and fopen. It first closes the stream referred to by stream, ignoring any errors that are detected in the process. (Because errors are ignored, you should not use freopen on an output stream if you have actually done any output using the stream.) Then the file named by filename is opened with mode opentype as for fopen, and associated with the same stream object stream. If the operation fails, a null pointer is returned; otherwise, freopen returns stream. freopen has traditionally been used to connect a standard stream such as stdin with a file of your own choice. This is useful in programs in which use of a standard stream for certain purposes is hard-coded. In the GNU C library, you can simply close the standard streams and open new ones with fopen. But other systems lack this ability, so using freopen is more portable. From bdesth.quelquechose at free.quelquepart.fr Thu Aug 21 16:22:58 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 21 Aug 2008 22:22:58 +0200 Subject: How to simulate packages? In-Reply-To: <7d1b00d3-8c7d-4bce-860a-2e740ca52cd8@b2g2000prf.googlegroups.com> References: <7d1b00d3-8c7d-4bce-860a-2e740ca52cd8@b2g2000prf.googlegroups.com> Message-ID: <48adced6$0$32729$426a74cc@news.free.fr> Daniel a ?crit : > Hello, > > I have a project that I've decided to split into packages in order to > organize my code better. So what I have looks something like this > > src > -module1 > -mod1_file.py > -module2 > -mod2_file.py > > Everytime I run mod2_file.py I need to import mod1_file.py. Right now > I'm using an ugly little thing to do my import (see below). Isn't > there some python mechanism to handle packages? cf Gabriel's answer wrt/ Python's packages. > import os, sys > # add packages to path then finish importing > for dir in ['module1','module2']: > # how about this ugly thing to find adjacent directories for > imports > sys.path.append('\\'.join(os.path.dirname(__file__).split('\\') > [:len(os.path.dirname(__file__).split('\\'))-1]) + "\\" + dir) > > Any and all suggestions appreciated. Thanks in advance. A suggestion: os.path is about os independance when it comes to filesystem. Please read the whole doc for this module, and learn how to avoid writing system dependant code. From davideyork at gmail.com Tue Aug 5 17:50:34 2008 From: davideyork at gmail.com (David York) Date: Tue, 5 Aug 2008 14:50:34 -0700 Subject: Finding IP address of localhost via socket API (or other API) Message-ID: <38c9cdb10808051450q3912f70evdae9fd61950e09d2@mail.gmail.com> Does anybody know how to find the real IP address (e.g.: address visible to internet) of a machine via Python? In other words I have a machine with an IP address something like 192.168.1.5, an address given to me by a router. The router's address (and thus my machine's address) to the outside world is something realistic, 123.156.123.156 or whatever. How do I get that number? I've tried socket.getaddrinfo('localhost', None) but all I get is 127.0.0.1 as expected. How do I find out my machine's IP address as visible to the outside world? Thanks a lot. David -------------- next part -------------- An HTML attachment was scrubbed... URL: From qxyuestc at yahoo.cn Sat Aug 30 05:46:52 2008 From: qxyuestc at yahoo.cn (qxyuestc at yahoo.cn) Date: Sat, 30 Aug 2008 02:46:52 -0700 (PDT) Subject: How to place menu on the bottom Message-ID: <89fab7ac-c34c-453b-9dc2-e58215e3a666@i20g2000prf.googlegroups.com> #!/usr/bin/env python import sys import os from tkinter import * def callback(self): #int this snippet, all menu entries use the same callback... print("callback") class DemoMenu(): def __init__(self): self.dataTemp = "" self.createWidgets() def createWidgets(self): # create application GUI self.rootWin = Tk() self.rootWin.minsize(width=800, height=600) self.rootWin.maxsize(width=800, height=600) self.rootWin.title = ("JoeQ Menu test...") self.mainFrame = Frame(self.rootWin) self.createMenu() def createMenu(self): # create menu menuFrame = Frame(self.rootWin) menuFrame.pack(side=BOTTOM, fill=X) menuBar = Menu(menuFrame, tearoff=1) filemenu = Menu(menuBar, tearoff=0) filemenu.add_command(label="Open...", command=callback) filemenu.add_separator() filemenu.add_command(label="Exit", command=callback) menuBar.add_cascade(label="File", menu=filemenu) self.rootWin.config(menu=menuBar) return menuBar def start(self): self.rootWin.mainloop() if __name__ == '__main__': demomenu = DemoMenu() demomenu.start() ###################################################### I want to place the menu on the bottom (menuFrame.pack(side=BOTTOM, fill=X)). But it does not work. Why? From zancudero at gmail.com Fri Aug 8 07:23:45 2008 From: zancudero at gmail.com (Alexei Zankevich) Date: Fri, 8 Aug 2008 14:23:45 +0300 Subject: regular expressions. In-Reply-To: References: <23cd7bec-264e-4a1d-a285-4683b48bf99d@a21g2000prf.googlegroups.com> Message-ID: <7df72c080808080423q18995752pb56abefd9cd8b968@mail.gmail.com> Use the print statement: import re vowel = r'[aeiou]' print re.findall(vowel, r"vowel") Alexey On Fri, Aug 8, 2008 at 2:17 PM, Atul. wrote: > > > Yes. You didn't paste the traceback into your message. > > > > >>> import re > > >>> vowel = r'[aeiou]' > > >>> re.findall(vowel, r"vowel") > > > > ['o', 'e'] > > > > It works as expected here. > > > > Peter > > When I key this input in IDLE it works but when I try to run the > module it wont work. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Wed Aug 13 17:02:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Aug 2008 23:02:35 +0200 Subject: callbacks in python In-Reply-To: <2b3a25c6-9985-4d05-8721-5a57a020e845@w7g2000hsa.googlegroups.com> References: <2b3a25c6-9985-4d05-8721-5a57a020e845@w7g2000hsa.googlegroups.com> Message-ID: Alexandru Mosoi wrote: > does anyone know a nice implementation of callbacks in python? i have > issues mixing named & unamed parameters. i want build a callback over > a function such that some parameters are passed when callback is > created and the rest are passed when the function is called. > > example: > callback = Callback(function, x=1, y) > callback(z, t=4, u) your use of the word "callback" is a bit unusual, and your example isn't valid Python code, but it looks as if functools.partial might be what you need: http://docs.python.org/lib/module-functools.html From davidreynon at gmail.com Thu Aug 14 11:55:04 2008 From: davidreynon at gmail.com (korean_dave) Date: Thu, 14 Aug 2008 08:55:04 -0700 (PDT) Subject: for y in range (0,iNumItems)--> not in order? References: <8514d915-95bf-4e57-a16a-68866e0ad789@l42g2000hsc.googlegroups.com> Message-ID: hahah true. Sorry folks. I am running a third party scripting machine that uses python. It's the third-party program that is at fault. More detail involved that you don't need to know, but it's not python's "fault". Sorry for the inconvenience. On Aug 14, 11:47?am, Fredrik Lundh wrote: > korean_dave wrote: > > Still the same output... > > > Here's the actual code... > > > ? ? for x in range(0,2): > > ? ? ? ? for y in range(0,27): > > ? ? ? ? ? ? for z in range(0,15): > > ? ? ? ? ? ? ? ? print(str(x) + " " + str(y) + " " + str(z)) > > umm. ?that's even less related to your original output than your earlier > code sample. > > $ python actual_code.py > 0 0 0 > 0 0 1 > 0 0 2 > 0 0 3 > 0 0 4 > ... > 1 26 10 > 1 26 11 > 1 26 12 > 1 26 13 > 1 26 14 > > please do a little more debugging on your own machine before claiming > that fundamental python features that's been around for ages suddenly > won't work. > > From akonsu at gmail.com Sat Aug 16 18:46:23 2008 From: akonsu at gmail.com (akonsu) Date: Sat, 16 Aug 2008 15:46:23 -0700 (PDT) Subject: how to add property "dynamically"? Message-ID: hello, i need to add properties to instances dynamically during run time. this is because their names are determined by the database contents. so far i found a way to add methods on demand: class A(object) : def __getattr__(self, name) : if name == 'test' : def f() : return 'test' setattr(self, name, f) return f else : raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name)) this seems to work and i can invoke method test() on an object. it would be nice to have it as property though. so i tried: class A(object) : def __getattr__(self, name) : if name == 'test' : def f() : return 'test' setattr(self, name, property(f)) return f else : raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name)) but this does not work, instance.test returns a callable but does not call it. i am not an expert in python, would someone please tell me what i am doing wrong? thanks konstantin From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 21 11:14:12 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 21 Aug 2008 17:14:12 +0200 Subject: getattr() on nested functions? In-Reply-To: References: <48abe483$0$31875$426a74cc@news.free.fr> <48AC322E.9000404@arimaz.com> <48ad5980$0$4634$426a74cc@news.free.fr> Message-ID: <48ad8631$0$3819$426a74cc@news.free.fr> Gabriel Rossetti a ?crit : > Bruno Desthuilliers wrote: >> Gabriel Rossetti a ?crit : >>> Terry Reedy wrote: >> (snip) >>>> Unlike the class approach, this requires recreating the constant >>>> functions and dict with each call to _test. Quick to write but a >>>> bit 'dirty', in my opinion. Another standard idiom is to set up the >>>> constants outside the function: >>>> >>>> def request(params): >>>> pass >>>> def submit(params, values): >>>> pass >>>> def update(params, values): >>>> pass >>>> def delete(params): >>>> pass >>>> dispatch = {'request':request, 'submit':submit, 'update':update, >>>> 'delete':delete} >>>> >>>> def _test(self, action, *args): >>>> return resultToXmo(dispatch[action](*args)) >>> >>> That's how I had done it originally (before the use of eval()), but >>> in this case also, since the functions are still nested, >> >> Uh ??? You probably want to re-read the above code snippet. >> > Uh...yes, I didn't see the external/parent function was no longer there. > I prefer to nest mine though because I have several parent functions for > different tasks, so each child/nested function has a diff. > implementation, I find that cleaner than having n*4+n top-level > functions (+ n dicts), e.g. I prefer this : > > def __task1(self, action, *args): > def request(params): > pass > def submit(params, values): > pass > def update(params, values): > pass > def delete(params): > pass > return resultToXml(locals()[action](*args)) > > def __task2(self, action, *args): > def request(params): > pass > def submit(params, values): > pass > def update(params, values): > pass > def delete(params): > pass > return resultToXml(locals()[action](*args)) > > > over this : > (snip) > > > I could use your callable approach, but like you said it may not be > worth the trouble. The "trouble" I was talking about was not with using callable objects, but with trying to hack func.func_code to extract nested functions (if ever possible). But anyway... The point of using callable objects is to avoid going thru the whole "setup" part again and again and again. Now if all your task functions only differ by the dispatch dict, there's at least another ways to avoid this runtime repetition - as well as coding repetition FWIW (warning : untested code): def _make_task(func): dispatch = func() def _task(action, *args): return resultToXml(dispatch[action](*args)) _task.__name__ = _task.func_name = func.__name__ return _task @_make_task def _task1(): def request(params): pass def submit(params, values): pass def update(params, values): pass def delete(params): pass return locals() HTH From deets at nospam.web.de Sat Aug 2 11:26:36 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 02 Aug 2008 17:26:36 +0200 Subject: applescript/python question In-Reply-To: References: Message-ID: <6fjclcFc0dh8U1@mid.uni-berlin.de> jyoung79 at kc.rr.com schrieb: > I can't seem to figure this out. I just installed Python 2.5.2 a few days ago on my OS X 10.4.11 > system. It runs fine and if I type "Python -V" in the Terminal it outputs "Python 2.5.2" which is > correct. However, if I try to run a 'do shell script' in AppleScript which I'm wanting to run a Python > program, it reverts to using Python 2.3. For example, if I run this code in AppleScript: > > -------------------- > set p to "#!/usr/bin/python > import sys > print sys.version[:3]" > set x to do shell script "Python -c \"" & p & "\"" > return x > -------------------- > > I get "2.3". Does anyone have any ideas why AppleScript is using the older version of Python? > Is there a way to fix this? I guess the shebang is simply ignored - the actual interpreter is fetched from the "Python -c"-line. It's a bit weird that there is Python with a capital P, but what happens if you change that to Python2.5 for example? Diez From boblatest at googlemail.com Wed Aug 27 07:15:48 2008 From: boblatest at googlemail.com (boblatest at googlemail.com) Date: Wed, 27 Aug 2008 04:15:48 -0700 (PDT) Subject: How can this script fail? References: <4129c566-de92-433e-bc3f-f1dcbc255c46@m3g2000hsc.googlegroups.com> Message-ID: <48b2013f-0103-4f00-8597-b1ccad2425cf@k13g2000hse.googlegroups.com> On Aug 27, 1:08?pm, "M.-A. Lemburg" wrote: > I don't think this is related to IDLE or your setup. The odbc > module is very old and unmaintained, so it's possible that Windows > doesn't find some system DLLs needed for it to work. Please note that 1) I can type "import odbc" directly into the IDLE shell without getting an error message, but only BEFORE I've run a script that tries to import odbc. 2) The same script runs fine under PyWin (which I don't like much as an environment). > If you're looking for a reliable Python ODBC interface, I'd suggest > you have a look at our mxODBC: Thanks, but I'm working on some kind of guerilla project of which my employer doesn't know, so they won't spend any money on a commercial product. robert From krishnan.sid at gmail.com Wed Aug 6 18:59:54 2008 From: krishnan.sid at gmail.com (Sid K) Date: Wed, 6 Aug 2008 15:59:54 -0700 (PDT) Subject: Adding Microsoft objects in Boa Constuctor Palette Message-ID: <26b16796-f717-40bb-b6e9-a918598b44e2@d77g2000hsb.googlegroups.com> This is what I wanted to do: Add Microsoft Active objects like Excel sheets and Word files to the Palette in Boa Constructor. There is a User tab in the GUI builder menu, but I'm not sure how to use/enable it. 1. Does anyone know how to do this? 2. Is anyone aware of any work that is currently going on to support adding Microsoft objects in Boa. 3. Does any other Python GUI creator/editor exist out there that can do this? 4. How would one add an excel sheet to a wx.Panel in general w/ or w/o Boa? Looking forward to replies... -SK From poojaangali at gmail.com Fri Aug 15 05:59:18 2008 From: poojaangali at gmail.com (pooja) Date: Fri, 15 Aug 2008 02:59:18 -0700 (PDT) Subject: EARN MONEY $1500-$5000 PER MONTH Message-ID: EARN MONEY $1500-$5000 PER MONTH SIMPLE ONLINE SURVEY CREATE UR ACCOUNT AND EARN IMMEDIATLY ************************************************************************* http://www.AWSurveys.com/HomeMain.cfm?RefID=kingraja666 ************************************************************************* From Edwin.Madari at VerizonWireless.com Mon Aug 11 08:23:05 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Mon, 11 Aug 2008 08:23:05 -0400 Subject: for x,y in word1, word2 ? In-Reply-To: Message-ID: <20080811122317.8A46A1E4005@bag.python.org> sounds like *soundex* is what you are looking for. google soundex regards Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of Marc 'BlackJack' Rintsch Sent: Monday, August 11, 2008 3:09 AM To: python-list at python.org Subject: Re: for x,y in word1, word2 ? On Sun, 10 Aug 2008 23:14:50 -0700, ssecorp wrote: > I know zip but lets say I have a word "painter" and I want to compare it > to a customer's spelling, he might have written "paintor" and I want to > check how many letters are the same. > > Now I know how I could do this, it is not hard. I am just wondering if > these is any specific simple syntax for it. No special syntax for that, but you can combine the `sum()` function, a generator expression and `zip()`: In [40]: sum(int(a == b) for a, b in zip('painter', 'paintor')) Out[40]: 6 Or this way if you think it's more clear: In [41]: sum(1 for a, b in zip('painter', 'paintor') if a == b) Out[41]: 6 Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From dudeja.rajat at gmail.com Fri Aug 29 05:37:33 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Fri, 29 Aug 2008 10:37:33 +0100 Subject: problem with execv command Message-ID: Hi, I'm facing problem with the execv command: my command is : os.execv(' C:\Program Files\Subversion\bin\svn ', ( 'list', ' \" http://subversion.stv.abc.com/svn/Eng \" ' ) ) The error I'm getting is : OSError: [Errno 22] Invalid argument I tried using a variable for http path but still I'm getting the same error Please help. -- Regards, Rajat From rafesacks at gmail.com Fri Aug 15 11:16:38 2008 From: rafesacks at gmail.com (Rafe) Date: Fri, 15 Aug 2008 08:16:38 -0700 (PDT) Subject: Parsing and Editing Source References: Message-ID: On Aug 15, 9:21 pm, "Paul Wilson" wrote: > Hi all, > > I'd like to be able to do the following to a python source file > programmatically: > * Read in a source file > * Add/Remove/Edit Classes, methods, functions > * Add/Remove/Edit Decorators > * List the Classes > * List the imported modules > * List the functions > * List methods of classes > > And then save out the result back to the original file (or elsewhere). > > I've begun by using the tokenize module to generate a token-tuple list > and am building datastructures around it that enable the above > methods. I'm find that I'm getting a little caught up in the details > and thought I'd step back and ask if there's a more elegant way to > approach this, or if anyone knows a library that could assist. > > So far, I've got code that generates a line number to token-tuple list > dictionary, and am working on a datastructure describing where the > classes begin and end, indexed by their name, such that they can be > later modified. > > Any thoughts? > Thanks, > Paul I can't help much...yet, but I am also heavily interested in this as I will be approaching a project which will require me to write code which writes code back to a file or new file after being manipulated. I had planned on using the inspect module's getsource(), getmodule() and getmembers() methods rather than doing any sort of file reading. Have you tried any of these yet? Have you found any insurmountable limitations? It looks like everything needed is there. Some quick thoughts regarding inspect.getmembers(module) results... * Module objects can be written based on their attribute name and __name__ values. If they are the same, then just write "import %s" % mod.__name__. If they are different, write "import %s as %s" % (name, mod.__name__) * Skipping built in stuff is easy and everything else is either an attribute name,value pair or an object of type 'function' or 'class'. Both of which work with inspect.getsource() I believe. * If the module used any from-import-* lines, it doesn't look like there is any difference between items defined in the module and those imported in to the modules name space. writing this back directly would 'flatten' this call to individual module imports and local module attributes. Maybe reading the file just to test for this would be the answer. You could then import the module and subtract items which haven't changed. This is easy for attributes but harder for functions and classes...right? Beyond this initial bit of code, I'm hoping to be able to write new code where I only want the new object to have attributes which were changed. So if I have an instance of a Person object who's name has been changed from it's default, I only want a new class which inherits the Person class and has an attribute 'name' with the new value. Basically using python as a text-based storage format instead of something like XML. Thoughts on this would be great for me if it doesn't hijack the thread ;) I know there a quite a few who have done this already. Cheers, - Rafe From http Fri Aug 29 21:43:29 2008 From: http (Paul Rubin) Date: 29 Aug 2008 18:43:29 -0700 Subject: posix semaphore support? References: Message-ID: <7x3aknjn0e.fsf@ruckus.brouhaha.com> Neal Becker writes: > Does that provide semaphores between unrelated processes? The threading module is just for threads of a single process. There's an shm module that implements semaphores: http://nikitathespider.com/python/shm/ From harrrrpo at gmail.com Sat Aug 23 18:29:09 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Sun, 24 Aug 2008 01:29:09 +0300 Subject: Imports awareness in Imported modules problem Message-ID: <538050a90808231529s61855330r1ec68048847ef241@mail.gmail.com> Hello , The problem I'm asking about is how can imported modules be aware of other imported modules so they don't have to re-import them (avoiding importing problems and Consicing code and imports ) Take Example :- in A.py :- import B print dir() # no problems we can see B which contain re module and C module B.C.W() # our problem here we get an empty list in B.py :- import re import C in C.py :- def W(): print dir()# when called from A we get [] though other imports has been made to re and others my goal is basically making W() aware of the re module when called from A ---- why am i doing this in the first place I'm in the process of a medium project where imports of modules start to make a jungle and i wanted all needed imports to be in a single file (namely __init__.py) and then all imports are made once and other modules feel it another reason to do this that my project is offering 2 interfaces (Console and GUI through Qt) and i needed a general state class ( whether i'm in Console or GUI mode) to be available for all , for determining state and some public functions ,and just injecting Imports everywhere seems a bad technique in many ways (debugging , modifying ...etc ) in PHP "Require" would do the trick neatly ... so is there is something I'm missing here or the whole technique is bad in which case what do you suggest Thanks, Regards, Mohamed Yousef From tkpmep at gmail.com Sat Aug 2 22:41:03 2008 From: tkpmep at gmail.com (Thomas Philips) Date: Sat, 2 Aug 2008 19:41:03 -0700 (PDT) Subject: Teething troubles with Python on a Mac Message-ID: <6651edd6-d47f-4e10-bf0b-0875190b9bc2@a1g2000hsb.googlegroups.com> I've got a new iMac, have installed Python 2.5.2 on it, and am now trying to run my existing Python programs on it (these are typically number crunching programs that I run from IDLE). Some things work, while others don't, and as this is my first time grappling with Unix and MacOS X, I appreciate some guidance on how to get up and running. Here are details of my setup interspersed with my woes and my questions. Your assistance is greatly appreciated. Item 1. I downloaded and installed 2.5.2 from python.org. Runs fine, it installed a MacPython directory under applications, which has a few icons, including IDLE. However, I have absolutely NO idea where all the Python files are kept. Question 1: How can I locate the Python installation? There a few files under Applications > MacPython 2.5, but this is clearly not the entire installation. Question 2: In Finder, If I click on Search For > Past week, I can see a sequence of folders under the horizontal scroll bar at the bottom of the window, allowing me to determine that some files that were placed under Applications > MacPython 2.5> Extra> Demo. But I do not seem to be able to see the sequence of folders under the horizontal scroll bar in any finder window. What do I need to do to make the folder sequence visible in all Finder Windows? Item 2. I downloaded and installed the SciPy superpack from Macinscience,org. Scipy seems to import correctly into the Python 2.5.1 that comes with the Mac, but i cannot import it into MacPython 2.5.2. Question 3. What do I have to do in order to make SciPy work with both Python 2.5.1 (that comes with the Mac) and 2.5.2 (that I installed myself)? Item 3. I accidentally clicked on something (not sure what) and suddenly found the path to the numpy folder was Macintosh HD > Developer > SDKs > MacOSX10.5.sdk>System> Library>Frameworks>Python.framework>Versions>2.5>extras>lib>Python>numpy. This is insane!!! Where would the superpack have installed SciPy, and how can I find it? Question 4. How do I get MacPython 2.5.2 to see SciPy, NumPy etc. Question 5. How can I find the current value of the PYTHONPATH environment variable, and how can I edit it and add a directory in which I keep my Python programs. Question 6. Apparently there's a Property List Editor that must be used to create a file called ~ /.MacOSX/environment.plist. I can't find a directory called ~/.MacOSX. Is this a hidden directory? Item 4. I opened a terminal window, and typed ipython. Here's what I got: Welcome to IPython. I will try to create a personal configuration directory where you can customize many aspects of IPython's functionality in: /Users/tom/.ipython WARNING: Installation error. IPython's directory was not found. Check the following: The ipython/IPython directory should be in a directory belonging to your PYTHONPATH environment variable (that is, it should be in a directory belonging to sys.path). You can copy it explicitly there or just link to it. IPython will create a minimal default configuration for you. Ipython actually runs once I hit enter, but I do not seem to be able to import and run my programs. Question 7. What is this cryptic message all about? I'm completely confused. I never thought I'd say this, but it actually seemed a lot easier to get Python and any associated programs up and running on Windows! I suspect that a large fraction of my troubles are due to the fact that I am brand new to the Mac and to Unix, but I bought the Mac in part because I thought that using it was effortless. Thank you in advance for your help. Sincerely Thomas Philips From JohnBMudd at gmail.com Mon Aug 25 14:50:07 2008 From: JohnBMudd at gmail.com (JohnMudd) Date: Mon, 25 Aug 2008 11:50:07 -0700 (PDT) Subject: os.popen() interferes with os.fork()? Message-ID: On Linux I get a "close failed: [Errno 10] No child processes" msg for each fork. But only if I have a pipe open. I don't understand the connection between the popen and the forks. Am I doing something wrong? #! /usr/bin/env python import os import sys import time p = os.popen('top -b -d1') n = 3 t1 = time.time() for i in range(n): pid = os.fork() if pid == 0: sys.exit(0) delay = time.time() - t1 print 'rate: %.1f fork/sec' % (n/delay) From kay.schluehr at gmx.net Wed Aug 13 02:31:38 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 12 Aug 2008 23:31:38 -0700 (PDT) Subject: Python as a Testing Language - TTCN-3 Comparison References: <001701c8fc84$451cd820$0b02a8c0@afelty> Message-ID: <032c4153-c979-4788-8b6b-bc46a5550fe5@c58g2000hsc.googlegroups.com> Bernard Stepien wrote: > 1. TTCN-3 is an international standard that comes among other > things with very precise semantics, thus everyone in the world using it > will talk exactly the same language. This also reduces considerably the > amount of documentation you need for the next of kin after the developer > that has developed a test suites or tool moves on. That's what industry standards are for. If you choose Python you want to get work done fast and in a somewhat playful way and that's *not* the goal of development departments of big corps. Departments want to receive money for maintaining projects ad infinitum. Providing tools that make one-third of the staff obsolete might be welcomed by higher management and controllers but definitely not by lower management and engineers i.e. by your boss and your coworkers. Development process and tool standards like TTCN-3 are sent from heaven for department leaders because they can pretend to manage test development like a factory with replaceable test workers. This indeed increases efficiency on average, lowers dependencies on creativity of individual coders and makes their job a bit safer. I've actually nothing to criticize about them because their behavior is entirely rational and if I was in their position I'd fill the role with a bit of cynicism and responsibility for the working class who want to have a well paid job no matter what they do. Python is almost always never a good choice because for this because it is too easy for a coder to gain power over his own work [1]. Known exceptions: Python is good for small companies who can be aggressive and have not much to lose but also for small development departments in big corps with not much workforce. If there is pressure for innovation Python is o.k. as well. But then no one gives a shit on TTCN-3 and could care less about being compliant with it. Python has something in common with TTCN-3 according to your description: it is a language every programmer can learn and understand within a short period of time. But unlike TTCN-3 it is even useful. [1] Since we talk about testing in the Telco industry. I've done this a lot in the past and have written test frameworks in Python myself. They are very specific but there is one thing I'd like to advertise, namely the use of the right fundamental data structure for representing, parsing, and altering binary data for the tester: http://www.fiber-space.de/EasyExtend/doc/p4d/bytelets.html Here is some more context: http://pypi.python.org/pypi/P4D From __peter__ at web.de Fri Aug 22 11:55:13 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 22 Aug 2008 17:55:13 +0200 Subject: Should Python raise a warning for mutable default arguments? References: <00becb2d$0$20312$c3e8da3@news.astraweb.com> Message-ID: bearophileHUGS at lycos.com wrote: > DrScheme is an implementation of Scheme that is very newbie-friendly. > It has several limited sub-languages, etc. > > So maybe a command line option can be added to Python3 ( - > newbie ? :-) ) that just switches on similar warnings, to help newbies > (in schools, where there's a teacher that encourages to always use > that command line option) avoid some of the most common traps. Or maybe bundle pychecker with idle? $ cat tmp.py def test(x, a=[]): a.append(x) return a for i in range(5): print test(i) $ pychecker tmp.py Processing tmp... [0] [0, 1] [0, 1, 2] [0, 1, 2, 3] [0, 1, 2, 3, 4] Warnings... tmp.py:2: Modifying parameter (a) with a default value may have unexpected consequences Though it might be interesting to ask a newbie what he expects when warned of "unexpected consequences" ;) Peter From tjreedy at udel.edu Fri Aug 22 03:36:35 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 22 Aug 2008 03:36:35 -0400 Subject: Sorted Returns List and Reversed Returns Iterator In-Reply-To: References: <7f5690e0-0dcc-4d82-a177-6fdbcfa3f8e7@l33g2000pri.googlegroups.com> <48c54158-494f-4e0d-bcbd-b7dc05a90001@v39g2000pro.googlegroups.com> <490d4841-5595-4132-b01c-15f1d77a4414@a8g2000prf.googlegroups.com> <691c3dc2-44ae-43c6-ad4f-3f5e136f5ed1@a1g2000hsb.googlegroups.com> Message-ID: Peter Otten wrote: > ++imanshu wrote: >> I agree. Iterator is more flexible. I disagree. Neither is more flexible. You can iter the list returned by sorted and list the iter returned by reversed. Both do the minimum work necessary. See below. > Together and both might have returned the same types. True, but only by doing potentially unnecessary work and requiring the caller to do potentially unnecessary work that might even prevent the program from working. This is less flexible. Suppose sorted now returns alist with 50 million items. Suppose it instead returned iter(alist) but the caller wants to randomly index the items. Since the caller could not access the existing 50 million item list, the caller would have to make another 50 million item copy. This is non-trivial and might not even work do to memory limitations. > It's easy to generate a reversed sequence on the fly but impractical for a > sorted one. Python is taking the pragmatic approach here. To expand on this: sorting and reversing are algorithmically different operations. Sorting requires that one have all items in hand in a mutable sequence (list) for arbitrary re-ordering. Sorted works on any iterable and starts by making a new list. There is no point to not returning that list after it is sorted. It would be more work and less useful to do more. sorted(iterable, key=None, reverse=False): newlist = list(iterable) newlist.sort(key, reverse) return newlist Iterating over a concrete sequence in reverse order, on the other hand, is trivial. It would be more work and less useful to do more. def _reversed(seq): # 'hidden' generator function n = len(seq) while n: n -= 1 yield seq[n] def reversed(seq): if hasattr(seq, '__reversed__'): return seq.__reversed__() # I presume this is tried first else: return _reversed(seq) # generic fall-back Terry Jan Reedy From rhamph at gmail.com Mon Aug 4 17:04:52 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 4 Aug 2008 14:04:52 -0700 (PDT) Subject: Using two pythons in an application References: Message-ID: <3ca4d946-e2b0-4c2b-ac71-f760f9caaeb5@a21g2000prf.googlegroups.com> On Aug 3, 5:43?pm, Allen wrote: > Larry Bates wrote: > > Allen wrote: > >> I'm in the process of developing an application that will use Python > >> for a scripting support. ?In light of the upcoming changes to Python, > >> I was wondering if it is possible to link to and use two different > >> versions of ?Python so that in the future, scripts could be migrated > >> to the new version, and older scripts would still work as well. ?If so > >> are there any code examples of this. > > >> Brian Vanderburg II > > > Unlike languages you pay for, Python has on real motivation to > > "obsolete" old versions of Python (e.g. to force you to pay of an > > upgrade). ?You can still get version 1.5.2 of Python and it is MANY > > years old and most could consider quite obsolete. ?I just would not > > worry about it and stick with 2.5/2.6 for development and begin looking > > at Python 3.0 so I can learn what's new and exciting. > > > -Larry > > I agree. ?I had wanted for scripts of the program to be able to use the > new string format method that is only in py3k, but I'm currently looking > into other template solutions. That should work in 2.6 (sans bugs). To answer your original question, no, you can't load more than one version of python within a single process. The best you can do is running in a child process. From wuwei23 at gmail.com Tue Aug 12 09:49:04 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 12 Aug 2008 06:49:04 -0700 (PDT) Subject: Suggestion for converting PDF files to HTML/txt files References: Message-ID: <36e5683f-c46a-4bed-bd4c-269ba9e6ca86@q5g2000prf.googlegroups.com> On Aug 12, 11:13?pm, brad wrote: > Very neat program. Would be cool if it could easily integrate into other > py apps instead of being a standalone CLI tool. Perhaps, but I think you could get a long way using os.system(). From kyosohma at gmail.com Wed Aug 6 15:56:53 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 6 Aug 2008 12:56:53 -0700 (PDT) Subject: Run program from within Python References: <47eee9f1-c85d-4816-a204-8a11f178267d@d1g2000hsg.googlegroups.com> Message-ID: On Aug 6, 2:42?pm, frankrentef wrote: > Greetings all... > > Newbie to Python... need help with opening a file from within > Python... see the following code. > > import popen2 > stdout, stdin = popen2.popen2('c:\test\OpenProgram.exe 1 1') > keygen = stdout.read() > print "The keygen value is: %s" % keygen > > from the command line if I execute "OpenProgram.exe 1 1" a number is > returned. ?("1 1" are required to return the value needed.) Ultimately > I want to take that number and apply it to another script, but the > program is not running. > > Suggestions? > > NEWBIE to Python.. If you're using Python 2.4+, popen2 is deprecated. I recommend reading up on the subprocess module instead. Here's a couple links: http://blog.doughellmann.com/2007/07/pymotw-subprocess.html http://docs.python.org/lib/module-subprocess.html The first one also explains how to communicate with a process you opened. Mike From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 26 04:56:03 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 26 Aug 2008 10:56:03 +0200 Subject: What is class method? In-Reply-To: <31c553dc-b1f3-4a8c-b70e-024c751fd352@p10g2000prf.googlegroups.com> References: <31c553dc-b1f3-4a8c-b70e-024c751fd352@p10g2000prf.googlegroups.com> Message-ID: <48b3c4f3$0$30971$426a74cc@news.free.fr> MeTheGameMakingGuy a ?crit : > On Aug 24, 6:32 pm, Hussein B wrote: >> Hi, >> I'm familiar with static method concept, but what is the class method? >> how it does differ from static method? when to use it? >> -- >> class M: >> def method(cls, x): >> pass >> >> method = classmethod(method) >> -- >> Thank you for your time. > > Firstly, don't use method = classmethod(method). Decorators are far > better. The following code has the same effect: > > class M: > @classmethod > def method(cls, x): > pass > > Far more readable, right? Yes, but will only work with Python >= 2.4. There are cases where you want to keep compatibility with Python 2.3... > Class methods are useful if you've got lots of inheritance happening. > The first argument passed in is the class calling the method. Handy > for a mix-in: it can add methods affecting the actual class it's mixed > into, rather than messing with the mix-in itself. I'm not sure I get your point here. As far as I'm concerned, classmethods are useful anywhere you need to work on the class object itself. From Matt.Fielding at rockstarnewengland.com Tue Aug 12 11:49:49 2008 From: Matt.Fielding at rockstarnewengland.com (Matt Fielding (R* New England)) Date: Tue, 12 Aug 2008 11:49:49 -0400 Subject: Unable to lookup keys in dictionary In-Reply-To: Message-ID: I actually figured out the solution to my problem, of all times, right after I finished sending this mail. It seems P4Python returns a command as a dictionary, also inside of an array. The solution is in the following code: from P4 import P4, P4Exception p4 = P4() p4.port = "rsgnwep4s1:1666" p4.user = "mfielding" try: p4.connect() info = p4.run("info") info = info[0] print info s = info['serverVersion'] print s p4.disconnect() except P4Exception: for e in p4.errors: print e Matt Fielding IT Technician Rockstar New England ________________________________ From: python-list-bounces+matt.fielding=rockstarnewengland.com at python.org [mailto:python-list-bounces+matt.fielding=rockstarnewengland.com at python. org] On Behalf Of Matt Fielding (R* New England) Sent: Tuesday, August 12, 2008 11:27 AM To: python-list at python.org Subject: Unable to lookup keys in dictionary I am trying to run p4python API on top of python 2.5.2 and am extracting a dictionary from perforce. The following code returns the output that follows it: from P4 import P4, P4Exception p4 = P4() p4.port = "erased" #deleted p4.user = "erased" #deleted try: p4.connect() info = p4.run("info") print info p4.disconnect() except P4Exception: for e in p4.errors: print e Output: [{'userName': 'mfielding', 'clientRoot': 'c:\\perforce', 'monitor': 'enabled', 'serverRoot': 'H:\\p4root\\', 'serverVersion': 'P4D/NTX64/2007.3/143793 (2008/01/ 21)', 'serverDate': '2008/08/12 11:18:56 -0400 Eastern Daylight Time', 'clientAd dress': '10.24.20.97:1918', 'serverLicense': 'Mad Doc Software, Inc. 140 users ( support expired 2008/05/31) ', 'serverAddress': 'rsgnwep4s1.rockstar.t2.corp:166 6', 'clientHost': 'nwew-mfielding', 'security': 'enabled', 'password': 'enabled' , 'clientName': 'mfielding'}] I did this to test that I was receiving a dictionary back from the server, which I clearly am. I then followed by adding the following lines to the code: print info s = info[serverVersion] print s p4.disconnect() I would expect this to print out P4D/NTX64/2007.3/143793 (2008/01/23), but instead it spits out the following error: Traceback (most recent call last): File "test.py", line 10, in s = info[serverVersion] NameError: name 'serverVersion' is not defined Changing "s = info[serverVersion]" to "s = info['serverVersion']" only gives me another error, which is: Traceback (most recent call last): File "test.py", line 10, in s = info['serverVersion'] TypeError: list indices must be integers If anyone has any idea what is going on here, I would appreciate the help. I've spent a few hours over the past two days trying to figure this little quirk out, but to no avail. Matt Fielding IT Technician Rockstar New England -------------- next part -------------- An HTML attachment was scrubbed... URL: From arunasunil at gmail.com Wed Aug 13 21:24:01 2008 From: arunasunil at gmail.com (arunasunil at gmail.com) Date: Wed, 13 Aug 2008 18:24:01 -0700 (PDT) Subject: Python packages on the Mac References: <0a7f3c13-d901-4c6b-8d31-554daf0aa4a7@p10g2000prf.googlegroups.com> <65cd8d6d-c8b3-4460-a7f9-900cdf14a215@a70g2000hsh.googlegroups.com> Message-ID: On Aug 5, 5:33?am, Jeff wrote: > On Aug 4, 11:20?pm, arunasu... at gmail.com wrote: > > > Hi, > > > I would like to copy the contents of the PythonFramework.pkg folder > > and run python without having to run the installer on the Mac. On > > windows it's simple to copy the contents of the python folder and the > > python dll's. How can this be done on the Mac? > > > Thanks > > Sunil > > Are you trying to make a script for easy distribution without having > to first install Python? ?Look here:http://undefined.org/python/py2app.html This is cool. Will this work with Python 2.5.2? Sunil From sibteym at infotechsw.com Wed Aug 27 03:30:36 2008 From: sibteym at infotechsw.com (Sibtey Mehdi) Date: Wed, 27 Aug 2008 13:00:36 +0530 Subject: Memory Error Message-ID: <044701c90816$cc73be90$5fc513ac@pwit.com> I am using the cPickle module to serialization and de-serialization of heavy python object (80 MB). When I try to save the object it gives the memory Error. Any one can help me out of this problem. I am pickling the object as: def savePklFile(pickleFile, data): pickledFile = open(pickleFile, 'wb') cPickle.dump(data, pickledFile, -1) pickledFile.close() my system has 2 GB of RAM. Thanks, Sibtey -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sat Aug 9 17:49:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 09 Aug 2008 17:49:09 -0400 Subject: Ascii to binary conversion In-Reply-To: References: Message-ID: azrael wrote: > Any idea how to easily write a function that recieves a character or > string and returns a binary number like: > ascii("1") is converted to bin("00110001") Other alternatives in 2.6 (I believe) and 3.0: >>> 0b00111010101 469 >>> b='111010101' >>> eval('0b'+b) 469 >>> '{0:b}'.format(469) '111010101' From ken at seehart.com Mon Aug 25 19:37:29 2008 From: ken at seehart.com (Ken Seehart) Date: Mon, 25 Aug 2008 16:37:29 -0700 Subject: SocketServer and long-polling connections Message-ID: <48B34239.1040408@seehart.com> I apologize if this message is a repeat. It looks like didn't get received. I'm using SocketServer to implement a local server that serves comet long-polling connections. How do I increase the maximum number of open connections? Currently it is limited to about 8 I think. More than that and it seems to block on opening more connections until one of the other connections releases. Is it possible that the limit may actually be imposed by the client in some bizarre way? In this case all of the clients are local, and are multiple instances of the same mozilla activex DLL. - Ken From vel.accel at gmail.com Thu Aug 28 01:30:31 2008 From: vel.accel at gmail.com (dieter) Date: Wed, 27 Aug 2008 22:30:31 -0700 (PDT) Subject: Process "Killed" Message-ID: <48a554c6-eeb3-4605-bdf2-a4b7de17bca3@b1g2000hsg.googlegroups.com> Hi, Overview ======= I'm doing some simple file manipulation work and the process gets "Killed" everytime I run it. No traceback, no segfault... just the word "Killed" in the bash shell and the process ends. The first few batch runs would only succeed with one or two files being processed (out of 60) before the process was "Killed". Now it makes no successful progress at all. Just a little processing then "Killed". Question ======= Any Ideas? Is there a buffer limitation? Do you think it could be the filesystem? Any suggestions appreciated.... Thanks. The code I'm running: ================== from glob import glob def manipFiles(): filePathList = glob('/data/ascii/*.dat') for filePath in filePathList: f = open(filePath, 'r') lines = f.readlines()[2:] f.close() f = open(filePath, 'w') f.writelines(lines) f.close() print file Sample lines in File: ================ # time, ap, bp, as, bs, price, vol, size, seq, isUpLast, isUpVol, isCancel 1062993789 0 0 0 0 1022.75 1 1 0 1 0 0 1073883668 1120 1119.75 28 33 0 0 0 0 0 0 0 Other Info ======== - The file sizes range from 76 Kb to 146 Mb - I'm running on a Gentoo Linux OS - The filesystem is partitioned and using: XFS for the data repository, Reiser3 for all else. From fredrik at pythonware.com Tue Aug 19 07:20:00 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Aug 2008 13:20:00 +0200 Subject: WindowsXP/ CTypes - How to convert ctypes array to a string? In-Reply-To: References: Message-ID: dudeja.rajat at gmail.com wrote: > I've used CTYPES module to access a function from a dll. This function > provides me the version of the dll. This information is accessible to > me as an array of 4 long inetegers. information as : > 2, 1, 5, 0 > > I want to display these elements concatenated as "v2.1.5.0". This > string ( I'm thinking of writing the above 4 array elements to a > string) is to be displayed as label in a GUI ( the GUI used is Tk) > > Please suggest how can I write these elements to a string to get me > the desired results as "v2.1.5.0". And, is writing to a string is > right way? any special reason why you're not reading replies to your previous post? here's what I wrote last time. expecting that Python/ctypes should be able to figure out that you want an array of 4 integers printed as a dot-separated string is a bit optimistic, perhaps. but nothing that a little explicit string formatting cannot fix: >>> from ctypes import * >>> versionArr = c_long * 4 >>> version = versionArr(1, 2, 3, 4) >>> "%d.%d.%d.%d" % tuple(version) '1.2.3.4' inserting a "v" in the format string gives you the required result: >>> "v%d.%d.%d.%d" % tuple(version) 'v1.2.3.4' From ptmcg at austin.rr.com Sun Aug 3 04:39:22 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 3 Aug 2008 01:39:22 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> <7360bd9a-4ff6-4e75-821c-eabc88ee6258@u6g2000prc.googlegroups.com> Message-ID: <94fcd03e-739a-4db9-b386-65545aa45359@34g2000hsh.googlegroups.com> On Jul 31, 6:15?pm, Paul McGuire wrote: > On Jul 28, 12:15?pm, Kay Schluehr wrote: > > > > > > > On 28 Jul., 06:42, "Russ P." wrote: > > > > On Jul 27, 8:58 pm, castironpi wrote: > > > > > On Jul 27, 2:39 pm, Bruno Desthuilliers > > > > > wrote: > > > > > Derek Martin a ?crit : > > > > > > It's bad programming, but the world is full of bad programmers, and we > > > > > > don't always have the choice not to use their code. ?Isn't one of > > > > > > Python's goals to minimize opportunities for bad programming? > > > > > > Nope. That's Java's goal. Python's goals are to maximize opportunities > > > > > for good programming, which is quite different. > > > > Oh, gosh, that is so clever. What a bunch of crap. > > > > > +1 QOTW > > > > Do you realize what an insult that is to everyone else who has posted > > > here in the past week? > > > Nothing glues a community together so well as a common enemy. Or even > > better: two enemies i.e. Perl and Java in Pythons case. On the other > > hand, some enemies have to be ignored or declared to be not an enemy > > ( Ruby ), although oneself is clearly an enemy for them. The same > > antisymmetry holds for Python and Java. Java is an enemy for Python > > but Python is not worth for Java to be an enemy as long as it can be > > ignored. C++ and Java are enemies for each other. Same holds for Java > > and C#.- Hide quoted text - > > > - Show quoted text - > > Help... being... sucked into... black hole... inside a... Klein... > bottle...- Hide quoted text - > > - Show quoted text - ... which is inside... the black hole... From Edwin.Madari at VerizonWireless.com Mon Aug 18 15:28:22 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Mon, 18 Aug 2008 15:28:22 -0400 Subject: Newbie problem inserting into MySQL In-Reply-To: <4A358F5ED2A5364A86711EDFEB9494BD294C5AAA@NYOBGCEXMB21.uswin.ad.vzwcorp.com> Message-ID: <20080818192833.ECCA91E4006@bag.python.org> > -----Original Message----- > From: Madari, Edwin > Sent: Monday, August 18, 2008 3:03 PM > To: 'len'; python-list at python.org > Subject: Re: Newbie problem inserting into MySQL > > > -----Original Message----- > > From: > python-list-bounces+edwin.madari=verizonwireless.com at python.org > > [mailto:python-list-bounces+edwin.madari=verizonwireless.com at p > > ython.org] > > On Behalf Of len > > Sent: Monday, August 18, 2008 11:55 AM > > To: python-list at python.org > > Subject: Newbie problem inserting into MySQL > > > > > > Hi All > > > > I have started a little pet project to learn python and MySQL. The > > project involves figuring out all the combinations for a 5 number > > lottery and storing the data in a MySQL file. > > > > The file looks like this; > > +----------+---------------------+------+-----+--------- > > +----------------+ > > | Field | Type | Null | Key | Default | > > Extra | > > +----------+---------------------+------+-----+--------- > > +----------------+ > > | lottryid | int(11) | NO | PRI | NULL | > > auto_increment | > > | lottryno | char(10) | YES | | NULL > > | | > > | no1 | tinyint(3) unsigned | NO | | NULL > > | | > > | no2 | tinyint(3) unsigned | NO | | NULL > > | | > > | no3 | tinyint(3) unsigned | NO | | NULL > > | | > > | no4 | tinyint(3) unsigned | NO | | NULL > > | | > > | no5 | tinyint(3) unsigned | NO | | NULL > > | | > > | nosum | tinyint(3) unsigned | NO | | NULL > > | | > > | nohits | int(10) unsigned | YES | | NULL > > | | > > +----------+---------------------+------+-----+--------- > > +----------------+ > > > > The code looks as follows; > > #!/usr/lib/env python > > > > import MySQLdb > > import datetime > > > > db = MySQLdb.Connection(host="localhost", user="lenyel", > > passwd="lsumnler", \ > > db="lottery") > > > > cursor = db.cursor() > > > > cursor.execute('delete from littlelottery') > > > > listofrec = [] > > > > tupcnt = 0 > > print "first tuple created" > > for a in xrange(1,36): > > for b in xrange(2,37): > > for c in xrange(3,38): > > for d in xrange(4,39): > > for e in xrange(5,40): > > tupcnt += 1 > > thekey = ('%02i%02i%02i%02i%02i' % (a,b,c,d,e)) > > mysum = a + b + c + d + e > > rectuple = tupcnt, thekey, a, b, c, d, > e, mysum, 0 > > listofrec.append(rectuple) > > if tupcnt % 10000 == 0: > > print "beginnign of mysql write" > > print datetime.datetime.now().time() > > cursor.executemany('''insert into > > littlelottery > > values (?,?,?,?,?,?,?,?,?)''', listofrec) > > db.close() > > print "end of mysql write" > > print datetime.datetime.now().time() > > os._exit() > > > > print "insert into mysql completed" > > > > i get the following error on insert; > > raise errorclass, errorvalue > > TypeError: not all arguments converted during string formatting > > Script terminated. > > > > Do I have to covert all of the fields in the tuple records to string > > or what? > > > > Len Sumnler > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > statement prepared first and executed many times with > exectemany - db API http://www.python.org/dev/peps/pep-0249/ > inline statemets can be exeucuted only. > > hope that helps > Edwin another thing - cumulative inserts will result, since listofrec is not emptied after each sql execution. regards Edwin The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From haraldarminmassa at gmail.com Fri Aug 29 08:51:32 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Fri, 29 Aug 2008 05:51:32 -0700 (PDT) Subject: translating "create Semaphore" to Linux References: Message-ID: <34ca0e34-69d1-466c-83ff-b2d99f54ae39@z66g2000hsc.googlegroups.com> Tim, > ... why use a Semaphore rather than a Mutex? as much as I understood the documentation at MSDN http://msdn.microsoft.com/en-us/library/ms686927(VS.85).aspx http://msdn.microsoft.com/en-us/library/ms686946(VS.85).aspx a mutex seems to be nothing else than a special case of a semaphore? That is, a semaphore can be created to allow MAX_SEM_COUNT concurrent runners, and MUTEX defaults to one and only one ... The other api-spells are identical, like wait_for_xxxx...; so propably I stumbled on the working Semaphore Code before, or in some ancient win32 wrapper createMutex was not documented or something in that aspect:) > Or why notsimply use the bound socket as its own mutex? I know > Windows won't allow you to rebind the same socket to the > same addr/port in two different processes (unless perhaps > you play some trickery with the socket options). My experience was that this is correct for certain values of "allow" and "trickery". Sometimes the binding seems to get allowed but does not work. Main reason is that the socket-bind happens somewhere in medusa or ; so to use it as a semaphore I would have to dig there. I am not totally sure what trickery on socket is played down there; and I prefer to stay as far away as possible from that area. Harald From bj_666 at gmx.net Mon Aug 11 03:08:34 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Aug 2008 07:08:34 GMT Subject: for x,y in word1, word2 ? References: <55d5ea68-f613-4754-8510-cc3934e36421@b1g2000hsg.googlegroups.com> Message-ID: <6ga6riFet68vU1@mid.uni-berlin.de> On Sun, 10 Aug 2008 23:14:50 -0700, ssecorp wrote: > I know zip but lets say I have a word "painter" and I want to compare it > to a customer's spelling, he might have written "paintor" and I want to > check how many letters are the same. > > Now I know how I could do this, it is not hard. I am just wondering if > these is any specific simple syntax for it. No special syntax for that, but you can combine the `sum()` function, a generator expression and `zip()`: In [40]: sum(int(a == b) for a, b in zip('painter', 'paintor')) Out[40]: 6 Or this way if you think it's more clear: In [41]: sum(1 for a, b in zip('painter', 'paintor') if a == b) Out[41]: 6 Ciao, Marc 'BlackJack' Rintsch From Afro.Systems at gmail.com Tue Aug 12 10:21:15 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Tue, 12 Aug 2008 07:21:15 -0700 (PDT) Subject: trying to use SOCK_RAW yields error " References: <3b701b38-9dd3-48f6-bdb0-c04fc9085008@x41g2000hsb.googlegroups.com> Message-ID: > When using SOCK_RAW, the family should be AF_PACKET, > not AF_INET. Note that you need root privileges to do so. I changed as instructed: server = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.getprotobyname('ip')) now I am getting: Traceback (most recent call last): File "tcpsrv.py", line 15, in server.bind((host,port)) File "", line 1, in bind socket.error: (19, 'No such device') From Edwin.Madari at VerizonWireless.com Thu Aug 14 11:39:31 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Thu, 14 Aug 2008 11:39:31 -0400 Subject: a question about mysqldb In-Reply-To: Message-ID: <20080814154550.190A21E401D@bag.python.org> replace the name of table before calling *.execute. s.dbptr.execute(str % (e[0])) good luck. Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of Evan Sent: Thursday, August 14, 2008 11:27 AM To: python-list at python.org Subject: a question about mysqldb a simple problem but I do not know why...:(, could anyone help me? MySQLdb nominally uses just the %s placeholder style, in my script, i got error if you want to use placeholder(%s) for table name: +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ >>> str="select tID,tNote from %s where tID=1" <-------- check here >>> >>> e=["tmp"] >>> s.dbptr.execute(str,e) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line 166, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''tmp') where tID=1' at line 1") >>> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ But sql worked but the I got no query result: ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ >>> str="select tID,tNote from tmp where %s = %s" <----------check here >>> e=["tID",int(1)] >>> s.dbptr.execute(str,e) 0L <------------------ check here >>> >>> s.dbptr.fetchall() () >>> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ And then, it worked if I do: ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ >>> str="select tID,tNote from %s where %s = %s" % ("tmp","tID",1) >>> >>> str 'select tID,tNote from tmp where tID = 1' >>> s.dbptr.execute(str) 1L >>> >>> s.dbptr.fetchall() ({'tID': 1L, 'tNote': 'kao'},) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ mysql> desc tmp -> ; +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+----------------+ | tID | int(11) | NO | PRI | NULL | auto_increment | | tDate | date | YES | | NULL | | | tSID | int(11) | NO | | NULL | | | tCom | varchar(15) | YES | | NULL | | | tNote | text | YES | | NULL | | +-------+-------------+------+-----+---------+----------------+ 5 rows in set (0.00 sec) +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ mysql> mysql> Thanks, -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From poojaangali at gmail.com Fri Aug 15 06:00:13 2008 From: poojaangali at gmail.com (pooja) Date: Fri, 15 Aug 2008 03:00:13 -0700 (PDT) Subject: EARN MONEY $1500-$5000 PER MONTH Message-ID: <82300e5a-70ad-43d9-b464-2fe5a7c038e6@i20g2000prf.googlegroups.com> EARN MONEY $1500-$5000 PER MONTH SIMPLE ONLINE SURVEY CREATE UR ACCOUNT AND EARN IMMEDIATLY ************************************************************************* http://www.AWSurveys.com/HomeMain.cfm?RefID=kingraja666 ************************************************************************* From george.sakkis at gmail.com Wed Aug 27 17:09:58 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 27 Aug 2008 14:09:58 -0700 (PDT) Subject: Identifying the start of good data in a list References: <94524253-b946-4ffa-ae2e-ae6a555d4e7c@a1g2000hsb.googlegroups.com> Message-ID: <9bf75f04-a4bb-42ec-a80c-66ae4d458fd5@e53g2000hsa.googlegroups.com> On Aug 27, 3:00 pm, Gerard flanagan wrote: > tkp... at hotmail.com wrote: > > I have a list that starts with zeros, has sporadic data, and then has > > good data. I define the point at which the data turns good to be the > > first index with a non-zero entry that is followed by at least 4 > > consecutive non-zero data items (i.e. a week's worth of non-zero > > data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, > > 9], I would define the point at which data turns good to be 4 (1 > > followed by 2, 3, 4, 5). > > > I have a simple algorithm to identify this changepoint, but it looks > > crude: is there a cleaner, more elegant way to do this? > > > flag = True > > i=-1 > > j=0 > > while flag and i < len(retHist)-1: > > i += 1 > > if retHist[i] == 0: > > j = 0 > > else: > > j += 1 > > if j == 5: > > flag = False > > > del retHist[:i-4] > > > Thanks in advance for your help > > > Thomas Philips > > data = [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > def itergood(indata): > indata = iter(indata) > buf = [] > while len(buf) < 4: > buf.append(indata.next()) > if buf[-1] == 0: > buf[:] = [] > for x in buf: > yield x > for x in indata: > yield x > > for d in itergood(data): > print d This seems the most efficient so far for arbitrary iterables. With a few micro-optimizations it becomes: from itertools import chain def itergood(indata, good_ones=4): indata = iter(indata); get_next = indata.next buf = []; append = buf.append while len(buf) < good_ones: next = get_next() if next: append(next) else: del buf[:] return chain(buf, indata) $ python -m timeit -s "x = 1000*[0, 0, 0, 1, 2, 3] + [1,2,3,4]; from itergood import itergood" "list(itergood(x))" 100 loops, best of 3: 3.09 msec per loop And with Psyco enabled: $ python -m timeit -s "x = 1000*[0, 0, 0, 1, 2, 3] + [1,2,3,4]; from itergood import itergood" "list(itergood(x))" 1000 loops, best of 3: 466 usec per loop George From digitig at gmail.com Fri Aug 1 08:53:32 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 1 Aug 2008 13:53:32 +0100 Subject: Python Written in C? In-Reply-To: <8d3752f20807202258w2a4167e4hd40b56b12c0c74fc@mail.gmail.com> References: <8d3752f20807202258w2a4167e4hd40b56b12c0c74fc@mail.gmail.com> Message-ID: 2008/7/21 Krishnakant Mane : > First off all c# is absolute rubbish waist of time. What a pity others are joining in this pointless language flame-war. Look, I recently had to write a script for manipulating some data; I struggled to organise it in Python and in C++, but when I tried C# everything fell naturally into place and I had it done in next to no time. Other times it has been Python or C++ that has been the most natural way to express what I'm trying to do. Just because /you/ don't like C# doesn't mean it's rubbish or a waste of time; personally I loathe Perl, but I respect the fact that a lot of programmers can get good results very quickly in it. I reckon that the programmer who only knows one language is like a carpenter trying to make a cabinet with just a chisel. Ok for making the joints (although a hammer would have been handy to hit it with), not /really/ as good as a plane for getting large areas smooth, and the blade keeps jumping out when you try to use it as a screwdriver... The one-language programmer isn't really in a position to choose the right tool for the job, because they only have one tool. Anybody who says that a language in real use is a waste of time is denying the reality of those who find it an effective tool. Similarly, anybody who says that a language -- any language -- is right for all jobs plainly doesn't understand that language design involves a lot of compromises, and that the compromises that are appropriate choices for one task are inappropriate for another. Python is a great tool. So is C#. You /can/ do the same job with either, but the smart move is to choose the one that is best adapted to the task in hand. -- Tim Rowe From cousinstanley at gmail.com Fri Aug 29 09:47:30 2008 From: cousinstanley at gmail.com (Cousin Stanley) Date: Fri, 29 Aug 2008 15:47:30 +0200 (CEST) Subject: iterating over two arrays in parallel? References: Message-ID: > I want to interate over two arrays in parallel, > something like this: > > a=[1,2,3] > b=[4,5,6] > > for i,j in a,b: > print i,j > > where i,j would be 1,4, 2,5, 3,6 etc. > > Is this possible? > > Many TIA! > Mark >>> >>> list_1 = range( 1 , 4 ) >>> list_2 = range( 4 , 7 ) >>> >>> list12 = zip( list_1 , list_2 ) >>> >>> for this in list12 : ... print ' ' , this ... (1, 4) (2, 5) (3, 6) >>> >>> for i , j in list12 : ... print ' ' , i , j ... 1 4 2 5 3 6 -- Stanley C. Kitching Human Being Phoenix, Arizona From anartz at anartz.cjb.net Mon Aug 11 09:15:45 2008 From: anartz at anartz.cjb.net (anartz at anartz.cjb.net) Date: Mon, 11 Aug 2008 07:15:45 -0600 Subject: =?UTF-8?B?ZHluYW1pY2FsbHkgY3JlYXRpbmcgaHRtbCBjb2RlIHdpdGggcHl0aG9uLi4u?= Message-ID: <200808111315.m7BDFjqs045647@cjb.net> Hi, how can I combine some dynamically generated html code (using python) with the output of a urllib.openurl() call? I have tried to use the StringIO() class with .write functions, but it did not work. Below is the code that does not work. [CODE] f=StringIO.StringIO() f.write('data analysis') f.write(urllib.urlopen("http://localhost/path2Libs/myLibs.py", urllib.urlencode(TheData))) f.write("") print "Content-type: text/html\n" print f.read() f.close() [/CODE] What is wrong with this approach/code? Is there an easier way of doing it? Thanks. From martin at marcher.name Tue Aug 26 03:43:40 2008 From: martin at marcher.name (Martin Marcher) Date: Tue, 26 Aug 2008 09:43:40 +0200 Subject: Are dictionaries the same as hashtables? In-Reply-To: References: Message-ID: <20080826074338.GB10162@marcher.name> On 2008-08-26 00:32:20, cnb wrote: > Are dictionaries the same as hashtables? Yes, but there is nothing in there that does sane collision handling like making a list instead of simply overwriting. PS: your sig was *a bit* longer than you question. please don't do that... -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 844 bytes Desc: Digital signature URL: From deets at nospam.web.de Sat Aug 2 13:05:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 02 Aug 2008 19:05:53 +0200 Subject: Continually check object status In-Reply-To: <48dca0ce-3389-4f0d-a137-a1aaa9dcef67@25g2000hsx.googlegroups.com> References: <48dca0ce-3389-4f0d-a137-a1aaa9dcef67@25g2000hsx.googlegroups.com> Message-ID: <6fjifiFb0jraU1@mid.uni-berlin.de> futileissue at gmail.com schrieb: > Beginner, so please bare with me. I'm not sure what to call what it > is I'm looking for. > > If I have an object class, let's call it "Creature": > > class Creature: > def __init__(self, status): > self.status = "happy" > > def change_status(self, new_status): > self.status = new_status > > def print_status(self): > print self.status > > I would like to be able to print out the Creature's status every 20 > seconds. Let's say I use a script like this: > > import time > while True: > time.sleep(20) > Creature.print_status() > > But, while cycling through printing the status, I would like to be > able to update Creature.status to something new. > > I might be approaching this from the wrong direction entirely. Thanks > for your input. The "simple", yet possibly dangerous answer is: you need multi-threading. Multi-threading is a technique that allows several (quasi)-parallel paths of execution whilst sharing memory and objects inside that memory. The module in python to achieve this is called "threading". However, concurrent programming is a very advanced topic, ridded with pitfalls for even experienced developers. There are other ways to solve the problem, commonly known as event-loops and timers. These are usually part of frameworks for e.g GUI-creation an such, but you can also roll your own if you like. So, the better answer might be a question: what do you ultimately want to achieve? Given the name of your class, Creature, I assume you are writing on some game or such. Depending on how you plan to do that, you might have a framwork providing you with the needed tools/library calls or whatever. Diez From fredrik at pythonware.com Sat Aug 30 01:57:07 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 30 Aug 2008 07:57:07 +0200 Subject: Which is faster? In-Reply-To: References: Message-ID: cnb wrote: > For a big nbr of it might matter? > Is av_grade O(n*2) and the first O(n) when it comes to adding or is > "sum x for x in y" just traversing the list ones, accumulating the > values, it doesnt first build the list and then travese it for sum? sum() doesn't build a list, but even if it would do that, it'd still be O(n) -- looping over an array twice doesn't change the time complexity. to find out which one's actually faster, benchmark them. From aaa at bbb.it Mon Aug 4 05:59:13 2008 From: aaa at bbb.it (Fred Mangusta) Date: Mon, 04 Aug 2008 10:59:13 +0100 Subject: Nlp, Python and period Message-ID: Hi, are you aware of any nlp packages or algorithms in Python to spot whether a '.' represents an end of sentence or rather something else (eg Mr., foo at home.co.uk, etc)? Thanks F. From stephane at is-webdesign.com Mon Aug 25 08:56:04 2008 From: stephane at is-webdesign.com (=?iso-8859-1?q?KLEIN_St=E9phane?=) Date: Mon, 25 Aug 2008 12:56:04 +0000 (UTC) Subject: I can't fetch dom node in svg file with getElementById method (module minidom and libxml2dom) References: Message-ID: Le Mon, 25 Aug 2008 04:30:00 -0700, Paul Boddie a ?crit?: >> Well, my final purpose isn't to fetch root dom node but to fetch many >> other sub node. > > You could always try using an XPath expression: > > node = (dom2.xpath("//*[@id='svg2383']") or [None])[0] > > Similar things could be done in PyXML and other libraries, I'm sure, but > minidom lacks XPath support, if I remember correctly. Thanks ! It work. Regards, Stephane From deets at nospam.web.de Thu Aug 21 06:09:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 21 Aug 2008 12:09:52 +0200 Subject: evaluating code lines above breakpoints ? References: Message-ID: <6h4t94Fj84dgU1@mid.uni-berlin.de> Stef Mientki wrote: > hello, > > I'm trying to create a high level debugger, based on rpd2. > > So when the debugger enters a breakpoint, > I want to display the values of all variables in the, let's say, > 5 lines above the breakpoint (if possible). > Any hints on how I get a list of all vars in those lines ? > My rough idea is to scan the lines, skip keywords, test type of each > term ( by eval), if the term is var eval the value of it. > Are there better ways ? I don't know about better ways, but I for *sure* know that this is a really bad idea. Simply because a debugger that executes arbitrary evals can cause side-effects that make it useless. Why do you want this anyway? Why don't you simply show all the variables in the local frame? I'd say thats enough. > Another idea, when hoovering over a variable during a breakpoint, a > hint appears with the type and value of that var. The simple thing to do is to extract tokens, and then if these as names are matched in the local frames, you can display the content. Things get more difficult in cases like foo[index] as this can cause a side-effect to occur. I wouldn't automatically evaluate the expression, for reasons given above. Diez From timothy.grant at gmail.com Thu Aug 7 12:40:10 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Thu, 7 Aug 2008 09:40:10 -0700 Subject: Access individual fields in csv using python In-Reply-To: References: Message-ID: On Thu, Aug 7, 2008 at 9:23 AM, Krishna wrote: > How do I access individual fields in csv using python? Please let me > know ASAP as its real urgent for me. > > Thanks for your help > > Krishna > -- > http://mail.python.org/mailman/listinfo/python-list > I'd likely use the csv module. http://docs.python.org/lib/module-csv.html -- Stand Fast, tjg. [Timothy Grant] From circularfunc at yahoo.se Tue Aug 26 03:52:44 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 26 Aug 2008 00:52:44 -0700 (PDT) Subject: Are dictionaries the same as hashtables? References: Message-ID: <0dbb5dfe-8ec4-4a57-ac3f-08c021a39337@k30g2000hse.googlegroups.com> On Aug 26, 9:43?am, Martin Marcher wrote: > On 2008-08-26 00:32:20, cnb wrote: > > > Are dictionaries the same as hashtables? > > Yes, but there is nothing in there that does sane collision handling > like making a list instead of simply overwriting. > > PS: your sig was *a bit* longer than you question. please don't do > that... > > ?signature.asc > < 1KViewDownload my what? From gneuner2 at comcast.net Fri Aug 22 11:11:09 2008 From: gneuner2 at comcast.net (George Neuner) Date: Fri, 22 Aug 2008 11:11:09 -0400 Subject: The Importance of Terminology's Quality References: <48a8df27$0$7362$607ed4bc@cv.net> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: On Thu, 21 Aug 2008 02:30:27 GMT, sln at netherlands.com wrote: >On Wed, 20 Aug 2008 21:18:22 -0500, rpw3 at rpw3.org (Rob Warnock) wrote: > >>Martin Gregorie wrote: >>+--------------- >>| I was fascinated, though by the designs of early assemblers: I first >>| learnt Elliott assembler, which required the op codes to be typed on >>| octal but used symbolic labels and variable names. Meanwhile a colleague >>| had started on a KDF6 which was the opposite - op codes were mnemonics >>| but all addresses were absolute and entered in octal. I always wondered >>| about the rationale of the KDF6 assembler writers in tackling only the >>| easy part of the job. >>+--------------- >> >>In the LGP-30, they used hex addresses, sort of[1], but the opcodes >>(all 16 of them) had single-letter mnemonics chosen so that the >>low 4 bits of the character codes *were* the correct nibble for >>the opcode! ;-} >> >>[Or you could type in the actual hex digits, since the low 4 bits >>of *their* character codes were also their corresponding binary >>nibble values... "but that would have been wrong".] >> >> >>-Rob >> >>[1] The LGP-30 character code was defined before the industry had >> yet standardized on a common "hex" character set, so instead of >> "0123456789abcdef" they used "0123456789fgjkqw". [The "fgjkqw" >> were some random characters on the Flexowriter keyboard whose low >> 4 bits just happened to be what we now call 0xa-0xf]. Even worse, >> the sector addresses of instructions were *not* right-justified >> in the machine word (off by one bit), plus because of the shift- >> register nature of the accumulator you lost the low bit of each >> machine word when you typed in instructions (or read them from >> tape), so the address values you used in coding went up by *4*! >> That is, machine locations were counted [*and* coded, in both >> absolute machine code & assembler] as "0", "4", "8", "j", "10", >> "14", "18", "1j" (pronounced "J-teen"!!), etc. >> >>----- >>Rob Warnock >>627 26th Avenue >>San Mateo, CA 94403 (650)572-2607 > > >Whats os interresting about all this hullabaloo is that nobody has >coded machine code here, and know's squat about it. A friend of mine had an early 8080 micros that was programmed through the front panel using knife switches ... toggle in the binary address, latch it, toggle in the binary data, latch it, repeat ad nauseam. It had no storage device initially ... to use it you had to input your program by hand every time you turned it on. I did a little bit of programming on it, but I tired of it quickly. As did my friend - once he got the tape storage working (a new prom) and got hold of a shareware assembler, we hardly ever touched the switch panel again. Then came CP/M and all the initial pain was forgotten (replaced by CP/M pain 8-). >I'm not talking assembly language. Don't you know that there are routines >that program machine code? Yes, burned in, bitwise encodings that enable >machine instructions? Nothing below that. > >There is nobody here, who ever visited/replied with any thought relavence that can >be brought foward to any degree, meaning anything, nobody.... What are you looking for? An emulator you can play with? Machine coding is not relevant anymore - it's completely infeasible to input all but the smallest program. My friend had a BASIC interpreter for his 8080 - about 2KB which took hours to input by hand and heaven help you if you screwed up or the computer crashed. >sln George From mal at egenix.com Fri Aug 1 15:04:28 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 01 Aug 2008 21:04:28 +0200 Subject: DB-API corner case (psycopg2) In-Reply-To: <6fh3gfFbi581U1@mid.individual.net> References: <6fgi95Fbeot8U1@mid.individual.net> <6fh3gfFbi581U1@mid.individual.net> Message-ID: <48935E3C.3040304@egenix.com> On 2008-08-01 20:38, Thomas Guettler wrote: > I forgot to mention where I stumbled about this. > > Django has a wrapper: > http://code.djangoproject.com/browser/django/trunk/django/db/backends/util.py > > def execute(self, sql, params=()): > start = time() > try: > return self.cursor.execute(sql, params) > finally: > > Most people don't have a percent sign in the variable sql. > > I guess > cursor.execute(sql, None) > is not portable for all database backends. > > I guess this should be the best solution: > if params: > return self.cursor.execute(sql, params) > else: > return self.cursor.execute(sql) > > What do you think? Not good enough... you should use this: def execute(self, sql, params=None): start = time() try: if params is None: return self.cursor.execute(sql) else: return self.cursor.execute(sql, params) finally: ... > Thomas > > Thomas Guettler schrieb: >> Hi, >> >> I discovered this: >> >> import psycopg2 >> connection=psycopg2.connect("dbname='...' user='...'") >> cursor=connection.cursor() >> cursor.execute('''SELECT '%' ''') # Does not fail >> cursor.execute('''SELECT '%' ''', ()) # Does fail >> >> Traceback (most recent call last): >> File "/localhome/modw/tmp/t.py", line 5, in >> cursor.execute('''SELECT '%' ''', ()) # Does fail >> IndexError: tuple index out of range >> >> Is this a bug in psycopg2? >> >> How do other PEP 249 implementation behave? >> >> Regards, >> Thomas >> > -- > http://mail.python.org/mailman/listinfo/python-list -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Aug 01 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 26 06:29:41 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 26 Aug 2008 12:29:41 +0200 Subject: Is my thinking Pythonic? In-Reply-To: References: <638bf217-3eaf-43af-8604-4145aa156afe@m73g2000hsh.googlegroups.com> <39fcb558-2869-438b-9309-e55ccfed7ec6@i24g2000prf.googlegroups.com> <48add182$0$12232$426a74cc@news.free.fr> <48ae84de$0$13858$426a34cc@news.free.fr> Message-ID: <48b3dae6$0$17486$426a74cc@news.free.fr> Fredrik Lundh a ?crit : > Bruno Desthuilliers wrote: > >> Given the lack of proper support for the descriptor protocol in >> old-style classes and a couple other diverging behaviors, I wouldn't >> say that advising newcomers to use new-style classes is so pointless. > > Yeah, but if you don't need descriptors, new-style classes don't buy you > anything Except being python-3000 ready wrt/ diverging behavious - like overriding __magic__ methods on a per-instance basis. Ok, this is certainly not a very common case, but still we've seen questions about this on this ng... > (except a slight slowdown in certain situations). > Dogmatic "dogmatic" ??? > use > of new-style classes (or any other "new" feature) isn't "pythonic". You're right to quote the word "new" here - how many years since Python grew a new object model explicitely intended to replace the original one ? From brendandetracey at yahoo.com Mon Aug 25 08:42:08 2008 From: brendandetracey at yahoo.com (Brendan) Date: Mon, 25 Aug 2008 05:42:08 -0700 (PDT) Subject: urllib2 HTTPBasicAuthHandler and resumingbroken downloads References: <63d6d10e-c023-4ec6-9f11-0687d7ae8254@k37g2000hsf.googlegroups.com> Message-ID: <68ce446c-f7c0-45fb-a723-69db37dc9dea@d45g2000hsc.googlegroups.com> On Aug 22, 1:59?pm, "Gabriel Genellina" wrote: > En Fri, 22 Aug 2008 08:55:57 -0300, Brendan ? > escribi : > > > > > > > On Aug 21, 3:57?pm, "Gabriel Genellina" > > wrote: > >> En Thu, 21 Aug 2008 15:37:41 -0300, Brendan ? > >> ? > >> escribi : > > >> > Is there any way to resume an https file download using urllib2 and an > >> > HTTPBasicAuthHandler? > > >> You should provide the Range header (and probably If-Range too) in the ? > >> request.http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 > > > Ug. Why does everything in Python boil down to reading rfcs? It really > > slows us non computer science types down. I'll probably spend a day on > > this instead of an hour. I did search the web but had no luck finding > > an example, so I posted here as a last resort. > > The easy way is to use wget... > If you want a Python example, go to the Python cookbook:http://code.activestate.com/recipes/langs/python/ > enter "resume download" in the search box, and the very first recipe shows ? > how to use the Range header. > > -- > Gabriel Genellina- Hide quoted text - > > - Show quoted text - Thanks for the link. Much appreciated. From tino at wildenhain.de Sat Aug 30 15:57:12 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sat, 30 Aug 2008 21:57:12 +0200 Subject: Writing to ms excel In-Reply-To: References: Message-ID: <48B9A618.8090106@wildenhain.de> Marin Brkic wrote: > Hello all, > > please, let me apologize in advance. English is not my first language > (not even my second one), so excuse any errors with which I'm about to > embarass myself in front of the general public. Second, I'm relatively > new to python, so sorry if this seems like a stupid question. > > I'm trying to find a way to write data to excel cells (or to be more > specific to an .xls file), let's say for the sake of argument, data > readen from a file (although it will be calculated in the process). > I've been searching, but couldn't find any examples which allows that. > > Do anyone knows of any ? All help is appreciated on this matter. > Tutorials? Anything ... Its quite easy, a little googling brings: http://sourceforge.net/projects/pyexcelerator which comes with examples and all. Works on any platform (python only code). I'm using it to generate excel reports for all the damnd ms office adicts in the company... Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From deets at nospam.web.de Thu Aug 21 13:32:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 21 Aug 2008 19:32:58 +0200 Subject: Is my thinking Pythonic? References: <638bf217-3eaf-43af-8604-4145aa156afe@m73g2000hsh.googlegroups.com> <39fcb558-2869-438b-9309-e55ccfed7ec6@i24g2000prf.googlegroups.com> Message-ID: <6h5n7tFj6mk1U1@mid.uni-berlin.de> Craig Allen wrote: > generally, I name the members in the Class definition and set them to > None there... > > class Car: > speed = None > brand = None > > def __init__(): > self.speed = defaultspeed #alternately, and more commonly, get > this speed as a initializer argument > self.brand = defaultbrand > > > That solves the issue of being able to "see" all the members of an > object by reading code... however, this all goes out the window when > composing an instance dynamically (i.e. metaclass type stuff). While I use this idiom myself, one must be cautious not to create unwanted side-effects if anything mutable comes into play: class Foo: bar = [] def baz(self): self.bar.append(2) will *not* make bar instance-variable, but keep it as class-variable. From news1234 at free.fr Mon Aug 18 17:54:21 2008 From: news1234 at free.fr (nntpman68) Date: Mon, 18 Aug 2008 23:54:21 +0200 Subject: searching through a string and pulling characters In-Reply-To: References: Message-ID: <48a9ef8d$0$11574$426a34cc@news.free.fr> Hi, Is it thousands of lines or millions of lines? If it's just a few thousands and you're not working on an embedded device with little memory you could use the brute force approach Just read the whole file in one string vaiable split everything into an array separated by '()' Now you can directly access each element by number (or by number + 1 if you want, that the first index is 0 Example: ( assuming your text file is bla.txt ) import os import sys in_file = open('bla.txt') whole_text = in_file.read() sections = whole_text.split('()') # now print all entries n=0 for section in sections: print '%3d' % n,'---------------' print section n += 1 #or directly selecting one entry n=3 print "=" * 60 print 'Entry %d\n' % n,sections[3] print "=" * 60 bye N Alexnb wrote: > This is similar to my last post, but a little different. Here is what I would > like to do. > > Lets say I have a text file. The contents look like this, only there is A > LOT of the same thing. > > () A registry mark given by underwriters (as at Lloyd's) to ships in > first-class condition. Inferior grades are indicated by A 2 and A 3. > () The first three letters of the alphabet, used for the whole alphabet. > () In church or chapel style; -- said of compositions sung in the old church > style, without instrumental accompaniment; as, a mass a capella, i. e., a > mass purely vocal. > () Astride; with a part on each side; -- used specif. in designating the > position of an army with the wings separated by some line of demarcation, as > a river or road. > > Now, I am talking 1000's of these. I need to do something like this. I will > have a number, and what I want to do is go through this text file, just like > the example. The trick is this, those "()'s" are what I need to match, so if > the number is 245 I need to find the 245th () and then get the all the text > from after it until the next (). If you have an idea about the best way to > do this I would love your help. If you made it all the way through thanks! > ;) From deets at nospam.web.de Tue Aug 19 12:07:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 19 Aug 2008 18:07:00 +0200 Subject: who to call a list of method inside the class itself References: Message-ID: <6h09euFi1j20U1@mid.uni-berlin.de> Edwin.Madari at VerizonWireless.com wrote: > fredrik at pythonware.com wrote: >> >> Edwin.Madari at VerizonWireless.com wrote: >> >> > 1. return string names of required methods in getAllMethod >> > return ['method1', 'method2', 'method3'] >> > 2. use gettattr on self and then exetute methods in applyAll >> > def applyAll(self): >> > for method_name in self.getAllMethod(): >> > method = gettattr(self,method_name) >> > method() #execute method now >> >> why? > > ensure instance's method invocation with all state information to that > point, rather than relying on implemenation. Erm, that makes no sense. The OP's code was perfectly fine - for some reason he seemed to think it wasn't. Your additional indirection doesn't add anything beyond clutter, as name = "foo" getattr(instance, name) == instance.foo holds. Diez From darcy at druid.net Sat Aug 2 09:27:12 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 2 Aug 2008 09:27:12 -0400 Subject: Strong/weak typing In-Reply-To: References: <6727fa22-aee9-4a9b-b9c0-08534aab6b34@m45g2000hsb.googlegroups.com> Message-ID: <20080802092712.d252256e.darcy@druid.net> On Fri, 01 Aug 2008 22:47:04 -0400 Mel wrote: > middle_name = raw_input ('Name?') > middle_name = middle_name.split() > middle_name = middle_name[1] > > It works, but I don't like it enough to actually use it. Especially since this works better anyway: middle_name = raw_input ('Name?').split()[1] -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From wuwei23 at gmail.com Thu Aug 7 03:44:14 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 7 Aug 2008 00:44:14 -0700 (PDT) Subject: benchmark References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> <489a8cf8$0$11738$9b4e6d93@newsspool1.arcor-online.net> <00aa8eeb$0$20317$c3e8da3@news.astraweb.com> Message-ID: <7d6b3d0d-deb7-4f4b-99a8-1a5b52c1cf1f@h17g2000prg.googlegroups.com> Steven D'Aprano wrote: > In other words, about 20% of the time he measures is the time taken to > print junk to the screen. Which makes his claim that "all the console outputs have been removed so that the benchmarking activity is not interfered with by the IO overheads" somewhat confusing...he didn't notice the output? Wrote it off as a weird Python side-effect? I find his reluctance to entertain more idiomatic implementations particularly telling. It's seems he's less interested in actual performance comparisons and more into showing that writing static lang style code in dynamic langs is bad, which isn't really anything new to anyone anywhere, I would've thought. All up, this reminds me of last years benchmarking fiasco that demonstrated Storm's ORM handling being -incredibly-faster than SQLAlchemy's SQL expression handling, something that just didn't seem to be born out by user experience. Eventually, Mike Beyer reverse engineered the benchmarks to discover that, surprise surprise, the tests -weren't equal-; in one test SQLA was issuing a commit per insert, while Storm was performing -no commits whatsoever-. Benchmarks, IMO, are like statistics. You can tweak them to prove pretty much any position you already take. From cokofreedom at gmail.com Fri Aug 22 05:24:20 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Fri, 22 Aug 2008 02:24:20 -0700 (PDT) Subject: def X(l=[]): weirdness. Python bug ? References: <8824d$48ae83b2$18847a51$1995@news.chello.nl> Message-ID: On Aug 22, 11:13?am, Bart van Deenen wrote: > Hi all. > > I've stumbled onto a python behavior that I don't understand at all. > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > > # function > def X(l=[]): > ? ?l.append(1) > ? ?print l > > # first call of X > X() > [1] > > #second call of X > X() > [1, 1] > > Where does the list parameter 'l' live between the two successive calls of X(). > Why is it not recreated with an empty list? > Is this correct behavior or is it a Python bug? > Does anyone have any pointers to the language documentation where this behavior is described? > > Thanks all > > Bart van Deenen http://docs.python.org/ref/function.html "Default parameter values are evaluated when the function definition is executed." Depending on your use the common way to handle this is to do def x(lst = None): if lst is None: pass # lst has not been set to anything else: pass # lst has been set to something From lists at svrinformatica.it Thu Aug 14 03:50:28 2008 From: lists at svrinformatica.it (Mailing List SVR) Date: Thu, 14 Aug 2008 09:50:28 +0200 Subject: Distinguish file and folder on ftp site Message-ID: <1218700228.7851.1.camel@localhost.localdomain> Hi, is there a simple way to do this? ftplib seems unable to distinguish between files and dir, a mimetype check would be good, regards Nicola From half.italian at gmail.com Mon Aug 11 19:03:20 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Mon, 11 Aug 2008 16:03:20 -0700 (PDT) Subject: SSH utility References: Message-ID: On Aug 11, 5:17?am, Edwin.Mad... at VerizonWireless.com wrote: > for similar tasks, I use pexpecthttp://pypi.python.org/pypi/pexpect. > > spawning bash process and simulate an interactive session. Here sending ls command, retrieving results and exiting. In the spawned process ssh or any other command, is just another command. > > ------------actual session-------------------------- > $ python > Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) > [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin > Type "help", "copyright", "credits" or "license" for more information.>>> import pexpect > >>> c = pexpect.spawn('/bin/bash') > >>> c.expect([pexpect.TIMEOUT, pexpect.EOF, '\$ ']) > 2 > >>> c.before, c.after > > ('\x1b[?1034hmadared at NJWARHQD0IT696A:~\r\n', '$ ')>>> c.sendline('ls') > 3 > >>> c.expect([pexpect.TIMEOUT, pexpect.EOF, '\$ ']) > 2 > >>> c.before, c.after > > ('ls\r\x.txt ?xx.txt ?xy.txt ?y.txt\r\nmadared at NJWARHQD0IT696A:~\r\n', '$ ')>>> c.sendline('exit') > 5 > >>> c.expect([pexpect.TIMEOUT, pexpect.EOF, '\$ ']) > 1 > >>> c.before, c.after > > ('exit\r\nexit\r\n', )>>> exit() > > madared at NJWARHQD0IT696A:~ > $ > --------------------------------------------------------------- > > hope that helps. > > regards. > Edwin > > -----Original Message----- > From: python-list-bounces+edwin.madari=verizonwireless.... at python.org > > [mailto:python-list-bounces+edwin.madari=verizonwireless.... at python.org] > On Behalf Of James Brady > Sent: Monday, August 11, 2008 12:26 AM > To: python-l... at python.org > Subject: SSH utility > > Hi all, > I'm looking for a python library that lets me execute shell commands > on remote machines. > > I've tried a few SSH utilities so far: paramiko, PySSH and pssh; > unfortunately all been unreliable, and repeated questions on their > respective mailing lists haven't been answered... > > It seems like the sort of commodity task that there should be a pretty > robust library for. Are there any suggestions for alternative > libraries or approaches? > > Thanks! > James > --http://mail.python.org/mailman/listinfo/python-list > > The information contained in this message and any attachment may be > proprietary, confidential, and privileged or subject to the work > product doctrine and thus protected from disclosure. ?If the reader > of this message is not the intended recipient, or an employee or > agent responsible for delivering this message to the intended > recipient, you are hereby notified that any dissemination, > distribution or copying of this communication is strictly prohibited. > If you have received this communication in error, please notify me > immediately by replying to this message and deleting it and all > copies and backups thereof. ?Thank you. I second pexpect and the nice little module that comes with it ssh_session.py. Been using it for ages now! ~Sean From raashid_hbk at yahoo.com Wed Aug 20 13:39:45 2008 From: raashid_hbk at yahoo.com (raashid bhatt) Date: Wed, 20 Aug 2008 10:39:45 -0700 (PDT) Subject: urllib fails to connect References: Message-ID: <5e7ed5d0-e2d3-4364-8567-456e3988d226@z11g2000prl.googlegroups.com> On Aug 20, 10:06?am, "jlist" wrote: > I'm running ActiveState Python 2.5 on Windows XP. It used > to work fine. Today however I get (10061, 'Connection refused') > for any site I try with urllib.urlopen(). May be the host is Listening on the port you are connecting to or the host isnt availible if u on a LAN try to ping the host first and Disable the Firewall on Hosts Computer From kay.schluehr at gmx.net Sat Aug 9 04:38:04 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 9 Aug 2008 01:38:04 -0700 (PDT) Subject: ANN: P4D 1.2 Message-ID: P4D = E4X style embedded DSL for Python but without E and X. The main feature of P4D 1.2 are *Bytelets*. While the primary purpose of P4D 1.1 was the support textual data which can be considered as isomorphic to XML the new release is focussed on binary data. Bytelets are P4D objects that are assembled from hexcode which is reified as a Hex object. Bytelets can also be serialized as Hex objects which makes them apt for low level communication. Bytelets can be used to parse hexcode into other Bytelets of the same structure and Bytelets can be cloned like object prototypes which makes it easy to produce sequences of variations of one Bytelet ( usually you do not derive from a Bytelet but modify a prototype ). For more information see: http://pypi.python.org/pypi/P4D http://www.fiber-space.de http://www.fiber-space.de/EasyExtend/doc/p4d/bytelets.html From fabiofz at gmail.com Fri Aug 22 22:52:03 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Fri, 22 Aug 2008 23:52:03 -0300 Subject: Pydev 1.3.20 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.20 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Code Analysis: Show error if using token not defined in __all__ in wild import. * Search: Working with eclipse 3.4. Release Highlights in Pydev: ---------------------------------------------- * Pydev Package Explorer: Editor-link does not remove focus from current editor if it's already a match (bug when compare editor was opened) * Pydev debugger: Showing set and frozenset contents * Pydev debugger: Watch working in eclipse 3.4 * Pydev debugger: Breakpoint properties accept new lines and tabs * Pydev debugger: Workaround for python bug when filenames don't have absolute paths correctly generated * Pydev code-completion: Wild import will only show tokens defined in __all__ (if it's available) * Interactive console: Fixed problem when more attempts to connect were needed * Interactive console: Fixed console integration problem with other plugins because of interfaces not properly implemented * Incremental find: Backspace works correctly * Launch icons: Transparent background (thanks to Radim Kubacki) * Code Formatter: Exponentials handled correctly * Launching: Unit-test and code-coverage may launch multiple folders/files at once * Code coverage: Number format exception no longer given when trying to show lines not executed in the editor and all lines are executed * Auto-indent: Fixed issue when using tabs which could result in spaces being added What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From notvalid2 at sbcglobal.net Sat Aug 23 13:53:24 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Sat, 23 Aug 2008 10:53:24 -0700 Subject: Total No. of "Records" in a File? In-Reply-To: References: <1JXrk.20070$89.12375@nlpi069.nbdc.sbc.com> Message-ID: Nick Dumas wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Err...you want to know what is in a file before you open it? This could > be done if you keep some external database documenting changes made to > the file. But unless I misunderstand what you're saying, then it's not > possible to know the contents of a file without opening and reading that > file. > > W. eWatson wrote: >> I have an ordinary text file with a CR at the end of a line, and two >> numbers in each line. Is there some way to determine the number of lines >> (records) in the file before I begin reading it? >> > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (MingW32) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iEYEARECAAYFAkiwSZ4ACgkQLMI5fndAv9hXugCeJs5XBkLLne6ljqQggB/MoAVs > SNIAoJxsU04cwcZMrH9QjElAbMD34RdK > =RlmP > -----END PGP SIGNATURE----- Maybe. I could see it if the file were truly in a record format. The # of records might be kept by the OS. It's conceivable that Python or the OS might see a file with a CR as "recordized". All unlikely though. Just checkin'. How about in a slightly different case. Suppose I want to know the number of files in a folder? The OS and maybe some Python method might know that. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From Edwin.Madari at VerizonWireless.com Thu Aug 7 11:53:53 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Thu, 7 Aug 2008 11:53:53 -0400 Subject: Testing for the first few letters of a string In-Reply-To: Message-ID: <20080807155404.C68641E400D@bag.python.org> use re module import re template = '^My name is alex' astring = 'My name is alex, and I like pie' if re.match(template, astring): print 'Found it' else: print '%s does not begin with %s' % (astring, template) good luck. Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of Alexnb Sent: Thursday, August 07, 2008 11:40 AM To: python-list at python.org Subject: Testing for the first few letters of a string Okay, I have a fix for this problem, but it is messy and I think there might be a better way. Heres an example: Lets say I have a string: "My name is alex" and I have another string "My name is alex, and I like pie". I want to test to see if just the "My name is alex" part is there. I don't care about the pie part. My first instinct was to just create a for loop and test for the string like this: n = 0 for x in string1: if string1[n] == string2[n] n = n +0 else: break and then later testing to see what n was = to and figuring out if it got through the whole loop. I feel like there should be an easier way to do this, and probably is. So Does anyone have a suggestion? -- View this message in context: http://www.nabble.com/Testing-for-the-first-few-letters-of-a-string-tp18873375p18873375.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From notvalid2 at sbcglobal.net Sat Aug 23 19:28:42 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Sat, 23 Aug 2008 16:28:42 -0700 Subject: Turning py into an Executable Program for Win? Message-ID: How do I get my py code into some executable form so that Win users who don't have python can execute it? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From fiacre.patrick at gmail.com Thu Aug 28 12:01:30 2008 From: fiacre.patrick at gmail.com (Andrew Lee) Date: Thu, 28 Aug 2008 12:01:30 -0400 Subject: def X(l=[]): weirdness. Python bug ? In-Reply-To: <8824d$48ae83b2$18847a51$1995@news.chello.nl> References: <8824d$48ae83b2$18847a51$1995@news.chello.nl> Message-ID: <48b6cb62$0$20917$607ed4bc@cv.net> Bart van Deenen wrote: > Hi all. > > I've stumbled onto a python behavior that I don't understand at all. > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > > # function > def X(l=[]): > l.append(1) > print l > > # first call of X > X() > [1] > > #second call of X > X() > [1, 1] > > Where does the list parameter 'l' live between the two successive calls of X(). > Why is it not recreated with an empty list? > Is this correct behavior or is it a Python bug? > Does anyone have any pointers to the language documentation where this behavior is described? > > Thanks all > > Bart van Deenen > I happen to be reading about decorators at the moment: from copy import deepcopy def nodefault(myfunc): myfunc_defaults = myfunc.func_defaults def fresh(*args, **kwargs): myfunc.func_defaults = deepcopy(myfunc_defaults) return myfunc(*args, **kwargs) return fresh @nodefault def X(l=[]): l.append(1) print l >>> for i in range(1,6): ... X() ... [1] [1] [1] [1] [1] Which is just a very fancy way of doing: def X(l=[]): if l is None: l = [] l.append(1) print l * sound of two pennies * From Sebastian.Pawlus at gmail.com Tue Aug 26 06:40:28 2008 From: Sebastian.Pawlus at gmail.com (x_O) Date: Tue, 26 Aug 2008 03:40:28 -0700 (PDT) Subject: RPCXML hide implementation. Message-ID: <1309dc37-6589-428c-a7fa-3e9e3251b872@2g2000hsn.googlegroups.com> Hi I'm working recently with XMLRPC for python and It never was so easy. But I've meet a obstacle. Because python is not giving us any reasonable encapsulation mechanism, I have problems with hiding some part of the implementation. When class has 2 methods and I want to make rpc private only ONE of them. I can always use __name. But what in case when I really need to use those two methods inside other class as a public, but not by RPC Simple code: class RpcClass: def one(self): #visible by RPC, available as public for other class return "one" def two(self): #INVISIBLE by RPC, available as public for other class return "two" Server.register_instance(RpcClass()) Thanks From steve at REMOVE-THIS-cybersource.com.au Thu Aug 21 06:22:46 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Aug 2008 10:22:46 GMT Subject: exception handling in complex Python programs References: Message-ID: <00bd3cc9$0$20315$c3e8da3@news.astraweb.com> On Thu, 21 Aug 2008 00:34:21 -0700, eliben wrote: > On Aug 19, 7:19?pm, eliben wrote: >> Python provides a quite good and feature-complete exception handling > > > Thanks for the interesting discussion. Armed by the new information and > few online sources, I blogged a summary for myself on the topic of > robust exception handling in Python: > > http://eli.thegreenplace.net/2008/08/21/robust-exception-handling/ Just a few random points. You say: "Exceptions are better than returning error status codes. Some languages (like Python) leave you with no choice as the whole language core and standard libraries throw exceptions." Of course you have a choice. Your function can return anything you want: def mysqrt(x): try: return math.sqrt(x) except ValueError: return "Code 37" I've written functions that return an object on success and None if the function failed. In the context of what I was doing, that made more sense than raising an exception. Furthermore, the str.find() method returns -1 for not found instead of raising an exception. There are probably other examples as well. You also wrote: "Exceptions exist for exceptional situations: unanticipated events that are not a part of normal execution." Exceptions can and often are anticipated. E.g. if you write code that opens a URL, you better anticipate that the server might reject your connection. You better expect to be asked for a cookie, or authentication. If you check for robots.txt, you better expect that it might not exist. That's all normal execution. "When a programmer calls str.find('substring') he doesn?t expect an exception to be thrown if the substring isn?t found." But if he called str.index() then he does expect an exception to be thrown, just like for list.index() and dict[key] can raise exceptions. They are neither bugs nor unexpected. "This is what he called find for. A better approach is to return a special value like None or -1." Sometimes, maybe. But usually not, because that just complicates the calling code. You end up writing code that repeatedly checks that the result isn't a special value before doing anything. Often a better tactic is to write your code assuming that the result is the unexceptional case, and then wrap it in a try...except block to catch the exceptional cases. "When used for flow-control, exceptions are like goto. There might be a few esoteric cases in which they?re appropriate, but 99.99% of the time they are not." I strongly disagree. try...except is like break or continue. Yes, it breaks the linear flow of control, but not in a wild, dangerous way like goto. It is possible to write bad code with exceptions, but you can write bad code with anything. -- Steven From gminick at bzt.bzt Fri Aug 15 11:17:50 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Fri, 15 Aug 2008 15:17:50 +0000 (UTC) Subject: How do I control output buffering on Win32? References: <1I-dndTLBfGbCjjVnZ2dnUVZ_hCdnZ2d@posted.visi> Message-ID: On Fri, 15 Aug 2008 09:47:34 -0500, Grant Edwards wrote: > When I ssh in to my Windows XP box and run Python apps, output > from "print" and and "sys.stdout.write()" is being buffered so > that none of the output shows up until the program exits. > > From within my program how do I set output buffering to either > line-buffered or un-buffered? [I'm looking for the equivalent > of the C stdio "setbuf" call.] That's not exactly what you want, but what about creating your own printing function and flushing at its end? import sys def printf(mystr): print mystr sys.stdout.flush() -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From timothy.grant at gmail.com Mon Aug 4 20:28:52 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Mon, 4 Aug 2008 17:28:52 -0700 Subject: Module re, extract on string match In-Reply-To: References: Message-ID: On Mon, Aug 4, 2008 at 4:54 PM, Sriram Rajan wrote: > I am wondering if I can use re.search to extract from a particular > location in a string. > Example: > string1='/Users/sriram/folder1/folder2/folder3/folder4/folder5/file' > re.search ('folder3,string1) > > > > Thanks, > > Sriram Something like below? Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> s = '/Users/sriram/folder1/folder2/folder3/folder4/folder5/file' >>> y = re.search('folder3.*', s) >>> y.group() 'folder3/folder4/folder5/file' >>> -- Stand Fast, tjg. [Timothy Grant] From timr at probo.com Mon Aug 18 01:17:52 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 18 Aug 2008 05:17:52 GMT Subject: export sites/pages to PDF References: Message-ID: jvdb wrote: > >My employer is asking for a solution that outputs the content of urls >to pdf. It must be the content as seen within the browser. >Can someone help me on this? It must be able to export several kind of >pages with all kind of content (javascript, etc.) There are a number of obstacles to this. Printer pages are a different size from screen windows, so the browser does the layout differently. Further, many style sheets have rules that are "screen only" or "print only". If you really want an image of exactly what's on the screen, then I don't think you have any option other than a screen capture utility, like "xwd". -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tjreedy at udel.edu Fri Aug 1 16:45:10 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 01 Aug 2008 16:45:10 -0400 Subject: Difference between type and class In-Reply-To: References: <87myjy2vc6.fsf@nokile.rath.org> <00a23ad3$0$20313$c3e8da3@news.astraweb.com> Message-ID: Thomas Troeger wrote: > Steven D'Aprano wrote: >>> class A: >>> def bar(self): >>> print "A" >> >> >> Alas, you've chosen the worst-possible example to "clarify" matters, >> because old-style classic classes are *not* unified with types, and >> will disappear in the future: > > Of course I wanted to write `class A(object)', but I keep forgetting > this one because I'm still used to the old ways... > > Will this disappear in Python 3.0., i.e. can you again simply write > class A: > and inherit from object automagically? Yes. IDLE 3.0b2 >>> class a: pass >>> a >>> a.__bases__ (,) 3.0 is really a nicer version. Once the final release is out, the main reason to stick with 2.x for new code will be if it depends on third-party code (including your own ;-) that has not been upgraded. From brahmaforces at gmail.com Tue Aug 19 02:32:05 2008 From: brahmaforces at gmail.com (brahmaforces) Date: Mon, 18 Aug 2008 23:32:05 -0700 (PDT) Subject: Python Substitute for PHP GD, Resizing an image on the client side Message-ID: <02f733bb-e734-46a9-b42f-5b664cdddd3f@v26g2000prm.googlegroups.com> Hi Folks, I am using cherrypy and python. I am trying to get a user profile image to resize on the client side before uploading to the server. PHP has a gd library that does it it seems. Has anyone done this in a python environment without uploading to the server? From prologic at shortcircuit.net.au Thu Aug 28 00:48:58 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 28 Aug 2008 14:48:58 +1000 Subject: List of modules available for import inside Python? In-Reply-To: References: Message-ID: On Thu, Aug 28, 2008 at 2:21 PM, ssecorp wrote: > Also, is there anything like Cpan for Python? Try the Python Cheese Shop / PyPi http://pypi.python.org/pypi cheers James -- -- -- "Problems are solved by method" From george.sakkis at gmail.com Fri Aug 22 23:13:49 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 22 Aug 2008 20:13:49 -0700 (PDT) Subject: Should Python raise a warning for mutable default arguments? References: <00becb2d$0$20312$c3e8da3@news.astraweb.com> <6h8hhhFk2gamU1@mid.uni-berlin.de> <00bf687f$0$20312$c3e8da3@news.astraweb.com> Message-ID: <3c3ec9a8-5d1e-4aeb-afce-267d99520a67@x41g2000hsb.googlegroups.com> On Aug 22, 9:54?pm, Steven D'Aprano wrote: > On Fri, 22 Aug 2008 14:39:11 -0700, Emile van Sebille wrote: > > Dan wrote: > >> I'd suggest that at the > >> end of the tutorial, when people have a better general idea of how > >> Python works, there would be a Python Gotchas section. > > > Hmmm, OK -- mutable defaults, integer division, name mangling... > > > I'd think decimal precision is more a general problem than a python > > problem, but still one that throws newbies... > > > Any other ideas for gotcha's (as opposed to faqs)? > > Augmented assignment: x ?= y is not always the same as x = x ? y. > > Repeated string addition can be very slow. For that matter, so can list > addition. > > Inserting at the beginning of lists is slow. > > Everything about unicode is a Gotcha! *wink* > > Raw strings are not designed for Windows paths, they're designed for > regexes. Consequently, you can't write the following: > > r'C:\dir\' > > list.sort() and list.reverse() return None. > > sorted() returns a list, but reversed() returns an iterator. > > urllib2.urlopen() will automatically detect the proxy in your environment > and use that. That's usually a feature, but sometimes it can be a gotcha. > > urllib2 doesn't work well with some HTTPS proxies. This is, I believe, a > known bug, but until it is fixed, it can be a gotcha. My "favorite": comparisons between disparate types are allowed by default. Thankfully fixed in 3.0. George From steve at REMOVE-THIS-cybersource.com.au Mon Aug 25 19:48:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Aug 2008 23:48:00 GMT Subject: Replace reduce with listcomprehension? References: <3a99c7ea-4cc9-4b9f-b6f8-60856cbd8837@c58g2000hsc.googlegroups.com> <836b78ed-605b-4b23-933e-116953103a0f@d77g2000hsb.googlegroups.com> <297c7ac3-f63a-4ffe-8597-ef975b8bf5b8@y21g2000hsf.googlegroups.com> <6hgrffFlsv2pU1@mid.uni-berlin.de> Message-ID: <00c33f63$0$15868$c3e8da3@news.astraweb.com> On Tue, 26 Aug 2008 00:53:35 +0200, Diez B. Roggisch wrote: >> So it seems only reduce will be eliminated. > > Nope. From the link you provided yourself: > > """ > Only reduce will be removed from the 3.0 standard library. You can > import it from functools. > """ functools isn't in the standard library??? *wink* Seriously, I think Guido meant "built-ins". Since I don't agree with him that reduce() is hard to read, I disagree that accumulators are easier to use. But since reduce is only an import away, I'm satisfied. -- Steven From bj_666 at gmx.net Wed Aug 27 11:39:30 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Aug 2008 15:39:30 GMT Subject: Getting references to obect instances into a list References: <59619323-8ff1-4697-bfbe-b19aa478e8b8@m44g2000hsc.googlegroups.com> Message-ID: <6hlapiFmn37uU1@mid.uni-berlin.de> On Wed, 27 Aug 2008 08:32:52 -0700, parent.eric.3 at gmail.com wrote: > Thanks for your reply Simon. > > I will read the article you told me to but first, please, have a look at > this snippet: Please read the article! >>>> m = [2,3,4] >>>> p = ['a','b','c'] >>>> q = [m,p] >>>> q > [[2, 3, 4, 'a', 'b', 'c'], ['a', 'b', 'c']] >>>> del p >>>> q > [[2, 3, 4, 'a', 'b', 'c'], ['a', 'b', 'c']] >>>> >>>> > > How come q is not updated after I deleted p? Because neither the name `q` nor the list object bound to it has anything to do with the name `p`. ``del`` does not delete objects but *names*. Objects exist as long as there is a reference to them. You deleted the name `p` and thus one reference to the list with the three characters but there's still the reference from the list bound to `q` to that three character list. What did you expect for an "updated q" anyway? Ciao, Marc 'BlackJack' Rintsch From Slaunger at gmail.com Thu Aug 7 02:16:52 2008 From: Slaunger at gmail.com (Slaunger) Date: Wed, 6 Aug 2008 23:16:52 -0700 (PDT) Subject: Best practise implementation for equal by value objects References: <135eb396-6daa-4ff4-a722-253ba149889c@27g2000hsf.googlegroups.com> Message-ID: <573362d6-5356-4029-8ee4-f43248263976@p25g2000hsf.googlegroups.com> On 6 Aug., 21:36, Terry Reedy wrote: > Slaunger wrote: > > Hi, > > > I am new here and relatively new to Python, so be gentle: > > > Is there a recommended generic implementation of __repr__ for objects > > equal by value to assure that eval(repr(x)) == x independet of which > > module the call is made from? > > The CPython implementation gives up on that goal and simply prints > for at least two reasons ;-). > > 1. In general, it require fairly sophisticated analysis of __init__ to > decide what representation of what attributes to include and decide if > the goal is even possible. ?If an attribute is an instance of a user > class, then *its* __init__ needs to be analyzed. ?If an attribute is a > module, class, or function, there is no generic evaluable representation. OK, the situation is more complicated than that then. In the case here though, the attributes would always be sinmple bulit-in types, where eval(repr(x))==x or, where the attribute is a user-defined equal-by-value class, that I have control over. The classes I am making as struct type classes with some added functionlity for human readable string representation, packing into a stream or unpacking from a stream using a "private" class Struct. I come from a Java and JUnit world, where, if I am used to always overriding the default reference based implementations of the equals(), toString(), and hashCode() methods for "equals-by-value" objects such that they work well and efficient in, e.g., hash maps. With my swich-over to Python, I looked for equivalent features and stumbled over the eval(repr(x))==x recommendation. It is not that I actually (yet) need the repr implementations, but mostly because I find the condition very useful in PyUnit to check in a test that I have remembered to initialize all instance fields in __init__ and that I have remembered to include all relevant attributes in the __eq__ implementation. Whereas this worked fine in a unit test module dedicated to only test the specific module, the test failed when called from other test package modules, wrapping the unit tests from several unit test modules. > > 2. Whether eval(repr(x)) even works (returns an answer) depends on > whether the name bindings in the globals and locals passed to eval > (which by default are the globals and locals of the context of the eval > call) match the names used in the repr. ?You discovered that to a first > approximation, this depends on whether the call to repr comes from > within or without the module containing the class definition. ?But the > situation is far worse. ?Consider 'import somemod as m'. ?Even if you > were able to introspect the call and determine that it did not come from > somemod**, prepending 'somemod.' to the repr *still* would not work. > Or, the call to repr could come from one context, the result saved and > passed to another context with different name bindings, and the eval > call made there. ?So an repr that can be eval'ed in any context is hopeless. > Ok, nasty stuff > If this is a practical rather than theoretical question, then use your > first repr version that uses the classes definition name and only eval > the result in a context that has that name bound to the class object. > > from mymod import Age > #or > import mymod > Age = mymod.Age > > #in either case > eval(repr(Age(10))) == Age(10) > > > class Age: > > > ? ? def __init__(self, an_age): > > ? ? ? ? self.age = an_age > > > ? ? def __eq__(self, obj): > > ? ? ? ? self.age == obj.age > > > ? ? def __repr__(self): > > ? ? ? ? return self.__class__.__name__ + \ > > ? ? ? ? ? ? ? ?"(%r)" % self.age > Yes, it is most from a practicl point of view, altough I was surprised that I could not find more material on it in the Python documentation or mailing groups, and I moight just do what you suggest in the unit test modules to at least make it robust in that context. Hmm... a bit of a dissapointment for me that this cannot be done cleaner > ** > While such introspection is not part of the language, I believe one > could do it in CPython, but I forgot the details. ?There have been > threads like 'How do I determine the caller function' with answers to > that question, and I presume the module of the caller is available also. OK, I think CPython, for the moment, is too much new stuff to dig into right now. Just grasping some of all the possibilities in the API, and how to do things the right way is giving me enough challenges for now... > > Terry Jan Reedy Again, thank you for your thorough answer, Slaunger From hubaghdadi at gmail.com Wed Aug 27 06:09:58 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Wed, 27 Aug 2008 03:09:58 -0700 (PDT) Subject: Understanding this generator function Message-ID: Hey, This is an example of a generator function: ===== def counter(start_at=0): count = start_at while True: val = (yield count) if val is not None: count = val else: count += 1 ====== >>> count = counter(5) >>> count.next() 5 >>> count.send(9) 9 ====== I'm not able to understand how this generator function is working, would you please me (what happens when calling next/send)? Thanks. From davidreynon at gmail.com Tue Aug 19 11:42:55 2008 From: davidreynon at gmail.com (korean_dave) Date: Tue, 19 Aug 2008 08:42:55 -0700 (PDT) Subject: datetime.datetime.now() in military time Message-ID: <4401a30e-0445-40d3-b23a-bec538ff148c@a70g2000hsh.googlegroups.com> import datetime def main(): timenow = datetime.datetime.now() print(str(timenow.hour)) if __name__ == "__main__": main() If the time was, say, 2pm, how can I make output of timenow.hour "14" instead of "2"? Thanks. -Dave From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 26 04:52:30 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 26 Aug 2008 10:52:30 +0200 Subject: A variables variables In-Reply-To: <5455bc1a-a4fe-42b2-ab86-9becf30b8f6e@x35g2000hsb.googlegroups.com> References: <625fce19-df89-4a6c-890a-22008a4fe92f@c58g2000hsc.googlegroups.com> <5455bc1a-a4fe-42b2-ab86-9becf30b8f6e@x35g2000hsb.googlegroups.com> Message-ID: <48b3c41f$0$30971$426a74cc@news.free.fr> castironpi a ?crit : > On Aug 23, 7:25 pm, Gandalf wrote: >> how can I declare a variable with another variable name? >> >> for example I will use PHP: >> >> $a= "hello"; >> >> $a_hello="baybay"; >> >> print ${'a_'.$a) //output: baybay >> >> how can i do it with no Arrays using python >> >> thanks! > > Here's one idea. > >>>> a= 'hello' >>>> a_hello= 'bayb' >>>> print eval( 'a_'+ a ) > bayb Please avoid this kind of yucky ugly hacks. From ivan at datasyncorp.com Mon Aug 4 11:40:37 2008 From: ivan at datasyncorp.com (Ivan Ven Osdel) Date: Mon, 4 Aug 2008 10:40:37 -0500 (CDT) Subject: Agnostic fetching In-Reply-To: <6fjetjFbovjiU1@mid.uni-berlin.de> Message-ID: <909379793.819371217864437840.JavaMail.root@saturn.datasyncintra.net> >----- Original Message ----- >From: "Diez B. Roggisch" >To: python-list at python.org >Sent: Saturday, August 2, 2008 11:05:07 AM GMT -06:00 US/Canada Central >Subject: Re: Agnostic fetching >Bruce Frederiksen schrieb: > On Fri, 01 Aug 2008 17:05:00 -0700, jorpheus wrote: > >> OK, that sounds stupid. Anyway, I've been learning Python for some >> time now, and am currently having fun with the urllib and urllib2 >> modules, but have run into a problem(?) - is there any way to fetch >> (urllib.retrieve) files from a server without knowing the filenames? >> For instance, there is smth like folder/spam.egg, folder/ >> unpredictable.egg and so on. If not, perhaps some kind of glob to >> create a list of existing files? I'd really appreciate some help, >> since I'm really out of my (newb) depth here. > > You might try the os.path module and/or the glob module in the standard > python library. >Not on remote locations. The only work on your local filesystem. >Diez Here's a function I wrote for checking remote or local file existence. It works for me but admittedly I haven't tested many cases with it. Also its currently specific to an http URI scheme. def fileExists(self, fileUrlPath): fileExists = False if "http:" in fileUrlPath.lower(): #We don't want to open the file so ask the header if the #file exists urlParts = urlparse(fileUrlPath) host = urlParts[1] http = httplib.HTTP(host) http.putrequest("HEAD", fileUrlPath) http.putheader("Host", host) http.endheaders() errorcode, errormessage, headers = http.getreply() if errorcode == 200: fileExists = True else: fileExists = path.exists(fileUrlPath) return fileExists -- Ivan Ven Osdel http://datasyncsuite.com From __peter__ at web.de Mon Aug 11 05:38:57 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 11 Aug 2008 11:38:57 +0200 Subject: benchmark References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> Message-ID: M8R-n7vorv at mailinator.com wrote: > On Aug 10, 10:10?pm, Kris Kennaway wrote: >> jlist wrote: >> > I think what makes more sense is to compare the code one most >> > typically writes. In my case, I always use range() and never use psyco. >> > But I guess for most of my work with Python performance hasn't been >> > a issue. I haven't got to write any large systems with Python yet, >> > where performance starts to matter. >> >> Hopefully when you do you will improve your programming practices to not >> make poor choices - there are few excuses for not using xrange ;) >> >> Kris > > And can you shed some light on how that relates with one of the zens > of python ? > > There should be one-- and preferably only one --obvious way to do it. For the record, the impact of range() versus xrange() is negligable -- on my machine the xrange() variant even runs a tad slower. So it's not clear whether Kris actually knows what he's doing. For the cases where xrange() is an improvement over range() "Practicality beats purity" applies. But you should really care more about the spirit than the letter of the "zen". Peter From weiguo6 at gmail.com Thu Aug 7 16:28:46 2008 From: weiguo6 at gmail.com (Wei Guo) Date: Thu, 7 Aug 2008 13:28:46 -0700 Subject: A question about string and float number In-Reply-To: References: <489A8A01.1050908@linkline.com> Message-ID: Hi I tried the first type method but it seens that it doesn't work. Could anyone help me about it? >>> s = '3.145' >>> type(s) == type(float()) False >>> type(s) >>> type(float()) >>> Best regards, Wei On 8/7/08, Wei Guo wrote: > > Hi Thanks for Tyler and Edwin's help. > > For my questions, I need to import some xml file and there are floating > number and strings in it. I need to process string and number differently. > This is reason that I am asking question here. Is this background > information we need for this quesions. > > Btw, which way is better? type or with exception ValueError? > > Thanks, > > Wei > > > On 8/6/08, Tyler Breisacher wrote: >> >> It's generally a bad idea to use "except" without naming a specific >> exception. The exception you might expect in this case is ValueError. Any >> other exception *should* be uncaught if it happens. By the way, this method >> will return true for integers as well as floats. For example, isFloat('3') >> will return 3.0. So make sure this is what you want, since it wasn't 100% >> clear from the original message. >> >> >> Wei Guo wrote: >> >>> #this is a better way of testing a string for float >>> def isFloat(s): >>> try: >>> s = float(s) >>> except: >>> return False >>> return True >>> >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From marco.bizzarri at gmail.com Sat Aug 30 13:48:10 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 30 Aug 2008 19:48:10 +0200 Subject: Counting Elements in an xml file In-Reply-To: <7dd68868-5490-464d-9cc1-ddf6a2c50dbe@l42g2000hsc.googlegroups.com> References: <7dd68868-5490-464d-9cc1-ddf6a2c50dbe@l42g2000hsc.googlegroups.com> Message-ID: <3f0d61c40808301048ra3a08f6l283790381686080b@mail.gmail.com> On Sat, Aug 30, 2008 at 7:37 PM, Ouray Viney wrote: > Hi All: > > I am looking at writing a python script that will let me parse a > TestSuite xml file that contains n number of TestCases. > > My goal is to be able to count the elements base on a key > value pair in the xml node. > > Example > > > > I would like to be able to count the number of TestCases that contain > the "execute=true" but not the ones that contain "execute=false". > > I have review the python docs and various python ebooks. > > Does anyone have any experience with this sort of thing? If so, could > you suggest a good library and possibly some samples? Isn't the SAX part of this howto http://pyxml.sourceforge.net/topics/howto/xml-howto.html enough for you to create your parser? Regards Marco -- Marco Bizzarri http://iliveinpisa.blogspot.com/ http://notenotturne.blogspot.com/ From hishaam.ab at gmail.com Wed Aug 13 08:04:34 2008 From: hishaam.ab at gmail.com (Hishaam) Date: Wed, 13 Aug 2008 05:04:34 -0700 (PDT) Subject: Regarding Telnet library in python Message-ID: <7412fd2f-b6b0-4b91-b05e-53b434d6fd2e@w24g2000prd.googlegroups.com> Hi, In python documentation, i found a telnet example as follows: ------------------------------------------------------------------------- import getpass import sys import telnetlib HOST = "localhost" user = raw_input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until("login: ") tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") tn.write("ls\n") tn.write("exit\n") print tn.read_all() ------------------------------------------------------------------------- The ouput of it as follows: ------------------------------------------------------------------------- Enter your remote account: root Last login: Mon Aug 13 11:54:32 from pcp246879pcs.ca Sun Microsystems Inc. SunOS 5.10 Generic January 2005 # Desktop boot hishaam net system work Documents cdrom home opt tfile2 zonemgr File.txt dev kernel platform tmp QA_tmp devices lib proc usr acunix etc lost+found sbin var bin export mnt sfile vol # ------------------------------------------------------------------------- The difficulty i find in this is th code line "print tn.read_all()" is used for reading all of the output of the code at once. Is there a possibility to read the stdout of each command by command like - # ls [capture in a variable] # cd /root [capture in a variable] Like the above would be useful if there are a large number of commands to be executed in the telnet session. Can anyone help on this? Regards, Hishaam From harrrrpo at gmail.com Sun Aug 24 06:11:03 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Sun, 24 Aug 2008 13:11:03 +0300 Subject: Imports visibility in imported modules problem In-Reply-To: <1bb81100-c8bb-48e6-b9f9-ce199d8198f1@m45g2000hsb.googlegroups.com> References: <1bb81100-c8bb-48e6-b9f9-ce199d8198f1@m45g2000hsb.googlegroups.com> Message-ID: <538050a90808240311k6c619b82g820ef75875262927@mail.gmail.com> On Sun, Aug 24, 2008 at 5:54 AM, Patrick Maupin wrote: > On Aug 23, 7:27 pm, "Mohamed Yousef" wrote: > >> The problem I'm asking about is how can imported modules be aware of >> other imported modules so they don't have to re-import them (avoiding >> importing problems and Consicing code and imports ) > > You could import sys and look at sys.modules no even if you imported sys or used dir you will see no re in W() from A . and you can even try to use re and will see >> why am i doing this in the first place I'm in the process of a medium >> project where imports of modules start to make a jungle and i wanted >> all needed imports to be in a single file (namely __init__.py) and >> then all imports are made once and other modules feel it > > This doesn't sound like a good idea. If A imports a module which is > automatically imported into B's namespace, that sounds like a > maintenance nightmare. why ? this saves time and consices whole package imports in one file and maintaining it is easier (eg. you will never have circuular imports) >> >> another reason to do this that my project is offering 2 interfaces >> (Console and GUI through Qt) and i needed a general state class ( >> whether i'm in Console or GUI mode) to be available for all , for >> determining state and some public functions ,and just injecting >> Imports everywhere seems a bad technique in many ways (debugging , >> modifying ...etc ) > > I still don't understand. put it another way a general variable in all modules and some functions visible in all modules >> in PHP "Require" would do the trick neatly ... so is there is >> something I'm missing here or the whole technique is bad in which case >> what do you suggest ? > > I don't know what to suggest, in that you haven't yet stated anything > that appears to be a problem with how Python works. If two different > modules import the same third module, there is no big performance > penalty. The initialization code for the third module is only > executed on the first import, and the cost of having the import > statement find the already imported module is trivial. it's not performance it's the jungle resulting many imports in every file and suppose i changed the module used in all modules name guess what , it will have to be renamed in every import to it in all modules From henhiskan at gmail.com Thu Aug 28 13:18:48 2008 From: henhiskan at gmail.com (Richard Rossel) Date: Thu, 28 Aug 2008 10:18:48 -0700 (PDT) Subject: epoch seconds from a datetime Message-ID: <40ab500b-f33f-4d6a-9c7c-fecee0119ba0@s50g2000hsb.googlegroups.com> Hi friends, I need a little help here, I 'm stuck with epoch calculation issue. I have this datetime: date_new = datetime(*time.strptime('20080101T000000','%Y%m%dT%H%M%S') [0:6]) This date_new is in UTC Now I need to know the seconds since epoch of this new date, so I run this: seconds = int(time.mktime(date_new.timetuple())) but the seconds returned belongs to : Tue, 01 Jan 2008 03:00:00 GMT because the localtime is in timezone 'America/Santiago': -3 I fix this trying to alter the TZ with time.tzset(): os.environ['TZ'] = 'UTC' time.tzset() .... and now I can gets the right epoch, but I can't restore the previous TimeZone, I try with: os.environ['TZ'] = '', but the time.tzset() doesn't back to the original ( America/Santiago) A solution should be set the os.environ['TZ'] to 'America/Santiago' but I can't make a TZ hardcode because the software should works on different timezones. So the question, how can restore the system into original timezone, or how to know the seconds since epoch from UTC datetime without change the local system TIMEZONE. please help From williamhpurcell at gmail.com Thu Aug 21 16:45:16 2008 From: williamhpurcell at gmail.com (William Purcell) Date: Thu, 21 Aug 2008 15:45:16 -0500 Subject: programming toolbox Message-ID: Hi all, I started programming with python about a year ago. I am now somewhat experienced with python but have virtually no experience with any other language. I use python to write little command line tools, GUI's to do anything from my time sheet at work to balancing my checkbook, and for school to do plotting and data manipulation. I was wondering what more experienced programmers think about what languages are necessary to be able to handle most programming problems. Another way to word the question is... Should I spend the time to learn C/C++ (or any other for that matter) or will Python handle most programming problems? Especially for applications that other people want to use and I need stability and speed. Just Curious, Bill P.S. If you do think it's worth learning C/C++...what type problems are fit for C/C++ and which should I keep with Python for? What are a couple languages that really complement python? -------------- next part -------------- An HTML attachment was scrubbed... URL: From adityashukla1983 at gmail.com Wed Aug 27 00:15:58 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Tue, 26 Aug 2008 23:15:58 -0500 Subject: Extracting path of a program from a list. Message-ID: <73045cca0808262115w71afa3adjc3565e204fd1d90f@mail.gmail.com> Hello folks, I wanna know how can i extract path of a program whose path i have added to the PATH variable. This is what i have done import os x=os.getenv("PATH") print x >>%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;c:\Program Files\Microsoft SQL Server\90\Tools\binn\;C:\Program Files\QuickTime\QTSystem\;C:\folder1\folder2\prog Now i have to extract the path of my program ie (C:\folder1\folder2\prog) .I mean i can split the string using y=x.split(';') a=y[-1] but i dont wanna do this way ,i wanna search for my program from this list and then return its path Please help me on this. Thanks in advance. Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Aug 14 11:47:23 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 17:47:23 +0200 Subject: for y in range (0,iNumItems)--> not in order? In-Reply-To: References: <8514d915-95bf-4e57-a16a-68866e0ad789@l42g2000hsc.googlegroups.com> Message-ID: korean_dave wrote: > Still the same output... > > Here's the actual code... > > for x in range(0,2): > for y in range(0,27): > for z in range(0,15): > print(str(x) + " " + str(y) + " " + str(z)) umm. that's even less related to your original output than your earlier code sample. $ python actual_code.py 0 0 0 0 0 1 0 0 2 0 0 3 0 0 4 ... 1 26 10 1 26 11 1 26 12 1 26 13 1 26 14 please do a little more debugging on your own machine before claiming that fundamental python features that's been around for ages suddenly won't work. From mail at timgolden.me.uk Sat Aug 9 18:34:51 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 09 Aug 2008 23:34:51 +0100 Subject: Win32 trouble with threading, signals, and sleep() In-Reply-To: <839ec5810808081817l4c47df87m2ed18edb54190dd4@mail.gmail.com> References: <839ec5810808081817l4c47df87m2ed18edb54190dd4@mail.gmail.com> Message-ID: <489E1B8B.9090603@timgolden.me.uk> Lowell Alleman wrote: > I'm running into this issue on Windows with the follow exception at > the time when the signal handler is called: > > Traceback (most recent call last): > ... > self.done.wait(30) > File "D:\Python24\lib\threading.py", line 348, in wait > self.__cond.wait(timeout) > File "D:\Python24\lib\threading.py", line 222, in wait > _sleep(delay) > IOError: [Errno 4] Interrupted function call Well you've certainly picked a ticklish area to run into problems with ;). First, forget about the threading aspects for the moment. AFAICT the smallest program which reproduces your problem is: import signal import time def handler (*args): pass signal.signal(signal.SIGBREAK, handler) time.sleep (10) Now run that and do a ctrl-break somewhere in that time.sleep. Sure enough... Traceback (most recent call last): File "C:\data\temp\sig3.py", line 8, in time.sleep (10) IOError: [Errno 4] Interrupted function call Under the covers, the sleep function is implemented as a WaitForSingleObject call with a timeout. The object being waited on is an anonymous event which is set from a console ctrl handler when one of those interrupts happens (ctrl-c / ctrl-break / shutdown). This makes sure that the (otherwise blocking) sleep can be interrupted. Something like this: import win32api import win32event hEvent = win32event.CreateEvent (None, 1, 0, None) def handler (*args): win32event.PulseEvent (hEvent) return True win32api.SetConsoleCtrlHandler (handler, 1) # # This line is basically the sleep happening # win32event.WaitForSingleObject (hEvent, 10000) For reasons which I'm not aware of, the code recognises that the interrupt has fired and sets the WSAEINTR error code, which is the IOError 4 which you're seeing, and then exits. EINTR is usually issued when a blocking call is cancelled explicitly, so presumably this is considered a simulation of that. Not sure. What happens now is that control passes back out to the routine which called the sleep. But... an exception condition has been set inside the sleep call and is now raised, appearing to come from within the routine which called sleep. Clear? You could obviously continue to catch the exception. Alternatively, I think your best bet, as long as you can make it work with the threads, is to install your own console ctrl handler. Note that the docs for this specify that: "When the signal is received, the system creates a new thread in the process to execute the function." So you'll need to be quite careful to make your code thread-safe. But it should work. I adapted your example slightly to replace all of the lines setting the signal handlers to one statement: win32api.SetConsoleCtrlHandler (handler, 1) and the handler function itself takes only one arg, the signal no, and returns False to indicate that control should pass to the next handler, which will probably be the default Python handler: def handler(arg): print "Signal handler", arg global workers for w in workers: w.stop() return False Hope that all helps. TJG From ronald.johnson at gmail.com Tue Aug 5 12:30:31 2008 From: ronald.johnson at gmail.com (ronald.johnson at gmail.com) Date: Tue, 5 Aug 2008 09:30:31 -0700 (PDT) Subject: Is there a faster way to do this? Message-ID: <8dbfab27-770e-44a5-b4db-12f67d21ab3f@t54g2000hsg.googlegroups.com> I have a csv file containing product information that is 700+ MB in size. I'm trying to go through and pull out unique product ID's only as there are a lot of multiples. My problem is that I am appending the ProductID to an array and then searching through that array each time to see if I've seen the product ID before. So each search takes longer and longer. I let the script run for 2 hours before killing it and had only run through less than 1/10 if the file. Heres the code: import string def checkForProduct(product_id, product_list): for product in product_list: if product == product_id: return 1 return 0 input_file="c:\\input.txt" output_file="c:\\output.txt" product_info = [] input_count = 0 input = open(input_file,"r") output = open(output_file, "w") for line in input: break_down = line.split(",") product_number = break_down[2] input_count+=1 if input_count == 1: product_info.append(product_number) output.write(line) output_count = 1 if not checkForProduct(product_number,product_info): product_info.append(product_number) output.write(line) output_count+=1 output.close() input.close() print input_count print output_count From fredrik at pythonware.com Tue Aug 19 11:04:18 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Aug 2008 17:04:18 +0200 Subject: who to call a list of method inside the class itself In-Reply-To: References: <95910272-2045-4170-ab6e-549489b12108@d77g2000hsb.googlegroups.com> Message-ID: maduma at pt.lu wrote: >>> def getAllMethod(self): >>> return [self.method1, self.method2, self.method3] >>> def applyAll(self): >>> for m in self.getAllMethod(): >>> # how to call all methods ? >>> # is it correct >>> m() >> what happens when you run the code? > The code it is running fine but i just wondering if it's the syntax is > correct (avoid any side effect) It's the same thing as explicitly calling the three methods from inside the applyAll method. You'll still get side effects if the methods have side effects, of course. self.method1 and friends are "bound methods", that is, callable objects that are bound to both the object instance (self) and the actual method. They're no different from the temporary bound methods that are used to carry out an ordinary method call ("self.method1()" is evaluated as "tmp = self.method1; tmp()" on the inside, where tmp is an internal variable) From dullrich at sprynet.com Tue Aug 5 11:47:07 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 05 Aug 2008 10:47:07 -0500 Subject: PIL (etc etc etc) on OS X References: <489379A7.5060009@codebykevin.com> <48948BBA.9050706@codebykevin.com> <489797fc$0$49816$e4fe514c@news.xs4all.nl> Message-ID: In article <489797fc$0$49816$e4fe514c at news.xs4all.nl>, Irmen de Jong wrote: > David C. Ullrich wrote: > > Just as well that the message sent earlier today > > seems to have been lost... > > > > Ok. Read your instructions on libjpeg. Read some > > of the install.doc. ./configure, fine. make, fine. > > "make test", fine. So I said "sudo make install" > > and this happened: > > > > 0-1d-4f-fc-28-d:jpeg-6b dullric$ sudo make install > > Password: > [...] > > I had to do the following to build and install it in a way such that PIL > would recognise > it. But it does now, without changing anything in PIL's setup files. > > $ cd jpeg-6b/ > $ ln -s `which glibtool` libtool > $ export MACOSX_DEPLOYMENT_TARGET=10.4 > $ ./configure --enable-shared --enable-static --host=powerpc > $ make > $ sudo make install Thanks - that gets me closer: I'd already found out about the --enable-* switches, but when I tried them it complained it couldn't find ./libtool. I _guessed_ host should be intel I changed the 10.4 to 10.5 and did this: $ ln -s `which glibtool` libtool $ export MACOSX_DEPLOYMENT_TARGET=10.4 $ ./configure --enable-shared --enable-static --host=intel $ make $ sudo make install That fixed the complaints about no ./libtool, great. Then I went back to PIL. The setup.py reported that everything was great, including JPEG. And then selftest.py said it couldn't find a jpeg decoder... 0-1d-4f-fc-28-d:Imaging-1.1.6 dullric$ python selftest.py ***************************************************************** Failure in example: _info(Image.open("Images/lena.jpg")) from line #24 of selftest.testimage Exception raised: Traceback (most recent call last): File "./doctest.py", line 499, in _run_examples_inner exec compile(source, "", "single") in globs File "", line 1, in File "./selftest.py", line 22, in _info im.load() File "PIL/ImageFile.py", line 180, in load d = Image._getdecoder(self.mode, d, a, self.decoderconfig) File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available 1 items had failures: 1 of 57 in selftest.testimage ***Test Failed*** 1 failures. *** 1 tests of 57 failed. > > (note that I have a PPC mac so the host parameter may not be correct for your > system) > --irmen -- David C. Ullrich From cito at online.de Fri Aug 15 14:53:57 2008 From: cito at online.de (Christoph Zwerschke) Date: Fri, 15 Aug 2008 20:53:57 +0200 Subject: Missing exceptions in PEP 3107 In-Reply-To: <1d08d8f1-abb7-4bf3-83a8-2a109dc62ce6@a3g2000prm.googlegroups.com> References: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> <1d08d8f1-abb7-4bf3-83a8-2a109dc62ce6@a3g2000prm.googlegroups.com> Message-ID: Matimus wrote: > Christoph wrote: >> Maybe the following syntax would be even more intuitive: >> >> def foo(a: "a info", b: "b info") return "ret info" raise "exc info": >> return "hello world" > > That seems much more intuitive and extensible. The "->" syntax has > always bothered me. The main issue I see with it though is that it > might be confusing. Consider: > > def foo(a, b) return 0: > > return a + b > > A person reading the code might be tempted to read the annotation and > think that it is the body. Maybe not a huge problem, but definitely > something that will come up occasionally. Yes, that's a drawback; and the same problem for a "raise" clause. >> Well, yes, but wasn't the whole point of PEP 3107 to get rid of such >> decorators and provide a single standard way of specifying this kind of >> info instead? > > Maybe, but I think it also does two more things: 1. creates a standard > location for storing annotations, and 2. Keeps you from violating DRY > (http://en.wikipedia.org/wiki/DRY). > Using a single decorator for exception info (or even return info) does > not violate either of the two stated benefits. The exception > information would go into the standard annotations dictionary. The > raises decorator does not violate DRY any more or less than it would > if added to the language syntax. That's a valid point, but as you already mentioned, the same applies to the return value. In my opinion it is desirable that either both return value and exceptions get a special syntax, or both must be described using decorators. -- Christoph From grommasher at gmail.com Wed Aug 6 23:15:11 2008 From: grommasher at gmail.com (Grom) Date: Wed, 6 Aug 2008 20:15:11 -0700 (PDT) Subject: Function from C/PHP to Python Message-ID: <814caf84-ec0e-4d15-810a-76a77e399e76@d45g2000hsc.googlegroups.com> Hello everyone :) I have one problem with that function in C int calc_passcode(const char* pass, char* code) { int magic1 = 0x50305735; int magic2 = 0x12345671; int sum = 7; char z; while ((z = *pass++) != 0) { if (z == ' ') continue; if (z == '\t') continue; magic1 ^= (((magic1 & 0x3f) + sum) * z) + (magic1 << 8); magic2 += (magic2 << 8) ^ magic1; sum += z; } magic1 &= 0x7fffffff; magic2 &= 0x7fffffff; return sprintf(code, "%08x%08x", magic1, magic2); } // end _calc_passcode(); Can someone help me to rewrite it to python? There is the same function, in PHP: function _calc_passcode($pass) { $magic1 = 0x50305735; $magic2 = 0x12345671; $sum = 7; for ($i = 0; $i < strlen($pass); $i++) { $z = ord($pass[$i]); if ($z == 32) continue; if ($z == 9) continue; $magic1 = $magic1 ^ (((($magic1 & 0x3f) + $sum) * $z) + ($magic1 << 8)); $magic2 = $magic2 + (($magic2 << 8) ^ $magic1); $sum += $z; $magic1 = $magic1 & 0x7fffffff; $magic2 = $magic2 & 0x7fffffff; } return sprintf('%08x%08x', $magic1, $magic2); } // end _calc_passcode(); Please... its very important to me From kiruta at gmail.com Sun Aug 24 16:24:09 2008 From: kiruta at gmail.com (akva) Date: Sun, 24 Aug 2008 13:24:09 -0700 (PDT) Subject: semantics of the |= operator References: <16f69c9c-386f-41a3-852a-cd482327fc2d@c58g2000hsc.googlegroups.com> <905d2c92-86fe-484c-820e-bf5b853be28f@m3g2000hsc.googlegroups.com> <6h8c0gFk3g8hU1@mid.individual.net> Message-ID: <38202519-3a0e-4978-a6e6-1fdf3153849f@v57g2000hse.googlegroups.com> thanks everybody. From half.italian at gmail.com Wed Aug 20 02:24:20 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Tue, 19 Aug 2008 23:24:20 -0700 (PDT) Subject: searching through a string and pulling characters References: <19039594.post@talk.nabble.com> Message-ID: On Aug 19, 6:11?am, Wojtek Walczak wrote: > On Mon, 18 Aug 2008 15:34:12 -0700 (PDT), Alexnb wrote: > > Also, on a side-note, does anyone know a very simple dictionary site, that > > isn't dictionary.com or yourdictionary.com. > > This one is my favourite:http://www.lingro.com/ > > -- > Regards, > Wojtek Walczak,http://tosh.pl/gminick/ Thats hot! From tedpottel at gmail.com Wed Aug 20 08:42:34 2008 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: Wed, 20 Aug 2008 05:42:34 -0700 (PDT) Subject: TRying to read sercah results from googles web page Message-ID: Hi, I am trying to write a BOT to read the search results from Google. When I read from the www.google.com, the code works fine, loads in the web page. When I try to load in a url with the search results, http://www.google.com/search?hl=en&q=ted', I get a web page that says I do not have permissions. Is theree a way around this, or is Google just to smart???? the program looks like this import urllib print "-------- Google Web Page --------" print urllib.urlopen('http://www.google.com//').read() print "-------- Google Search Web Page --------" print urllib.urlopen('http://www.google.com/search? hl=en&q=ted').read() From dudeja.rajat at gmail.com Sat Aug 30 09:23:52 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 30 Aug 2008 14:23:52 +0100 Subject: How to delete elements from Tix Combo Box? Message-ID: HI, I'm using a Tix combo box (I call it combo2), the contents of which are loaded depeding on the selection in another Tix combo box(I call it combo1) I have used the commands: self.cbAnalysisLibVersion.insert(END, results) to insert elements to the combo box. I'm looking for some similar option to delete elements from the combo box. I mean, as soon as I change selection in combo1 the previous elements in the combo2 should get cleared up( or deleted) and | shall be able to the above insert command to add new elements to the combo2 ( depending upon selection in combo1) Please suggest how can I clear up the ( delete the entries) in combo2. Thanks and regards, Rajat From mail at timgolden.me.uk Thu Aug 28 04:26:23 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 28 Aug 2008 09:26:23 +0100 Subject: calling NetShareEnum win32api with ctypes In-Reply-To: References: Message-ID: <48B6612F.5050905@timgolden.me.uk> taghi wrote: > I wrote this code in python 2.5: > > from ctypes import * ... snip ... > netapi32=cdll.LoadLibrary('netapi32.dll') This is your problem: netapi32 is a windows DLL and needs to be attached as such: netapi32 = windll.LoadLibrary ("netapi32.dll") or, more simply: netapi32 = windll.net32api But see my other post re this function in pywin32 TJG From bart at at.vandeenensupport.punt.com.invalid Fri Aug 22 05:41:18 2008 From: bart at at.vandeenensupport.punt.com.invalid (Bart van Deenen) Date: Fri, 22 Aug 2008 11:41:18 +0200 Subject: def X(l=[]): weirdness. Python bug ? References: <8824d$48ae83b2$18847a51$1995@news.chello.nl> Message-ID: <677cb$48ae8a20$18847a51$6106@news.chello.nl> Hi Thanks all for your answers. I figured your solution already, but now I understand where the behavior is from. One question remains: can I find my parameter 'l' somewhere? I looked in a lot of objects, but couldn't find it. Thanks Bart. cokofreedom at gmail.com wrote: > On Aug 22, 11:13 am, Bart van Deenen > wrote: >> >> # function >> def X(l=[]): >> l.append(1) >> print l >> >> # first call of X >> X() >> [1] >> >> #second call of X >> X() >> [1, 1] >> >> Where does the list parameter 'l' live between the two successive calls >> of X(). Why is it not recreated with an empty list? >> Is this correct behavior or is it a Python bug? >> Does anyone have any pointers to the language documentation where this >> behavior is described? >> > "Default parameter values are evaluated when the function definition > is executed." > > Depending on your use the common way to handle this is to do > > def x(lst = None): > if lst is None: > pass # lst has not been set to anything > else: > pass # lst has been set to something From jkrukoff at ltgc.com Wed Aug 6 15:46:27 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Wed, 06 Aug 2008 13:46:27 -0600 Subject: Best practise implementation for equal by value objects In-Reply-To: <135eb396-6daa-4ff4-a722-253ba149889c@27g2000hsf.googlegroups.com> References: <135eb396-6daa-4ff4-a722-253ba149889c@27g2000hsf.googlegroups.com> Message-ID: <1218051988.25651.19.camel@jmk> On Wed, 2008-08-06 at 05:50 -0700, Slaunger wrote: > Hi, > > I am new here and relatively new to Python, so be gentle: > > Is there a recommended generic implementation of __repr__ for objects > equal by value to assure that eval(repr(x)) == x independet of which > module the call is made from? > > Example: > > class Age: > > def __init__(self, an_age): > self.age = an_age > > def __eq__(self, obj): > self.age == obj.age > > def __repr__(self): > return self.__class__.__name__ + \ > "(%r)" % self.age > > age_ten = Age(10) > print repr(age_ten) > print eval(repr(age_ten)) > print eval(repr(age_ten)).age > > Running this gives > > Age(10) > Age(10) > 10 > > Exactly as I want to. > > The problem arises when the Age class is iomported into another module > in another package as then there is a package prefix and the above > implementation of __repr__ does not work. > > I have then experimented with doing somthing like > > def __repr__(self): > return self.__module__ + '.' + self.__class__.__name__ + > "(%r)" % self.age > > This seems to work when called from the outside, but not from the > inside of the module. That is, if I rerun the script above the the > module name prefixed to the representation I get the following error > > Traceback (most recent call last): > File "valuetest.py", line 15, in > print eval(repr(age_ten)) > __main__.Age(10) > File "", line 1, in > NameError: name '__main__' is not defined > > This is pretty annoying. > > My question is: Is there a robust generic type of implementation of > __repr__ which I can use instead? > > This is something I plan to reuse for many different Value classes, so > I would like to get it robust. > > Thanks, > Slaunger > -- > http://mail.python.org/mailman/listinfo/python-list Are you really sure this is what you want to do, and that a less tricky serialization format such as that provided by the pickle module wouldn't work for you? -- John Krukoff Land Title Guarantee Company From rafesacks at gmail.com Tue Aug 19 13:31:06 2008 From: rafesacks at gmail.com (Rafe) Date: Tue, 19 Aug 2008 10:31:06 -0700 (PDT) Subject: exception handling in complex Python programs References: Message-ID: On Aug 20, 12:19 am, eliben wrote: > Python provides a quite good and feature-complete exception handling > mechanism for its programmers. This is good. But exceptions, like any > complex construct, are difficult to use correctly, especially as > programs get large. > > Most of the issues of exceptions are not specific to Python, but I > sometimes feel that Python makes them more acute because of the free-n- > easy manner in which it employs exceptions for its own uses and allows > users to do the same. > > Now, what do I mean more specifically... When a program starts growing > large, I find myself a bit scared of all the exceptions that might be > thrown: Python's exceptions as a result of runtime-detection of errors > (Python's dynamic typing also comes into play here), exceptions from > libraries used by the code, and exceptions from my lower-level > classes. > Python doesn't allow to specify which exceptions are thrown (C++'s > feature adding 'throw' after a function/method declaration specifying > the exceptions that can be thrown), and this leaves me at loss - what > should be caught and where ? Which errors should be left to > propagate ? > > I've tried looking around the Python blogosphere, but there doesn't > seem to be much concern with this topic. > > Apologies for the not-too-coherent post, but I suspect you feel the > pain too and can understand my meaning. > > Eli > > P.S. There's a common case where a method is passed a filename, to do > something with a file (say, read data). Should the method catch the > errors possibly thrown by open(), or leave it to the caller ? > > P.P.S. There's a great post on conditions (Common Lisp's exceptions) > here:http://dlweinreb.wordpress.com/2008/03/24/what-conditions-exceptions-... > Not really CL specific, and can apply to Python's exceptions. Maybe I am oversimplifying (and I am here to learn), but I catch all exceptions which otherwise would be hard to understand as a user. In other words, when a better error message is useful. Again, this is probably too simple to help, but the only way to ignore certain types of exceptions, as far as I know, is to catch them and pass. e.g. this ignores type errors... try: somethingBad() except TypeError, err: pass except Exception, err: raise TypeError(err) I suppose you could write a decorator to do this if you want it at the function level, but that seems a bit to broad. Shouldn't exceptions be on a case-by-case basis to add protection and return information exactly where it is needed? - Rafe From steve at REMOVE-THIS-cybersource.com.au Mon Aug 4 19:12:49 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2008 23:12:49 GMT Subject: Check if module is installed References: <813a0a6f-2f4d-482a-a3c4-5664798c5c26@f63g2000hsf.googlegroups.com> Message-ID: <00a7883e$0$20302$c3e8da3@news.astraweb.com> On Mon, 04 Aug 2008 05:25:08 -0700, Kless wrote: > How to check is a library/module is installed on the system? I use the > next code but it's possivle that there is a best way. > > ------------------- > try: > import foo > foo_loaded = True > except ImportError: > foo_loaded = False > ------------------- The "best" way depends on what you expect to do if the module can't be imported. What's the purpose of foo_loaded? If you want to know whether foo exists, then you can do this: try: foo except NameError: print "foo doesn't exist" Alternatively: try: import foo except ImportError: foo = None x = "something" if foo: y = foo.function(x) If the module is required, and you can't do without it, then just fail gracefully when it's not available: import foo # fails gracefully with a traceback Since you can't continue without foo, you might as well not even try. If you need something more complicated: try: import foo except ImportError: log(module not found) print "FAIL!!!" sys.exit(1) # any other exception is an unexpected error and # will fail with a traceback Here's a related technique: try: from module import parrot # fast version except ImportError: # fallback to slow version def parrot(s='pining for the fjords'): return "It's not dead, it's %s." % s -- Steven From gminick at nie.ma.takiego.adresu.w.sieci.pl Tue Aug 12 04:45:07 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Tue, 12 Aug 2008 08:45:07 +0000 (UTC) Subject: Looking out a module for Subversion References: Message-ID: Dnia Tue, 12 Aug 2008 04:25:50 -0400, Dudeja, Rajat napisa?(a): > Hi, > > I'm new to Python. I only have read "Byte of Python" by Swaroop C H just > to be familiar with sytax of python. I've installed Python 2.5 from > Active State and using its PythonWin Editor / interpreter. This, > unfortunaltely, does not help in debugging. > > I'm looking for an open source IDE / editor that has source level > debugging. Please suggest some tool. > > I'm intending to write a testing tool that uses Subversion. Is there > some module available for subversion, out of the box, that I can import > in my script? There is no such module in standard library, but you can try an external one. Check: http://pysvn.tigris.org/ -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From williamhpurcell at gmail.com Tue Aug 12 13:46:31 2008 From: williamhpurcell at gmail.com (William Purcell) Date: Tue, 12 Aug 2008 12:46:31 -0500 Subject: Checking a file's time stamp. Message-ID: Hi all, I am wanting to check to see the last time a file was edited. For example, I have a directory containing two text files, file1.txt and file2.txt. I want to be able to process these files but only if they have been edited since the last time they were processed. I think that I want to be able to check the time stamp of each file. Can anyone tell me how to do that or point me in a better direction of checking the last time a file was edited? Thanks, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Aug 22 00:56:44 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 21 Aug 2008 21:56:44 -0700 (PDT) Subject: Address-Of operator equivalent, PAVL search tree References: <82007443-29e3-47ae-8928-554b4170947b@z72g2000hsb.googlegroups.com> Message-ID: <3857fcf8-120a-4577-a017-967fadb14f36@m73g2000hsh.googlegroups.com> On Aug 21, 11:03?pm, castironpi wrote: > Hi, > > I am translating the GNU library's PAVL search tree implementation > into Python. ?I can't use it directly because a delete function I need > uses a different method of finding the node to delete. > > It contains this line: > > ? ? ? q = (struct pavl_node *) &tree->pavl_root; > > line 276 in http://www.sfr-fresh.com/unix/misc/avl-2.0.3.tar.gz:a/avl-2.0.3/pavl.c It seems the only property that's accessed is q->pavl_link[ 0 ], done in order to generically set the tree's root along with other nodes. I will use a proxy class to reroute set operations on q.link[ 0 ] to tree.root. It is also accessible via q.left. Here is a tentative implementation: class RootProxy: __slots__= '_tree' class RootLink: __slots__= '_tree' def __init__( self, tree ): self._tree= tree def __getitem__( self, key ): assert key== 0 return self._tree.root def __setitem__( self, key, val ): assert key== 0 self._tree.root= val def __init__( self, tree ): self._tree= tree def _getleft( self ): return self._tree.root def _setleft( self, val ): self._tree.root= val left= property( _getleft, _setleft ) def _getlink( self ): return self.RootLink( self._tree ) link= property( _getlink ) The line then becomes: > q = (struct pavl_node *) &tree->pavl_root; q= RootProxy( tree ) Thanks for your attention. Any questions or comments please share. From fredrik at pythonware.com Mon Aug 18 04:51:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 18 Aug 2008 10:51:25 +0200 Subject: Bizarre method keyword-arg bug. In-Reply-To: References: Message-ID: Jasper wrote: > I'm stumped. I'm calling a method that has keyword args, but not > setting them, and yet one of them starts off with data?! > > The class definition begins like so: > > class BattleIntentionAction( BattleAction ): > def __init__( self, factionName, location, tactic='hold', > targetFacName='', terrainArgs=[], garrisonIds=[] ): > self.terrainArgs = terrainArgs > print terrainArgs > > The constructor is called somewhere else, like so: > act = BattleIntentionAction( facName, self.location ) > > During this object's construction, terrainArgs is set to a list with > values corresponding to a previously created BattleIntentionAction! default argument values are evaluated when the function object is created (by the "def" statement, that is), not when the resulting function is called. if you mutate the default values, the mutations will stick. this is explained in the FAQ, the tutorial, and the reference manual, and hopefully in your favourite python book as well; see e.g. http://docs.python.org/tut/node6.html#SECTION006710000000000000000 http://docs.python.org/ref/function.html From Lie.1296 at gmail.com Sat Aug 30 13:01:12 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 30 Aug 2008 10:01:12 -0700 (PDT) Subject: Which is faster? References: Message-ID: On Aug 30, 5:30?pm, cnb wrote: > how does doing something twice not change complexity? yes it maybe > belongs to the same complexity-class but is still twice as slow no? Who is doing something twice? Definitely not sum(). sum() does not create intermediate list, and if you pass generator expressions in it you wouldn't make any intermediate list at all, thus simple looping but in interpreter code. sum() that is passed a list comprehension should be faster for extremely small numbers of values to sum, but we don't care about small things, do we? But using intermediate list should be fast enough for even large numbers of values, the time when it can't cope anymore would be when the intermediate list takes half of your memory (how often is that for regular applications?). From slfdsasdssaf at spam.not Wed Aug 27 21:51:52 2008 From: slfdsasdssaf at spam.not (RgeeK) Date: Wed, 27 Aug 2008 21:51:52 -0400 Subject: Global var access in imported modules? In-Reply-To: References: <48b5b72f$1@news.alcatel.com> Message-ID: Dennis Lee Bieber wrote: > On Wed, 27 Aug 2008 16:21:03 -0400, RgeeK > declaimed the following in comp.lang.python: > >> I have a main module doStuff.py and another module utility.py. At the >> start of doStuff.py I call >> >> import utility.py > > I hope not... import utility no .py >> Then I also proceed to initiallize some global variables >> > Python does not have global variables. Names belong within a module > (or within functions defined within the module). > >> sName = "" >> >> Then I create a class, some methods etc. In one of the methods I assign >> a value to my variable sName. Then I call a function from within >> my utility.py file: >> >> utility.makeOne(stuff) >> >> >> Within my utility.py file, I define the makeOne function. But I want to >> use that same global variable "sName" In utility.py I have tried to >> indicate that I'm using the global "sName" through the statement: >> >> global sName >> > The global statement is only used within functions (def blocks) to > indicate that "writes" to the specified name are to modify the MODULE > level version of the name, otherwise a write modifies a function local > version of the name (you don't need global for read-only access of > names, the search for names first looks inside the function, then out to > the module) > >> But when I go to use the variable it still gives me an error: >> >> NameError: global name 'sName' is not defined >> >> I thought perhaps I need to indicate 'globality' in my main module, so >> before I initiallized sName in doStuff.py I added: >> >> global sName >> >> But it doesn't help me. I had this issue before and resolved it by >> declaring the variable global in the sub-module utility.py, but then I >> needed to reference it in my main module with a prefix: >> >> utility.sName = "" >> >> It's more verbose,and defining globals in a submodule seems backward. >> But also, what if I need to access "sName" in another imported module, >> say "otherstuff.py"? I would do my "import otherstuff" call in my main >> module, but would I have to put an "import utility" into the >> otherstuff.py file? >> > If you really need "globals" the common solution is to create a > module such as "myglobals", define all the shared names within that > module, and import that module where ever you need access to one of the > names. And yes, you will need to qualify all those names with the module > name (though you can do things like: > > import myglobals as mg > > and then use > > mg.somename > > instead of > > myglobals.somename) > Thanks for the reply. Good to see that approach has broad support :) I'll do that. I like the idea of a nice short alias for the import to keep the qualifications brief. Ross. From grante at visi.com Fri Aug 15 11:10:41 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 15 Aug 2008 10:10:41 -0500 Subject: How do I control output buffering on Win32? References: <1I-dndTLBfGbCjjVnZ2dnUVZ_hCdnZ2d@posted.visi> Message-ID: On 2008-08-15, Fredrik Lundh wrote: > Grant Edwards wrote: > >> When I ssh in to my Windows XP box and run Python apps, output >> from "print" and and "sys.stdout.write()" is being buffered so >> that none of the output shows up until the program exits. >> >>>From within my program how do I set output buffering to either >> line-buffered or un-buffered? [I'm looking for the equivalent >> of the C stdio "setbuf" call.] > > I'm not sure you can do that from within the program [1]; to > do it from the outside, set the PYTHONUNBUFFERED environment > variable to something, or pass "-u" to the interpreter. I had seen references to PYTHONUNBUFFERED in my Google search, but it wasn't mentioned when I did a "python -h" -- so I assumed it was a Unix-only thing. > 1) well, I suppose you could replace sys.stdout with a thin > wrapper that does flush after each write, or play with > os.fdopen. I thought about that, but it seemed like there ought to be an easier, more obvious way. Is there some technical reason a Python program can't control the output buffering the way a C program can with setvbuf()? Or is it just something that's only wanted by weird people who do things like ssh into Windows boxes? That raises another question: what is the criteria that Python is using when it decides to run my program in block-buffered mode instead of line- or un-buffered mode? -- Grant Edwards grante Yow! I've read SEVEN at MILLION books!! visi.com From michaelmackus at gmail.com Sat Aug 16 03:40:27 2008 From: michaelmackus at gmail.com (Sonolin) Date: Sat, 16 Aug 2008 00:40:27 -0700 (PDT) Subject: You advice please References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> Message-ID: <1c03fef3-3abd-4369-962f-3773652fc785@z11g2000prl.googlegroups.com> On Aug 13, 4:14?am, Hussein B wrote: > Hey, > I'm a Java/Java EE developer and I'm playing with Python these days. > I like the Python language so much and I like its communities and the > Django framework. > My friends are about to open a Ruby/Rails shop and they are asking me > to join them. > I don't know what, sure I'm not leaving Java, but they are asking me > to stop learning Python and concentrate on Ruby/Rails. > The sad fact (at least to me), Ruby is getting a lot of attention > these days. > Why Python isn't getting this attention although is a much more mature > language and it is used by many big, big names? > And do I dare to say it is much more charming? > What do you think of Ruby/Rails? do they worth learning and working > with? > Any way, I'm not leaving Python and I will try to study it every time > I get a chance... > Thanks. Generally when developing something these days (Web App or not) I have found that the programming language really does not have a huge affect on the success of the product. If the developers are dedicated, they can generally make most programming languages work. It just comes down to what you prefer, or if something clearly is better than the others use it if at all possible. For example, when programming a game, you could easily code it in Python, or C++. Sure, C++ would be faster, but sometimes these days speed is not a large factor. And you can always just code the complex calculations in C, and the rest in Python. So, in short, if you are up to the challenge - take it. I do not know Ruby (at ALL), but if some of my friends wanted to develop a RoR app I would not turn them down for the language choice (Ruby). There has been successful Web Apps made in Ruby, Python, PHP, Perl, Java, etc. - they all have their place. I would much rather code in Python than in PHP, but most of my Web Programming is done in PHP due to client preference. And as for being afraid of "abandoning" Python... I know many programming languages, and have not abandoned my favorites. Just because I know how to code in Visual Basic does not mean I do regularly. Hopefully this made some sense - pretty tired ;) -- http://designandprogram.com http://twitter.com/sonolin From deets at nospam.web.de Sun Aug 31 03:41:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 31 Aug 2008 09:41:30 +0200 Subject: Mako --> Genshi In-Reply-To: <20080830205904.725f1bef@mail.asciiking.com> References: <20080830205904.725f1bef@mail.asciiking.com> Message-ID: <6hv09bFnvm0eU1@mid.uni-berlin.de> Chris Babcock schrieb: > Is there a cheap way to convert Myghty/Mako templates to Kid/Genshi? > There's some code written for Pylons that I want to incorporate into a > TurboGears 2 project and Genshi templates are more likely to behave > themselves with the tools I'm used to. Not that I'm aware of. And I think it's impossible to reliably do that, because mako allows broken XML or "pure" HTML, whereas KID/Genshi require well-formed XML. Diez From jeffober at gmail.com Mon Aug 4 12:45:20 2008 From: jeffober at gmail.com (Jeff) Date: Mon, 4 Aug 2008 09:45:20 -0700 (PDT) Subject: Bidirectional Generators References: <8e2cf6b7-4b5f-4701-8a4c-bc779ed7305c@m45g2000hsb.googlegroups.com> <976df308-3855-4f2b-a82a-dacba480e7d7@i76g2000hsf.googlegroups.com> <4f1ac687-2401-4ee7-acd9-b0eb3ef8e910@v39g2000pro.googlegroups.com> Message-ID: <914d16b4-efee-45cc-9751-b8156bdd943f@w7g2000hsa.googlegroups.com> On Aug 4, 12:39?pm, william tanksley wrote: > Paddy wrote: > > What's one of them then? > > I'm sorry, I don't know what you mean. > > Meanwhile, more pertinently: I did get my generator working, and then > I replaced it with a class that did the same thing in less than a > quarter of the number of lines. So... I'm not going to worry about > that anymore. My use case obviously wasn't the right one for them. > > I'm still curious, though, whether anyone's written any code that > actually uses yield _and_ send() to do anything that isn't in the > original PEP. > > > - Paddy. > > -Wm I have. An iterator that could backtrack itself without the user having to remember previous states. It would just send back something like reader.send('prev_token') or reader.send(-1). From jonas.esp at googlemail.com Sun Aug 3 04:12:18 2008 From: jonas.esp at googlemail.com (Kless) Date: Sun, 3 Aug 2008 01:12:18 -0700 (PDT) Subject: base-96 References: <094aaf8f-0d16-4f85-abd5-232f475b9785@x35g2000hsb.googlegroups.com> Message-ID: On 3 ago, 00:33, Terry Reedy wrote: > seehttp://en.wikipedia.org/wiki/Base-85 > for something more practical In this thread [1] --a mirror group of python-dev mailing list-- where I sent the same post, has been named too that enconding way. [1] http://groups.google.com/group/python-dev2/browse_thread/thread/c843ecf222948167 From claird at lairds.us Fri Aug 29 07:44:41 2008 From: claird at lairds.us (Cameron Laird) Date: Fri, 29 Aug 2008 11:44:41 +0000 Subject: Python in a Nutshell -- Book vs Web References: Message-ID: <924lo5-9u7.ln1@lairds.us> In article , Fredrik Lundh wrote: >Cameron Laird wrote: > >> No. No, to an almost libelous extent. > >No matter what you write about, there's always a certain subcategory of >potential readers who insist that collection, editing, filtering, >structuring, clarification, and the author's real-life experience of the >topic he's writing about has no value at all. My guess is that they >don't value their own time very highly. > > > Insightful. Well, I find it insightful; perhaps it's a personal blindness on my part. I expect programmers to understand, for example, that two lines of code can be a good day's production, in some circumstances, while it's "civilians" and managers who scorn their value on quantitative grounds. It's hard for me to conceive of an expert programmer who doesn't esteem what a high-quality book provides. From bidihall at gmail.com Fri Aug 29 18:44:32 2008 From: bidihall at gmail.com (BiDi) Date: Fri, 29 Aug 2008 15:44:32 -0700 (PDT) Subject: subclassing complex References: <3ce33299-e13c-4ce0-8a09-eab6d0359033@a3g2000prm.googlegroups.com> <0b908015-59c2-4dc9-a279-e42ce920fe03@d45g2000hsc.googlegroups.com> Message-ID: On Aug 30, 6:18?am, Patrick Maupin wrote: > On Aug 29, 4:24 am, Peter Otten <__pete... at web.de> wrote: > > > > > A minimal example is > > > >>> class Complex(complex): > > > ... ? ? def __radd__(self, other): print "radd" > > ...>>> 1j + Complex() > > > 1j > > > versus > > > >>> class Int(int): > > > ... ? ? def __radd__(self, other): print "radd" > > ...>>> 1 + Int() > > > radd > > > I think the complex subclass should behave like the int subclass. > > To get an authoritative answer you should file a bug report. > > Hmm, good point. ?I shouldn't look at newsgroups when I'm too tired to > see the whole problem. > > According to the documentation athttp://docs.python.org/ref/numeric-types.html: > > "Note: If the right operand's type is a subclass of the left operand's > type and that subclass provides the reflected method for the > operation, this method will be called before the left operand's non- > reflected method. This behavior allows subclasses to override their > ancestors' operations." > > I think this makes it pretty clear that the OP found a bug in how > complex works. ?(Before I read this note, I would have assumed that > the int() handling was broken, but it looks like a supportable design > decision. ?Probably whoever implemented it wasn't even thinking about > complex numbers, but for consistency, I would think they should be > made to work the same.) > > Regards, > Pat Thanks for the comments. I have filed it as an issue. Regards Blair From lee.walczak at gmail.com Mon Aug 18 08:47:39 2008 From: lee.walczak at gmail.com (lee.walczak at gmail.com) Date: Mon, 18 Aug 2008 05:47:39 -0700 (PDT) Subject: configuring temporary entry widget of TableList Cell using Python Message-ID: Hi, I am using Tkinter & the Kevin Walzer's TableList Wrapper for python implemented GUI: http://tkinter.unpythonic.net/wiki/TableListWrapper The TableList has been extremely useful in allowing me to create my GUI for my engineering requirements, but I have hit a brick wall and need some assistance. "I am unable to configure the Temporary Embedded ComboBox List when the specific TableList cell is selected for editing" I have a registered the Bwidget Combobox widget so I can use this as an alternative temporary Entry Widget ( depending on the specific cell usage) thanks to some assistance from Kevin Walzer ( Many thanks ). I configure the particular cell's edit window (-editwindow ) for ComboBox which is working successfully. The problem I have is I wish to change the "-values" of the Temporary Combobox Widget i.e. a List that I can specify. When my "-editstartcommand" is called I firstly get the pathname of the Temporary Embedded Widget using, TEW = editwinpath() I am then assuming (although I must be wrong!) that I can then do: TEW.configure( values=("my","list","of","Strings")) However, this leads to the exception error -> TEW does not contain such an attribute "configure". My reference for this procedure is (http://objectmix.com/tcl/377931- communicating-tablelist-embedded-widgets.html but also available from tcl.tk tablelist coding examples) : proc editStartCmd {tbl row col text} { set w [$tbl editwinpath] switch [$tbl columncget $col -name] { currency { # # Populate the ComboBox and make it non-editable # $w configure -values {Dollar Euro Yen ...} -editable no } . . . } return $text } It is this procedure I am trying to replicate in Python. Is it possible to guide help tell me the right approach here. Of course I can submit my code to help ( if this is useful ) but the problem I think clear to see from these summary details. Please take it easy on me, I am a HW engineer by trade and am slowly (but surely) gaining more knowledge & experience in the world of Python (and of course Tkinter)! B.Regards, Lee Walczak From h.goebel at goebel-consult.de Wed Aug 27 14:05:00 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Wed, 27 Aug 2008 20:05:00 +0200 Subject: Split function for host:port in standard lib In-Reply-To: <7nado5-0a4.ln1@nb2.stroeder.com> References: <7nado5-0a4.ln1@nb2.stroeder.com> Message-ID: <48b5974c$0$11749$9b4e6d93@newsspool1.arcor-online.net> Michael Str?der schrieb: > Examples IPv6 addresses: > '::1:389' -> ('::1',389) > '::1' -> ('::1',None) These are wrong, see http://tools.ietf.org/html/rfc2732 ("Format for Literal IPv6 Addresses in URL's?). Correct formats are: [::1]:389 [::1] From emile at fenx.com Thu Aug 7 18:43:50 2008 From: emile at fenx.com (Emile van Sebille) Date: Thu, 07 Aug 2008 15:43:50 -0700 Subject: Fastest way to store ints and floats on disk In-Reply-To: <489B41CE.8080909@shopzeus.com> References: <489B41CE.8080909@shopzeus.com> Message-ID: Laszlo Nagy wrote: > > Hi, > > I'm working on a pivot table. Hmm... I wrote an browser based analysis tool and used the working name pyvot... I found Numeric to provide the best balance of memory footprint and speed. I also segregated data prep into a separate process to avoid excessive memory use at run time. Turns out python For the site I'm at, I've got 10 years sales history recapped from 4327846 detail records into 458197 item by customer by month records and top shows a 240Mb memory footprint. I've got 21 cross indexed selection fields, and can display up to six data types (qty, price, sqft, cost, gp%, avg). At another site I've got approx 8.5M records recapped into 1M records with 15 indexes and 5 years monthly history living in a 540Mb memory footprint. It's reasonably quick: a query like 'select san mateo, foster city and san carlos accounts, sort by customer and product category and display this year's sales by month' selects 260 records and renders in the browser in about 2 seconds. Or on the larger installation 'Show sales for the past five years for product group 12 sorted by city within route' selects 160 records and renders in about 3 seconds. My objective was to keep the info in memory for fast response times. I played a lot of games getting this all to work well, including some c extensions, but Numeric's take, sum, tostring and fromstring ended up with 'pivotal' roles. :) Regards, Emile > I would like to write it in Python. I > know, I should be doing that in C, but I would like to create a cross > platform version which can deal with smaller databases (not more than a > million facts). > > The data is first imported from a csv file: the user selects which > columns contain dimension and measure data (and which columns to > ignore). In the next step I would like to build up a database that is > efficient enough to be used for making pivot tables. Here is my idea for > the database: > > Original CSV file with column header and values: > > "Color","Year","Make","Price","VMax" > Yellow,2000,Ferrari,100000,254 > Blue,2003,Volvo,50000,210 > > Using the GUI, it is converted to this: > > dimensions = [ > { 'name':'Color', 'colindex:0, 'values':[ 'Red', 'Blue', 'Green', > 'Yellow' ], }, > { 'name':'Year', colindex:1, 'values':[ > 1995,1999,2000,2001,2002,2003,2007 ], }, > { 'name':'Make', colindex:2, 'value':[ 'Ferrari', 'Volvo', 'Ford', > 'Lamborgini' ], }, > ] > measures = [ > { 'name', 'Price', 'colindex':3 }, > { 'name', 'Vmax', 'colindex':4 }, > ] > facts = [ > ( (3,2,0),(100000.0,254.0) ), # ( dimension_value_indexes, > measure_values ) > ( (1,5,1),(50000.0,210.0) ), > .... # Some million rows or less > ] > > > The core of the idea is that, when using a relatively small number of > possible values for each dimension, the facts table becomes > significantly smaller and easier to process. (Processing the facts would > be: iterate over facts, filter out some of them, create statistical > values of the measures, grouped by dimensions.) > > The facts table cannot be kept in memory because it is too big. I need > to store it on disk, be able to read incrementally, and make statistics. > In most cases, the "statistic" will be simple sum of the measures, and > counting the number of facts affected. To be effective, reading the > facts from disk should not involve complex conversions. For this reason, > storing in CSV or XML or any textual format would be bad. I'm thinking > about a binary format, but how can I interface that with Python? > > I already looked at: > > - xdrlib, which throws me DeprecationWarning when I store some integers > - struct which uses format string for each read operation, I'm concerned > about its speed > > What else can I use? > > Thanks, > > Laszlo > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From gminick at bzt.bzt Thu Aug 14 17:31:42 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Thu, 14 Aug 2008 21:31:42 +0000 (UTC) Subject: negative numbers are not equal... References: <48A4932F.4010302@gmail.com> Message-ID: On Thu, 14 Aug 2008 18:23:21 -0300, ariel ledesma wrote: > i see now, so i guess that's also why id() returns the same address for > them as well... It just have to work like this. a is b is actually equal to: id(a) == id(b) so there is no other way for id() in such case. Hope this helps. -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From larry.bates at websafe.com` Wed Aug 13 17:07:52 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 13 Aug 2008 16:07:52 -0500 Subject: callbacks in python In-Reply-To: <2b3a25c6-9985-4d05-8721-5a57a020e845@w7g2000hsa.googlegroups.com> References: <2b3a25c6-9985-4d05-8721-5a57a020e845@w7g2000hsa.googlegroups.com> Message-ID: Alexandru Mosoi wrote: > does anyone know a nice implementation of callbacks in python? i have > issues mixing named & unamed parameters. i want build a callback over > a function such that some parameters are passed when callback is > created and the rest are passed when the function is called. > > example: > callback = Callback(function, x=1, y) > callback(z, t=4, u) First problem is that all unnamed arguments must come BEFORE named ones (Python limitation). To do what you want define you callback as a class instead. class Callback(object): def __init__(x, y): self.x = x self.y = y def __call__(z, t, u): # # Do what you want done at every callback # callback = Callback(x, y) callback(z, t, u) -Larry From rowen at u.washington.edu Thu Aug 14 12:20:11 2008 From: rowen at u.washington.edu (Russell E. Owen) Date: Thu, 14 Aug 2008 09:20:11 -0700 Subject: ActiveState Python v2.5 doesn't come with Tkinter or Tk installed. References: Message-ID: In article , "Dudeja, Rajat" wrote: > Hi, > > So, now I've finally started using Eclipse and PyDev as an IDE for my > GUI Application. I just wrote some sample programs as an hands on. > > Now I would like to take up Tkinter. I'm using Active State Python > version 2.5 and found that there is not Tkinter and Tk module in it. > > To use Tkinter do I actually require Tk installed on my machine? Please > suggest and where can I find both these modules? > > Also, please direct me to a good and short document on using Tkinter or > Tk in Python. What operating system? For MacOS X this should not happen because Tcl/Tk is already available. But the best Python for MacOS X is the binary installer from python.org and the best Tcl/Tk is ActiveState version 8.4.19 (the Tcl/Tk that comes with MacOS X 10.4 and 10.5 is rather old and buggy). For Windows: the standard python.org binary Python includes its own Tcl/Tk. So the simplest solution is to use that. I know nothing about ActiveState's Python for Windows but it is possible that it requires ActiveState Tcl/Tk to use Tkinter. For unix: I'm not sure about ActiveState and unix. But the standard package installer that comes with your unix should offer tcl/tk, python and _tkinter (possibly as 3 separate packages, possibly not) and at least tcl/tk and python should be installed by default. In general ActiveState puts out a very nice Tcl/Tk installer that includes many useful extra packages. But I've never seen the point to ActiveState's Python installer. When I last tried it, their Python was missing readline and did not add any useful packages to the standard python.org version. For info on Tkinter: -- Russell P.S. if you do install Tcl/Tk to use with Tkinter, please use 8.4.x, NOT 8.5. Python 2.5.x is not fully compatible with Tcl/Tk 8.5. From brennan.ron at gmail.com Thu Aug 28 13:02:55 2008 From: brennan.ron at gmail.com (Ron Brennan) Date: Thu, 28 Aug 2008 13:02:55 -0400 Subject: Multiple values for one key In-Reply-To: <48b6ca75$0$5088$426a74cc@news.free.fr> References: <26c69b160808271326w2f53b6b8s6e4aa7f91071ac71@mail.gmail.com> <48b6ca75$0$5088$426a74cc@news.free.fr> Message-ID: <26c69b160808281002l262e4824y60b8d3cb3369ee91@mail.gmail.com> I have another question. How would like to be able to add the contents on the values for one key. key['20001']:[978, 345] How can I do this? Thanks, Ron On Thu, Aug 28, 2008 at 11:56 AM, Bruno Desthuilliers wrote: > norseman a ?crit : > >> Terry Reedy wrote: >> >>> >>> >>> Ron Brennan wrote: >>> >>>> Hello, >>>> How would I create a dictionary that contains multiple values for one >>>> key. >>>> >>> >>> Make the value a collection object (set or list if you plan to add and >>> delete). >>> >>> I'd also like the key to be able to have duplicate entries. >>>> >>> >>> Dict keys must be hashable and unique. >>> >>> tjr >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> ================ >> First part I understand, second is still giving me a problem. >> >> For some reason I still want keys to be dbf column headers. >> like: >> >> name:address:zip so forth >> ---- ------- --- ------------------ >> guy: unknown:00000 >> girl: 123 tiny street:12345 >> boy:321 here:33333 >> gal:999 over there: 55555 >> so forth >> >> Thus one key has many values. And you can then index on whatever key(s) >> you wish - name,zip... >> > > You can either use 1/ a list of dicts, or 2/ a dict mapping keys to lists. > > 1/ > records = [ > {"name":"guy", "address":"unknown","zip":"00000"}, > {"name":"girl", "address":"123 tiny street","zip":"12345"}, > {"name":"boy", "address":"321 here","zip":"33333"}, > {"name":"gal", "address":"999 over there","zip":"55555"}, > ] > > keys = ("name", "address", "zip") > > print ":".join(keys) > print "-" * len(":".join(keys)) > for record in records: > data = [record[key] for key in keys] > print ":".join(data) > > > 2/ > records = dict( > name=["guy", "girl", "boy", "gal"], > address=["unknown","123 tiny street","321 there","999 over there"], > zip=["00000", "12345", "33333", "55555"] > ) > > keys = ("name", "address", "zip") > nb_records = len(records[keys[0]]) > > print ":".join(keys) > print "-" * len(":".join(keys)) > for i in xrange(nb_records): > data = [data[key][i] for key in keys] > print ":".join(data) > > > You are of course entitled the right to prefer the second solution, but > then I hope I'll never have to maintain your code, since it's obviously not > an appropriate data structure. > > With billions plus records, >> > > With billions plus records, it may be time to move to a serious RDBMS. > Which btw will provide solution 1, or a lighter version of it using a list > of tuples, ie: > > cursor = connection.cursor() > cursor.execute("select name, address, zip from peoples") > records = cursor.fetchall() > > # at this time, you have : > #records = [ > # ("guy", "unknown","00000",), > # ("girl", "123 tiny street","12345",), > # ("boy", "321 here","33333",), > # ("gal", "999 over there", "55555",), > #] > > > (snip) > > OK - I know I missed the whole concept of a Python Dictionary. >> > > Bad thing for you, since it's the central datastructure in Python. > > I haven't read anything as yet that gives a clear picture of what it is and >> what it is for. >> > > Then you failed to read the FineManual's tutorial, which is where you > should have started: > > http://docs.python.org/tut/node7.html#SECTION007500000000000000000 > > Do yourself a favour : read the above first, then if you still have > questions about dicts, we'll gladly try to help. > > And do yourself another favour : learn about SQL, relational model and > RDBMS. > > (snip description of why the OP *really* wants a RDBMS) > > -- > http://mail.python.org/mailman/listinfo/python-list > -- FYI, my email address is changing. My rogers account will be deactivated shortly. From now on please use: brennan.ron at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rcn.com Sat Aug 30 18:33:36 2008 From: python at rcn.com (Raymond Hettinger) Date: Sat, 30 Aug 2008 15:33:36 -0700 (PDT) Subject: Which is faster? References: Message-ID: <14014a96-78d3-4070-8464-39cfea95f0f5@r15g2000prh.googlegroups.com> On Aug 29, 9:26?pm, cnb wrote: > def av_grade(self): > ? ? ?return sum(review.grade for review in self.reviews) / \ > ? ? ? ? ? ? ? len(self.reviews) Minor point. Consider making the divisor: float(len(self.reviews)). It would be a bummer to throw-off the average because of floor division. Also consider an itertools approach: sum(itertools.imap(operator.itemgetter('review'), self.reviews)) BTW, the sum() in Py2.6 is *much* faster than before. It should run circles around any other approach. As Effbot says, if you really care about speed, then just time both approaches. However, it's a good run of thumb that builtins are hard to beat by simulating them in pure python (unless you're using Psyco as an optimizer). Raymond From frankrentef at yahoo.com Wed Aug 6 15:42:12 2008 From: frankrentef at yahoo.com (frankrentef) Date: Wed, 6 Aug 2008 12:42:12 -0700 (PDT) Subject: Run program from within Python Message-ID: <47eee9f1-c85d-4816-a204-8a11f178267d@d1g2000hsg.googlegroups.com> Greetings all... Newbie to Python... need help with opening a file from within Python... see the following code. import popen2 stdout, stdin = popen2.popen2('c:\test\OpenProgram.exe 1 1') keygen = stdout.read() print "The keygen value is: %s" % keygen from the command line if I execute "OpenProgram.exe 1 1" a number is returned. ("1 1" are required to return the value needed.) Ultimately I want to take that number and apply it to another script, but the program is not running. Suggestions? NEWBIE to Python.. From PaulAlexWilson at gmail.com Tue Aug 12 10:35:08 2008 From: PaulAlexWilson at gmail.com (Wilson) Date: Tue, 12 Aug 2008 07:35:08 -0700 (PDT) Subject: Manipulating Python Source Message-ID: <8257ff71-4f67-405e-ada8-35ba8879ddca@e39g2000hsf.googlegroups.com> Hi, I'm wondering if there are any tools available or simple methods for taking a python source file and parsing into some hierarchical format, like the ConfigParser. I'd like to be able to do something like the following: test.py: ------------------------------------------------------- """ This is an example """ class MyClass(ParentA, ParentB): def some_func(self, foo, bar): self.baz = "batman" class MyClass2(object): """ This is an example class """ def __init__(self): self.a = "Blablabla" And from the interpreter: >>> import magicalParser >>> parsed = magicalParser.parse(test.py) >>> parsed.getClasses() ["MyClass", "MyClass2"] >>> parsed.docString " This is an example " >>> parsed.removeClass("MyClass2") >>> parsed.getClasses() ["MyClass"] >>> parsed.MyClass.getFuncs() ["some_func"] >>> parsed.MyClass.some_func.addParam("baz") >>> parsed.printSource() """ This is an example """ class MyClass(ParentA, ParentB): def some_func(self, foo, bar, baz): self.baz = "batman" >>> exit() Or something that would yield the above effect. Any ideas? Thanks, Paul From deets at nospam.web.de Tue Aug 12 02:49:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 12 Aug 2008 08:49:29 +0200 Subject: File reading across network (windows) In-Reply-To: References: Message-ID: <6gcq3qFehr5kU1@mid.uni-berlin.de> Prof. William Battersea schrieb: > Hello, > > Suppose I have a Vista machine called VISTA and an XP machine called > XP in a workgroup named WORKGROUP. Physically they're connected to a > router and I can see lists of public and shared files on each of them. > How do I address these for IO? > > A search suggested that the form open(r"\\server\folder\folder"), but > I tried many combinations guessing what it wants for that path in my > case (r"\\WORKGROUP\VISTA", "\\VISTA\PUBLIC", etc), and none have > worked so far. You need to create network shares in windows first. Once these are established, *all* programs using file-IO - including python - can access files. Diez From __peter__ at web.de Tue Aug 12 04:56:29 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 12 Aug 2008 10:56:29 +0200 Subject: module import search path strangeness References: <4a15ac45-aef6-458f-91b6-bcaf14e10412@56g2000hsm.googlegroups.com> Message-ID: tow wrote: >>> > I have a python script (part of a django application, if it makes any >> > difference) which is exhibiting the following behaviour: >> >> > import my_module # succeeds >> > imp.find_module("my_module") # fails, raising ImportError >> >> > which is completely baffling me. According to sys.path, both should >> > fail; the directory containing my_module is not in sys.path (though >> > the my_module directory itself is). > The current directory is actually a subdirectory of /home/tow/test/ > my_module, > but ".." is not in sys.path (nor is anything containing "..") In any > Basically, I had thought that import and imp.find_module used exactly > the same > search path, but the above example shows that at least in this > circumstance they > don't; import is picking up additional search paths from somewhere - > what am I missing? Grepping through the django source finds ./trunk/django/core/management/__init__.py: sys.path.append(os.path.join(project_directory, os.pardir)) sys.path could be changed as a side effect of an import, so I ask you to verify (again) that import and imp.find_module() see the same sys.path. assert all(".." not in p for p in sys.path) import my_module assert all(".." not in p for p in sys.path) imp.find_module("my_module") Peter From musiccomposition at gmail.com Fri Aug 1 22:47:42 2008 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 1 Aug 2008 19:47:42 -0700 (PDT) Subject: Class definition attribute order References: Message-ID: <5fb776ae-e3d7-49ec-9ebf-350b9bf9cac1@l42g2000hsc.googlegroups.com> On Aug 1, 6:23?pm, Andrew Lentvorski wrote: > How do I determine the order of definition of class attributes? > > For example, if I have a class > > class Test(object): > ? ? ?y = 11 > ? ? ?x = 22 > > How do I tell that y was defined before x? You wait until Python 3.0 where you can do this sort of thing with metaclasses. > > Thanks, > -a From saluk64007 at gmail.com Sun Aug 10 15:42:27 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sun, 10 Aug 2008 12:42:27 -0700 Subject: Wouldn't it be nice if this worked? In-Reply-To: References: Message-ID: How about: class A: def add(self,x,y): return x+y class B(A): pass print B().add(1, 2) This also works: class A: def add(self, x, y): return x+y class B: pass B.add = A.add.im_func print B().add(1, 2) From notvalid2 at sbcglobal.net Sat Aug 30 13:37:44 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Sat, 30 Aug 2008 10:37:44 -0700 Subject: Date Comparison and Manipulation Functions? In-Reply-To: <_vfuk.36060$co7.14057@nlpi066.nbdc.sbc.com> References: <6cdf0c14-80b6-42c4-8047-8c01fda8b87c@r15g2000prh.googlegroups.com> <9U8tk.19080$cW3.13729@nlpi064.nbdc.sbc.com> <8AVtk.8079$np7.5970@flpi149.ffdc.sbc.com> <4ad1c85c-479c-44e5-ac1b-ca0509d40c42@s20g2000prd.googlegroups.com> <_vfuk.36060$co7.14057@nlpi066.nbdc.sbc.com> Message-ID: The author has updated the Tutorial and added a flex method. From toby at tobiah.org Mon Aug 11 16:46:10 2008 From: toby at tobiah.org (Tobiah) Date: Mon, 11 Aug 2008 13:46:10 -0700 Subject: list question... unique values in all possible unique spots References: <57fcf019-1afd-4c48-b329-42a0ffc4c5ac@x35g2000hsb.googlegroups.com> Message-ID: On Sat, 09 Aug 2008 08:07:26 -0700, Mensanator wrote: > 403291461126605635584000000 I think it's only 4 septillion. Perfectly manageable. ** Posted from http://www.teranews.com ** From cito at online.de Sun Aug 17 09:56:09 2008 From: cito at online.de (Christoph Zwerschke) Date: Sun, 17 Aug 2008 15:56:09 +0200 Subject: Missing exceptions in PEP 3107 In-Reply-To: References: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> <8800beb6-c07b-44af-b9ac-fcb00f35dc3a@f36g2000hsa.googlegroups.com> Message-ID: Terry Reedy wrote: > I would agree... but... > The problem is that code that uses a function hardly cares whether an > exception that replaces the normal return is raised explicitly, by a > syntax operation (and these are not yet completely documented, though > perhaps they should be), or by a function called within the function. I often read that argument that info on thrown exceptions does not matter in Python, but I beg to differ. Just as a simple and well-known example, it is absolutely important to know that the str.index() method throws a ValueError if nothing is found, while the str.find() method should never throw a ValueError. -- Christoph From nytrokiss at gmail.com Wed Aug 27 16:19:20 2008 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 27 Aug 2008 13:19:20 -0700 Subject: Books about Python. In-Reply-To: <48b5a19a$0$10445$426a74cc@news.free.fr> References: <7acfbe5e-ccb7-4fcf-b775-4ff65ff6281d@i76g2000hsf.googlegroups.com> <48b5a19a$0$10445$426a74cc@news.free.fr> Message-ID: <8a6b8e350808271319g4542502bt4aeba2ed751cc9be@mail.gmail.com> I really liked Core python programming 2nd edition On Wed, Aug 27, 2008 at 9:49 AM, Bruno Desthuilliers wrote: > cscorley at gmail.com a ?crit : >> >> I'm up to write a 20-30 research paper for my computer science course, >> and I was considering choosing to do mine on Python. I was curious if >> anybody knows of any good books about python they could recommend that >> have more of a technical view rather than a Teach-yourself-in-24-hours >> type. > > May I recommand the fine manual and this newsgroup ? > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 13 08:34:15 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 13 Aug 2008 14:34:15 +0200 Subject: __getattr__, __setattr__ and pickle In-Reply-To: References: <48a1cdce$0$14748$426a74cc@news.free.fr> <48a21029$0$15610$426a74cc@news.free.fr> Message-ID: <48a2d4bb$0$9737$426a74cc@news.free.fr> mwojc a ?crit : > Bruno Desthuilliers wrote: > >> >>> class Prop(object): >> ... @apply >> ... def prop(): >> ... def fget(self): return self._prop >> ... def fset(self, val): self._prop = val >> ... return property(**locals()) >> ... def __init__(self, val): self.prop=val >> ... >> >>> class Hook(object): >> ... def __getattr__(self, name): >> ... if name == 'prop': >> ... return self._prop >> ... raise AttributeError("yadda") >> ... def __setattr__(self, name, val): >> ... if name == 'prop': >> ... self.__dict__['_prop'] = val >> ... else: >> ... # XXX : INCORRECT IMPLEMENTATION, DONT DO THIS ! >> ... self.__dict__[name] = val >> ... # correct implementation: >> ... # super(Hook, self).__setattr__(name, value) >> ... def __init__(self, val): self.prop=val > > Hi! > Finally i ended up with all the suggestions you gave me. The speed is > important to me besause i get/set my attribute a lot... The only doubts i > have are with the @apply decorator, because 'apply' seems to be depreciated > since python 2.3... As far as I can tell, it should stay until Python 3.0. But you don't have to write your properties that way anyway - it's just something I personnaly find to be a convenient shortcut, period. FWIW, the above code is just a copy/paste from an interactive session, not an example of "clean" Python coding. > And another thing: why writing for all > attributes 'self.__dict__[name] = val' in __setattr__ is incorrect? Because __setattr__ is *always* called. With your above solution, read/write properties setters won't be called. Python 2.5.1 (r251:54863, Mar 7 2008, 03:41:45) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo(object): @apply def bar(): def fget(self): print "bar get" return self._bar def fset(self, val): print "bar set" self._bar = val def __getattr__(self, name): print "__getattr__", name if name == 'baaz': return self._baaz raise AttributeError("yadda") def __setattr__(self, name, val): print "__setattr__", name self.__dict__[name] = val >>> foo = Foo('bar', 'baaz') __setattr__ bar __setattr__ baaz >>> foo.baaz 'baaz' >>> foo.bar 'bar' >>> foo.__dict__ {'baaz': 'baaz', 'bar': 'bar'} From deets at nospam.web.de Mon Aug 25 19:15:46 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Aug 2008 01:15:46 +0200 Subject: swig or ctypes , under the gun and need help In-Reply-To: References: Message-ID: <6hgsp2FlnrehU1@mid.uni-berlin.de> Sells, Fred schrieb: > Diez wrote... >> I don't know swig, but if all you have is a real C-API, try & >> use ctypes. >> It's much easier to create bindings for, keeps you fully in >> the warm and >> cozy womb of python programming and doesn't need no >> compilation to create >> the actual binding. >> > You're right the ctypes does seem more pythonesque; however I'm still stuck trying return all these parameters > that the c api uses. my ctypes code is below. It just quits running when I try to print > one of the args I did a pass byref on, no error out, nothing. admittedly I'm a newbie to ctypes and not much of a c programmer > but I could sure use some help. my ctypes test code follows... > > from ctypes import * > > ''' > create shared object file like so. > gcc -shared -o rug520.so rug520.c You need to create a proper library. The above doesn't do that - it creates as simple object file. I don't know how to really do that without using autoconf/automake. Diez From gminick at nie.ma.takiego.adresu.w.sieci.pl Wed Aug 13 18:50:29 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Wed, 13 Aug 2008 22:50:29 +0000 (UTC) Subject: Replace Several Items References: <513926b0-64fe-4fdc-bb33-bc4b8ad3ab10@a70g2000hsh.googlegroups.com> Message-ID: Dnia Thu, 14 Aug 2008 00:31:00 +0200, Fredrik Lundh napisa?(a): >>> if ch in my_string: >>> my_string = my_string.replace(ch, "") >>> >>> on representative data. >> >> I don't have to, I can anticipate the results. > > Chances are that you're wrong. At the moment my average is about 0.75 of mistake per post on comp.lang.python (please, bare with me ;-)). I strongly believe that the statement I made above won't make this number rise. :) -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From mbrkic at invalid_mail.adress Sat Aug 30 21:32:37 2008 From: mbrkic at invalid_mail.adress (Marin Brkic) Date: Sun, 31 Aug 2008 03:32:37 +0200 Subject: Writing to ms excel References: <56aeb3cd-1e37-4242-aefe-8a33452d61a2@q26g2000prq.googlegroups.com> Message-ID: <3msjb412b55hf4i00fvs3gto8lt6kv05na@4ax.com> On Sat, 30 Aug 2008 17:18:19 -0700 (PDT), John Machin wrote: Hello John (and everyone else), thanks for answering. >It helps in situations like this to mention details of your >environment >(1) what version of what operating system (Linux, OS X, Windows, etc) >(2) what version of Python >as the available solutions are often dependent on the answers. Yes, of course. I sometimes forget the most essential of things. - winxp, sp2 - python 2.5.2 > >For Python version 2.[345] on any platform, you can use xlwt, which is >as simple as this for writing a 1-worksheet Excel 97-to-2003 XLS file >(without any formatting): Actually, that might work. What I was needing (aiming for) was a way to write to excel 2003 files. Formatting is not necessary, since what I'm trying to write is some tabular data; results from fortran-python simulation (I can explain, but the details seem irrelevant for this case). I'm trying to avoid the text file - import to excel - mechanism, since there is quite a lot of files written. > >def write_xls(file_name, sheet_name, data): > import xlwt > book = xlwt.Workbook() > sheet = book.add_sheet(sheet_name) > rowx = 0 > for row in data: > rowx += 1 > for colx, value in enumerate(row): > sheet.write(rowx, colx, value) > book.save(file_name) ># data can be any of the following Python types: int, long, float, >decimal.Decimal, datetime.date, datetime.datetime, bool, str, and >unicode. > >xlwt is available from https://secure.simplistix.co.uk/svn/xlwt/trunk > >I suggest that you join the python-excel group (http:// >groups.google.com.au/group/python-excel?hl=en) or at least read some >of the questions and responses. Please, one more question. As you have noticed, I posted my message to comp.lang.python, using a newsreader. Is there a way to access google groups through a similiar interface program as a newsreader. Never used them before, and getting a lot of messages to my email every day does not sound very appealing to me. Best regards Marin > >HTH, > >John From poojaangali at gmail.com Fri Aug 15 06:00:17 2008 From: poojaangali at gmail.com (pooja) Date: Fri, 15 Aug 2008 03:00:17 -0700 (PDT) Subject: EARN MONEY $1500-$5000 PER MONTH Message-ID: <44213a03-09f5-4373-bec8-e84e5372dd6e@j1g2000prb.googlegroups.com> EARN MONEY $1500-$5000 PER MONTH SIMPLE ONLINE SURVEY CREATE UR ACCOUNT AND EARN IMMEDIATLY ************************************************************************* http://www.AWSurveys.com/HomeMain.cfm?RefID=kingraja666 ************************************************************************* From darcy at druid.net Tue Aug 26 09:11:30 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 26 Aug 2008 09:11:30 -0400 Subject: Sharing common memory space (In form of List) across the python processes. In-Reply-To: References: Message-ID: <20080826091130.d692951b.darcy@druid.net> On Tue, 26 Aug 2008 18:18:53 +0530 Piyush Chechani wrote: > Please suggest how to share a in-memory list object across two different > programs? Perhaps you want to investigate XML-RPC. Check the docs for some example scripts for both client and server. P.S. Please drop the legal crap from your postings. This is a public list and such things are just a waste of space. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From dangets at gmail.com Fri Aug 8 13:37:40 2008 From: dangets at gmail.com (DG) Date: Fri, 8 Aug 2008 10:37:40 -0700 (PDT) Subject: relative imports improve program organization... suggestions? Message-ID: <1a0a7d3c-4d65-4c50-823e-f8d8be61592f@1g2000pre.googlegroups.com> Alright, I have searched and searched and read many conversations on the topic of relative and absolute imports and am still not getting the whole thing through my skull. Highlights of what I've read: http://mail.python.org/pipermail/python-list/2007-January/422973.html http://groups.google.com/group/comp.lang.python/browse_thread/thread/b1e8dc93471a7079/8751c82cfe1ca3f2?lnk=gst&q=absolute+import#8751c82cfe1ca3f2 http://www.python.org/dev/peps/pep-0328/ http://docs.python.org/whatsnew/pep-328.html So my problem and argument: I want to create a package organized as the following: pckg/ __init__.py main.py moduleA/ __init__.py A_base.py A1/ __init__.py A_inherit1.py other_A1_files... A2/ __init__.py A_inherit2.py other_A2_files... moduleB/ ... Explanation: The main program is located in main.py and it implements the different modules (A, B). Within the modules the basic organization is; the base class for all different types of A is directly within the moduleA directory. All of the different inherited classes of A are within their own subdirectory with a mess of their own files. This is done so that a new subclass of A can be added/removed by just adding/ removing the subdirectory and each of these subclasses may have their own maintainer, but they should all inherit from A_base.py If I am developing the A1 directory, I want to be able to test A_inherit1.py by using 'if __name__ == "__main__"' within the A_inherit1.py file and by typing 'python A_inherit1.py' on the command line. I prefer this simply to keep all unit tests within the same directory and same file as the inherited class. My Problem: A_inherit1.py has the line: 'from ..A_base import A_Base_Class' so that I can later declare the inherited class as such: 'A1_Inherited_Class(A_Base_Class):' *BUT* I get the 'attempted relative import in non-package' error even when I try the 'from __future__ import absolute_import' command. I would prefer to be able to test the file without adding anything to the PYTHONPATH, like I said by using the name == main trick. So could someone explain to me what the rationale behind not allowing parent directory relative imports is? And possibly what I can do to get around it? (I really don't like messing with the sys.path for something like this) Thanks, Danny G From deets at nospam.web.de Thu Aug 7 11:58:24 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 07 Aug 2008 17:58:24 +0200 Subject: python-mode is missing the class browser References: <6361fac8-3bfb-4d7e-b13b-84261ebeea10@b1g2000hsg.googlegroups.com> <489b1509$0$3481$426a74cc@news.free.fr> Message-ID: <6g0kf5FdoskeU1@mid.uni-berlin.de> Bruno Desthuilliers wrote: > Michele Simionato a ?crit : >> I have noticed that the python-mode for Emacs that comes with the >> latest Ubuntu is missing the class browser. Moreover if works >> differently from the python-mode I was used to (for instance CTRL-c-c >> works as CTRL-c-! whereas CTRL-c-! is missing, etc). How can I go back >> to the old python-mode >> or at least how do I get back the class browser? > > I'm not really up2date wrt/ my ubuntu station here, but I remember > having seen this somewhat different (emacs-provided IIRC) python-mode > which I didn't like. I don't quite remember what I did, but I can at > least tell you what I have actually have: I've got the same, and a IM-Python-menu that contains the class-browser. > FWIW and talking about class-browser, there's the IMHO very excellent > emacs-code-browser too. Yes, it sure is cool. And I have no idea how I ever worked without flymake & pylint :) Emacs just rocks... Diez From simon at mullis.co.uk Wed Aug 13 08:45:31 2008 From: simon at mullis.co.uk (Simon Mullis) Date: Wed, 13 Aug 2008 14:45:31 +0200 Subject: From Ruby to Python? Message-ID: <23d7e1bb0808130545w28fb4c04s205c1de2a39dcb36@mail.gmail.com> Hi All, I just finally found 30 minutes to try and write some code in Python and realized after a couple of minor syntactic false starts that I'd finished my initial attempt without needing to refer to any documention... And after the first few minutes I stopped noticing the whitespace thing that had scared me off previously. (Admittedly it's a very basic script using telnetlib to log into a bunch of network devices via a few console servers and put the results of some remote commands into a data-structure). So, after this initially promising start: Are there any good cheatsheets / guides for a Ruby programmer to learn Python? I searched this list and couldn't find anything, and wasn't successful with google either... Many thanks in advance, SM -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon at brunningonline.net Wed Aug 13 14:32:42 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 13 Aug 2008 19:32:42 +0100 Subject: gasp In-Reply-To: <1ee11ba30808131006p22edb17ap206d42c9ffc2ef1d@mail.gmail.com> References: <65dba773-6441-424e-a019-dc1e493dddb7@v57g2000hse.googlegroups.com> <8c7f10c60808130956l19553772u62d8f993f610a0bc@mail.gmail.com> <1ee11ba30808131006p22edb17ap206d42c9ffc2ef1d@mail.gmail.com> Message-ID: <8c7f10c60808131132y577b7888lf7958d4534c6e770@mail.gmail.com> 2008/8/13 Cyprian Kumwaka : > No, it doesn't! I have even tried uninstalling and installing it but still > it doesn't not work. Any more ideas! What error message do you get when you try it? "Doesn't work" isn't anything like enough to go on. And please keep the conversation on-list. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From timr at probo.com Sat Aug 2 19:31:30 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 02 Aug 2008 23:31:30 GMT Subject: base-96 References: <094aaf8f-0d16-4f85-abd5-232f475b9785@x35g2000hsb.googlegroups.com> Message-ID: Kless wrote: >I think that would be very interesting thay Python would have a module >for working on base 96 too. [1] > >It could be converted to base 96 the digests from hashlib module, and >random bytes used on crypto (to create the salt, the IV, or a key). > >As you can see here [2], the printable ASCII characters are 94 >(decimal code range of 33-126). So only left to add another 2 >characters more; the space (code 32), and one not-printable char >(which doesn't create any problem) by last. Whether it creates problems depends on how you intend to use it. The biggest use for Base64, for instance, is in translating binary files to a form where they can be send via email using only printable characters. If you use a non-printable character, that's a problem for email. With Base64, 3 bytes becomes 4. With Base96, 5 bytes becomes 6. So, you would reduce the conversion penalty from 1.33 down to 1.17. It's not hard to write modules to translate from binary to Base96 and back again, and doing so would be a great exercise to explore the issues in this kind of encoding. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sln at netherlands.com Wed Aug 20 22:36:39 2008 From: sln at netherlands.com (sln at netherlands.com) Date: Thu, 21 Aug 2008 02:36:39 GMT Subject: The Importance of Terminology's Quality References: <48a8df27$0$7362$607ed4bc@cv.net> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: On Thu, 21 Aug 2008 02:30:27 GMT, sln at netherlands.com wrote: >On Wed, 20 Aug 2008 21:18:22 -0500, rpw3 at rpw3.org (Rob Warnock) wrote: > >>Martin Gregorie wrote: >>+--------------- >>| I was fascinated, though by the designs of early assemblers: I first >>| learnt Elliott assembler, which required the op codes to be typed on >>| octal but used symbolic labels and variable names. Meanwhile a colleague >>| had started on a KDF6 which was the opposite - op codes were mnemonics >>| but all addresses were absolute and entered in octal. I always wondered >>| about the rationale of the KDF6 assembler writers in tackling only the >>| easy part of the job. >>+--------------- >> >>In the LGP-30, they used hex addresses, sort of[1], but the opcodes >>(all 16 of them) had single-letter mnemonics chosen so that the >>low 4 bits of the character codes *were* the correct nibble for >>the opcode! ;-} >> >>[Or you could type in the actual hex digits, since the low 4 bits >>of *their* character codes were also their corresponding binary >>nibble values... "but that would have been wrong".] >> >> >>-Rob >> >>[1] The LGP-30 character code was defined before the industry had >> yet standardized on a common "hex" character set, so instead of >> "0123456789abcdef" they used "0123456789fgjkqw". [The "fgjkqw" >> were some random characters on the Flexowriter keyboard whose low >> 4 bits just happened to be what we now call 0xa-0xf]. Even worse, >> the sector addresses of instructions were *not* right-justified >> in the machine word (off by one bit), plus because of the shift- >> register nature of the accumulator you lost the low bit of each >> machine word when you typed in instructions (or read them from >> tape), so the address values you used in coding went up by *4*! >> That is, machine locations were counted [*and* coded, in both >> absolute machine code & assembler] as "0", "4", "8", "j", "10", >> "14", "18", "1j" (pronounced "J-teen"!!), etc. >> >>----- >>Rob Warnock >>627 26th Avenue >>San Mateo, CA 94403 (650)572-2607 > > >Whats os interresting about all this hullabaloo is that nobody has >coded machine code here, and know's squat about it. > >I'm not talking assembly language. Don't you know that there are routines >that program machine code? Yes, burned in, bitwise encodings that enable >machine instructions? Nothing below that. > >There is nobody here, who ever visited/replied with any thought relavence that can >be brought foward to any degree, meaning anything, nobody.... > >sln At most, your trying to validate you understanding. But you don't pose questions, you pose terse inflamatory declarations. You make me sick! sln From tomchelan at msn.com Wed Aug 20 21:11:16 2008 From: tomchelan at msn.com (TOM MCCULLOUGH) Date: Wed, 20 Aug 2008 18:11:16 -0700 Subject: Delivery Status Notification (Failure) Message-ID: You Suck big time! -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Emoticon7.gif Type: image/gif Size: 250 bytes Desc: not available URL: From thegiantsden at gmail.com Wed Aug 13 21:25:53 2008 From: thegiantsden at gmail.com (Shemia Miller) Date: Wed, 13 Aug 2008 21:25:53 -0400 Subject: JOB: Python Programmer Message-ID: <67d1651f0808131825k6ce7e0e1n992d5649028f0f40@mail.gmail.com> Greetings, I would like to hire a python expert who can quickly install the database with accuracy. It is only one script, and it shouldn't take no more than an hour. The script is at http://www.askspree.de My hosting provider doesn't have turbo, so I have vps. Quick way to earn $50.00. It is an hour job. Thank you for your immediate attention to this matter. -- Phone Number: (641) 715-3900 Extension: 66984# Please allow 24-48 hrs. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Thu Aug 28 20:00:57 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2008 00:00:57 GMT Subject: [Q] How to ignore the first line of the text read from a file References: <6hocqtFmpekqU5@mid.uni-berlin.de> Message-ID: <00c736d5$0$20302$c3e8da3@news.astraweb.com> On Thu, 28 Aug 2008 15:11:39 -0700, Dennis Lee Bieber wrote: > On 28 Aug 2008 19:32:45 GMT, Marc 'BlackJack' Rintsch > declaimed the following in comp.lang.python: > >> On Thu, 28 Aug 2008 10:16:45 -0700, norseman wrote: >> > import os >> > >> > file = open(filename, 'r') >> > for line in file: >> > dummy=line >> > for line in file: >> > print line >> > >> > >> > is cleaner and faster. >> >> That's not cleaner, that's a 'WTF?'! A ``for`` line over `file` that >> does *not* iterate over the file but is just there to skip the first >> line and a completely useless `dummy` name. That's seriously ugly and >> confusing. >> > Nice to see someone else was as, uhm, offended by that code sample > as I was -- I just lacked the vocabulary to put it across cleanly, so > didn't respond. > > Yes, the "dummy" statement could be completely dropped to the same > effect -- still leaving the useless outer loop... Nevertheless, I've just done some timeit tests on the two code snippets, and to my *great* surprise the second ugly snippet is consistently a smidgen faster even with the pointless import and dummy statement left in. That is so counter-intuitive that I wonder whether I've done something wrong, or if it's some sort of freakish side-effect of disk caching or something. But further investigation will have to wait for later. If anyone wants to run their own timing tests, don't forget to close the file explicitly, otherwise timeit() will (I think...) simply iterate over the EOF for all but the first iteration. -- Steven From siona at chiark.greenend.org.uk Fri Aug 1 09:47:17 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 01 Aug 2008 14:47:17 +0100 (BST) Subject: very large dictionary References: <5c5e6d6e-04ef-4340-963f-d3825875b32c@e39g2000hsf.googlegroups.com> Message-ID: Simon Strobl wrote: >I tried to load a 6.8G large dictionary on a server that has 128G of >memory. I got a memory error. I used Python 2.5.2. How can I load my >data? Let's just eliminate one thing here: this server is running a 64-bit OS, isn't it? Because if it's a 32-bit OS, the blunt answer is "You can't, no matter how much physical memory you have" and you're going to have to go down the database route (or some approach which stores the mapping on disk and only loads items into memory on demand). -- \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" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From bsder at allcaps.org Fri Aug 1 19:23:02 2008 From: bsder at allcaps.org (Andrew Lentvorski) Date: Fri, 01 Aug 2008 16:23:02 -0700 Subject: Class definition attribute order Message-ID: <48939AD6.8060703@allcaps.org> How do I determine the order of definition of class attributes? For example, if I have a class class Test(object): y = 11 x = 22 How do I tell that y was defined before x? Thanks, -a From fredrik at pythonware.com Sat Aug 30 09:32:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 30 Aug 2008 15:32:06 +0200 Subject: How to delete elements from Tix Combo Box? In-Reply-To: References: Message-ID: dudeja.rajat at gmail.com wrote: > I'm using a Tix combo box (I call it combo2), the contents of which > are loaded depeding on the selection in another Tix combo box(I call > it combo1) > I have used the commands: > > self.cbAnalysisLibVersion.insert(END, results) > > to insert elements to the combo box. > > I'm looking for some similar option to delete elements from the combo > box. I mean, as soon as I change selection in > combo1 the previous elements in the combo2 should get cleared up( or > deleted) and | shall be able to the above insert command to add new > elements to the combo2 ( depending upon selection in combo1) > > Please suggest how can I clear up the ( delete the entries) in combo2. no time to test this, but iirc, the combobox content is held in an ordinary listbox widget, so you should be able to use the subwidget method to fetch that widget, and then use ordinary listbox methods to change the content. Something like this: lb = w.subwidget("listbox") lb.delete(0, END) # delete all items From tjreedy at udel.edu Tue Aug 5 15:03:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 05 Aug 2008 15:03:27 -0400 Subject: Difference between type and class In-Reply-To: References: <87myjy2vc6.fsf@nokile.rath.org> <12072cbe-139a-430f-81aa-b64bc31b43e5@e39g2000hsf.googlegroups.com> <87zlny8cdg.fsf@nokile.rath.org> Message-ID: Gabriel Genellina wrote: A decade ago, in 1.x, 'types' were built-in classes. They were instances of class 'type'. 'Classes' were user-defined classes. They were instances of (built-in) class 'classob'. User classes had the same status as instances of any other built-in class. They could only inherit from other instances of 'UserClass'. Instances of user classes were actually instances of built-in class 'instance'. They could not be instances of the user class because user classes were, in a sense, not really classes, just instances of 'classob' that emulated 'real' classes. >>> class C(): pass ... >>> c=C() >>> type(C) >>> type(c) Many users found the distinction between built-in classes and user classes confusing and limiting. Users wanted to be able to use built-in classes as base classes for user classes. So in 2.2 'object' was added as the base-class for all built-in classes and user-classes with 'object' in the base-class tree became instances of type (or of some other meta-class derived from type) instead of classob. But the representation of new-style classes matched that of old-style classes rather than that of the other instances of 'type' that happened to be built in. In 3.0, built-in classes 'classob' and 'instance' are gone, along with the confusion of having two categories of user classes along with an apparently separate category of built-in classes. User-classes are real classes on a par with C-coded classes. >>> class C(): pass # 3.0, in 2.x, class c(object) >>> c=C() >>> type(C) # same as >> type(int) >>> type(c) > If it helps you to understand the issue, in Python 3.0 that > difference is gone - the word "class" is used on both cases. See > http://bugs.python.org/issue2565 The only visible difference now (in 3.0) is that C-coded built-in classes that are present as startup and which do not live in any particular module do not have a module name as part of their representation. Imported C-coded classes show no difference (and indeed, in other implementations, they might be coded in Python or ?? rather than C). >>> int >>> c >>> import itertools as i >>> i.product I believe this should mean that if one write a module in Python and later rewrites part of it in C for speed, with identical API, the change of implementation will otherwise be transparent to user code and users, as it ought to be. Terry Jan Reedy From ironfroggy at gmail.com Wed Aug 13 23:40:50 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Wed, 13 Aug 2008 23:40:50 -0400 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> <76fd5acf0808120651u259e5d8dt32a8d49bb5d77add@mail.gmail.com> <200808122240.22517.maric@aristote.info> <76fd5acf0808121415h41cc580bj85d96e648c54ab4b@mail.gmail.com> <74583B8642AB8841B30447520659FCA92CC054B5@dnce01.ent.ti.com> Message-ID: <76fd5acf0808132040n22fd51f2seb12c403162f5d8b@mail.gmail.com> On Wed, Aug 13, 2008 at 10:49 PM, Carl Banks wrote: >> There is no point of nested classes because nested classes _are not_ >> supported by python. They are simply an artifact of not actively >> denying the syntax non-globally. I would fully support a change to the >> language to actively forbid a class definition that is not >> module-level. > > I think that's taking it a little too far. It's not unreasonable to > throw small, private use classes into the class definition, like so: > > class Someting(object): > class PrivateException(Exception): > pass > > And inside function a class definition can make a lot of sense. > Oftentimes I write a quick adaptor class because I want to pass > something to code that expects something else, for instance: > > def some_function(lines): > class FileMimicker(object): > def __init__(self): > self.index = 0 > def readline(self): > line = lines[self.index] > self.index += 1 > return line > function_that_calls_readline(FileMimicker()) > > > (Why would I want to clutter up my module's namespace for that silly > thing?) > > So I see no good reason for the compiler to disallow nested class > statements; it's occasionally useful and not a common pitfall. > > Carl Banks I know every rule has its exceptions. I put "don't nest classes" in with other similar rules I will claim, where I think its safest to say "Never do this!", because only then will you know that, should you actually do it at some point, you've got a reason good enough to break a "rule". As for the cluttering of the namespace, I don't buy it. Sure there are cases to be made to reduce the number of names in any scope, but I don't see a big advantage here. Its still accessible from the module, just though the class. I also don't see any examples of nested classes that wouldn't be useful elsewhere, your example included. For that matter, your example should just being using StringIO. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy From boblatest at yahoo.com Fri Aug 1 15:22:14 2008 From: boblatest at yahoo.com (Robert Latest) Date: 1 Aug 2008 19:22:14 GMT Subject: Pointers/References in Python? References: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Message-ID: <6fh636Fb67ejU1@mid.uni-berlin.de> Gary Herron wrote: > No need. A Python list contains *references* to objects, not copies of > objects. (The same is true of variables, dictionaries, sets, and so > on...). Good to know. I just wanted to make sure before writing more code which in the end might not scale well. Thanks to all for the help! robert From sthembilengidi at gmail.com Mon Aug 25 04:58:36 2008 From: sthembilengidi at gmail.com (Amie) Date: Mon, 25 Aug 2008 01:58:36 -0700 (PDT) Subject: For loop inside an xml template Message-ID: <57deb346-9326-4d97-9c88-7475baf0a30f@c58g2000hsc.googlegroups.com> Hi, Is it possible to have a for loop within an xml template? From msakibkhan at gmail.com Sat Aug 23 02:33:32 2008 From: msakibkhan at gmail.com (SaqibKhan) Date: Fri, 22 Aug 2008 23:33:32 -0700 (PDT) Subject: Error accessing the system registery Message-ID: Hello members ! a message box is appearing when I goto 'Tools> References' in VBA or VB6. I have tried many options but issue is not resolved yet. I have no administrator's rights in PC. can anybody resolve my problem ??? Best Regards M. Saqib Khan From cvrebert+clp at gmail.com Thu Aug 28 14:25:43 2008 From: cvrebert+clp at gmail.com (Chris Rebert) Date: Thu, 28 Aug 2008 11:25:43 -0700 Subject: epoch seconds from a datetime In-Reply-To: <40ab500b-f33f-4d6a-9c7c-fecee0119ba0@s50g2000hsb.googlegroups.com> References: <40ab500b-f33f-4d6a-9c7c-fecee0119ba0@s50g2000hsb.googlegroups.com> Message-ID: <47c890dc0808281125r4af5aa3ex1f44fc122cba06cf@mail.gmail.com> On Thu, Aug 28, 2008 at 10:18 AM, Richard Rossel wrote: > Hi friends, > I need a little help here, I 'm stuck with epoch calculation issue. > I have this datetime: > date_new = datetime(*time.strptime('20080101T000000','%Y%m%dT%H%M%S') > [0:6]) > This date_new is in UTC > Now I need to know the seconds since epoch of this new date, so I run > this: > seconds = int(time.mktime(date_new.timetuple())) > but the seconds returned belongs to : > Tue, 01 Jan 2008 03:00:00 GMT > because the localtime is in timezone 'America/Santiago': -3 > > I fix this trying to alter the TZ with time.tzset(): > os.environ['TZ'] = 'UTC' > time.tzset() > > .... and now I can gets the right epoch, but I can't restore the > previous TimeZone, I try with: > os.environ['TZ'] = '', but the time.tzset() doesn't back to the > original ( America/Santiago) I think you need to del os.environ['TZ'] rather than setting it to the empty string. On my box: Python 2.5.1 (r251:54863, Feb 4 2008, 21:48:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin >>> import os, time >>> time.asctime() 'Thu Aug 28 11:19:57 2008' >>> #that's my correct local time >>> time.tzname ('PST', 'PDT') >>> #that's my correct timezone >>> os.environ['TZ'] = 'UTC' >>> time.tzset() >>> time.tzname ('UTC', 'UTC') >>> time.asctime() 'Thu Aug 28 18:20:33 2008' >>> #we're clearly in UTC now >>> del os.environ['TZ'] #this is the key line >>> time.tzset() >>> time.tzname ('PST', 'PDT') >>> time.asctime() 'Thu Aug 28 11:21:05 2008' >>> #and now we're back to my original timezone Regards, Chris ======== Follow the path of the Iguana... Rebertia: http://rebertia.com Blog: http://blog.rebertia.com > > A solution should be set the os.environ['TZ'] to 'America/Santiago' > but I can't make a TZ hardcode because > the software should works on different timezones. > > So the question, how can restore the system into original timezone, or > how to know the seconds since epoch > from UTC datetime without change the local system TIMEZONE. > > please help > > -- > http://mail.python.org/mailman/listinfo/python-list > From musiccomposition at gmail.com Fri Aug 15 23:13:25 2008 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 15 Aug 2008 20:13:25 -0700 (PDT) Subject: python interpreter References: <29e59f7a-af87-40b4-9c5e-58abe1a28721@t1g2000pra.googlegroups.com> <1a514d18-579f-4372-bf9d-0c7b8e45a24f@f63g2000hsf.googlegroups.com> Message-ID: <0058c2b4-1489-4d31-bb8a-f8b7bb0f8d6e@2g2000hsn.googlegroups.com> On Aug 12, 10:06?am, Wojtek Walczak wrote: > > And keep in mind that reload() is removed in Py3k. Hope this helps. It's not gone; it's just renamed to imp.reload. > > -- > Regards, > Wojtek Walczak,http://www.stud.umk.pl/~wojtekwa/ From mensanator at aol.com Tue Aug 12 00:25:55 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 11 Aug 2008 21:25:55 -0700 (PDT) Subject: list question... unique values in all possible unique spots References: <57fcf019-1afd-4c48-b329-42a0ffc4c5ac@x35g2000hsb.googlegroups.com> <90f040d9-ce7e-440f-96e1-785c47242bdb@k30g2000hse.googlegroups.com> <8471c20a-06f6-4927-967a-7eae395c3055@79g2000hsk.googlegroups.com> Message-ID: <2b0bd9b5-e5b6-4924-a0ce-b4d2a3bae63b@w7g2000hsa.googlegroups.com> On Aug 11, 7:34?pm, bearophileH... at lycos.com wrote: > Mensanator: > > > Ever tried to iterate 403 septillion times? > > The OP is talking about formulas, like: > X + Y * Z = W > Where X, Y, Z, W distinct and in [1, 26], so you have C(26, 4) > combinations that's way less than 26! > > >>> binomial(26, 4) > > 14950 > > So this can be solved with a xcombinations() generator. How did you surmise it's C(26,4)? > > Bye, > bearophile From anishchapagain at gmail.com Fri Aug 29 07:48:27 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Fri, 29 Aug 2008 04:48:27 -0700 (PDT) Subject: problem with plotting References: <418c1e73-f6ac-4a3c-bd56-f461f9209e03@2g2000hsn.googlegroups.com> <49907d0b-b880-4c65-bdb3-70b6f5b6144f@k37g2000hsf.googlegroups.com> Message-ID: On Aug 29, 12:24?pm, "Eric_Dex... at msn.com" wrote: > On Aug 29, 6:01?am, Anish Chapagain wrote: > > > > > > > hi, > > I'm getting problem with the code below which after displaying graph > > plotted in external window, doesnot closes itself, even after closing > > the window of plotting the main python window shows processing. > > code goes like this... > > > plot(col1, col2, linewidth=1.0) > > xlabel('col1') > > ylabel('col2') > > title('Values from List created with file read') > > grid(True) > > savefig('col1 col2.pdf') > > show() > > > is there any other function to be called after show() to close it > > properly. > > > thank's for any help. > > > anish > > what library/system are you using???- Hide quoted text - > > - Show quoted text - Hi.. am using pylab and have added the print "plotting finished" after show() which get's printed in python main window but then doesnot return to prompt and have to kill the window again. regard's# anish From attn.steven.kuo at gmail.com Fri Aug 1 14:54:27 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Fri, 1 Aug 2008 11:54:27 -0700 (PDT) Subject: mapping a string to an instancemethod References: <7wIkk.16976$mh5.6016@nlpi067.nbdc.sbc.com> Message-ID: <02639d28-e074-406e-a954-ace3d9db694a@w1g2000prk.googlegroups.com> On Aug 1, 11:22 am, m... at pixar.com wrote: > The following bit of code will allow an instance member to > be called by reference. How can I map a string (e.g. > "hello1" or "Foo.hello1" to a the instance member? > > class Foo: > def hello1(self, p): > print 'hello1', p > def hello2(self, p): > print 'hello2', p > def dispatch(self, func, p): > func(self,p) > > f=Foo() > f.dispatch(Foo.hello1, 23) > f.dispatch(Foo.hello1, 24) > > f.dispatch_as_string("hello1", 23) ## this is what I want to do. > > Many TIA and apologies if this is a FAQ, I googled and couldn't > find the answer. Use getattr; add exception handling as needed. E.g., class Foo(object): def __init__(self): self.fake = None def hello1(self, p): print 'hello1', p def hello2(self, p): print 'hello2', p def dispatch_as_string(self, fname, p): try: inst_method=getattr(self, fname) inst_method(p) except AttributeError: # maybe no such attribute raise except TypeError: # maybe the attribute is not callable (wrong type) raise f = Foo() f.dispatch_as_string('hello1', 12) -- Hope this helps, Steven From bdesth.quelquechose at free.quelquepart.fr Sun Aug 17 06:09:43 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 17 Aug 2008 12:09:43 +0200 Subject: how to add property "dynamically"? In-Reply-To: References: Message-ID: <48a814d9$0$10444$426a74cc@news.free.fr> akonsu a ?crit : > hello, > > i need to add properties to instances dynamically during run time. > this is because their names are determined by the database contents. > so far i found a way to add methods on demand: > > class A(object) : > def __getattr__(self, name) : > if name == 'test' : > def f() : return 'test' > setattr(self, name, f) > return f > else : > raise AttributeError("'%s' object has no attribute '%s'" % > (self.__class__.__name__, name)) > this seems to work and i can invoke method test() on an object. Nope. This adds per-instance *function* attributes - not *methods*. class A(object) : def __getattr__(self, name) : if name == 'test' : def f(self) : return "%s.test" % self setattr(self, name, f) return f else : raise AttributeError( "'%s' object has no attribute '%s'" \ % (self.__class__.__name__, name) ) a = A() a.test() => Traceback (most recent call last): File "", line 1, in TypeError: f() takes exactly 1 argument (0 given) To add methods on a per-instance basis, you have to manually invoke the descriptor protocol's implementation of function objects: class A(object) : def __getattr__(self, name) : if name == 'test' : def f(self) : return "%s.test" % self m = f.__get__(self, type(self)) setattr(self, name, m) return m else : raise AttributeError( "'%s' object has no attribute '%s'" \ % (self.__class__.__name__, name) ) > it > would be nice to have it as property though. so i tried: > > class A(object) : > def __getattr__(self, name) : > if name == 'test' : > def f() : return 'test' > setattr(self, name, property(f)) > return f > else : > raise AttributeError("'%s' object has no attribute '%s'" % > (self.__class__.__name__, name)) > > but this does not work, instance.test returns a callable but does not > call it. Properties must be class attributes. The only way (the only way I know) to get them to work as instance-attributes is to overload __getattribute__, which is tricky and may have pretty bad impact on lookup perfs - and ruins the whole point of using properties FWIW. > i am not an expert in python, would someone please tell me what i am > doing wrong? Wrong solution to your problem, I'd say. Let's start again: """ > i need to add properties to instances dynamically during run time. > this is because their names are determined by the database contents. """ Care to elaborate ? I may be wrong, but I suspect you're trying to roll your own python/database mapper. If so, there are quite a couple Python ORMs around. Else, please tell us more. From Edwin.Madari at VerizonWireless.com Tue Aug 19 11:56:28 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Tue, 19 Aug 2008 11:56:28 -0400 Subject: who to call a list of method inside the class itself In-Reply-To: Message-ID: <20080819155641.63F621E4006@bag.python.org> fredrik at pythonware.com wrote: > > Edwin.Madari at VerizonWireless.com wrote: > > > 1. return string names of required methods in getAllMethod > > return ['method1', 'method2', 'method3'] > > 2. use gettattr on self and then exetute methods in applyAll > > def applyAll(self): > > for method_name in self.getAllMethod(): > > method = gettattr(self,method_name) > > method() #execute method now > > why? ensure instance's method invocation with all state information to that point, rather than relying on implemenation. regards. Edwin The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From ironfroggy at gmail.com Tue Aug 12 09:51:30 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Tue, 12 Aug 2008 09:51:30 -0400 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> Message-ID: <76fd5acf0808120651u259e5d8dt32a8d49bb5d77add@mail.gmail.com> The simple answer is "Dont nest classes. It is not supported." What you are seeing is really an artifact of how classes are built. Basically, everything inside the class body has to exist before it can run, so the inner classes code objects are actually created first. However, the class object itself isnt created out of that until the body of the outer class is evaluated. On Tue, Aug 12, 2008 at 5:29 AM, Cousson, Benoit wrote: > Hi, > > I'd like to be able to use a nested class (C1) from another sibling nested class (C3). This looks very similar to the nested scopes of functions except that it does not work. > > class A(object): > pass > > class B(object): > > class C1(object): > pass > > class C2(C1): > foo = A > > class C3(object): > foo = C1 > > The funny thing is that C2 can inherit from C1 but C3 cannot reference C1. B.C1 does not work either, but in that case it makes sense since B is still being defined. > Is this a language limitation or something that does not make sense at all? > > I'm wondering as well if the new nonlocal statement will fix that in py3k? > > Thanks in advance, > Benoit > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From apardon at forel.vub.ac.be Fri Aug 1 04:35:12 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 1 Aug 2008 08:35:12 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <9f4b1c12-d010-45f6-91ee-d490e2f850dc@79g2000hsk.googlegroups.com> Message-ID: On 2008-08-01, Erik Max Francis wrote: > Antoon Pardon wrote: > >> I now have the following question for people who argue that "if x" >> is more polymorphic. I could subclass list, so that instances >> of this new sequence would always behave as true, even if they are >> empty. I could then rewrite my loop as follows: >> >> while 1: >> extra = produce() >> if not extra: >> break >> for el in extra: >> adjust_with(el) >> calculate() >> >> Is this second loop now more polymorphic as the first? > > It's more confusing since you've changed the standard behavior of a > standard type, which doesn't really have anything to do with > polymorphism. It's more confusing, if that's a benefit. So you accept my point that "if x" can be less polymorphic and in fact can be more confusing than a more specific test. -- Antoon Pardon From hubaghdadi at gmail.com Sun Aug 24 04:32:34 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Sun, 24 Aug 2008 01:32:34 -0700 (PDT) Subject: What is class method? Message-ID: Hi, I'm familiar with static method concept, but what is the class method? how it does differ from static method? when to use it? -- class M: def method(cls, x): pass method = classmethod(method) -- Thank you for your time. From mattheww at chiark.greenend.org.uk Fri Aug 1 13:24:34 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 01 Aug 2008 18:24:34 +0100 (BST) Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> <00a23ad3$0$20313$c3e8da3@news.astraweb.com> Message-ID: Thomas Troeger wrote: > Will this disappear in Python 3.0., i.e. can you again simply write > > class A: > > and inherit from object automagically? Short answer: yes. -M- From Nikolaus at rath.org Mon Aug 4 09:30:51 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 04 Aug 2008 15:30:51 +0200 Subject: Locking around Message-ID: <87ej547vqs.fsf@nokile.rath.org> Hello, I need to synchronize the access to a couple of hundred-thousand files[1]. It seems to me that creating one lock object for each of the files is a waste of resources, but I cannot use a global lock for all of them either (since the locked operations go over the network, this would make the whole application essentially single-threaded even though most operations act on different files). My idea is therefore to create and destroy per-file locks "on-demand" and to protect the creation and destruction by a global lock (self.global_lock). For that, I add a "usage counter" (wlock.user_count) to each lock, and destroy the lock when it reaches zero. The number of currently active lock objects is stored in a dict: def lock_s3key(s3key): self.global_lock.acquire() try: # If there is a lock object, use it if self.key_lock.has_key(s3key): wlock = self.key_lock[s3key] wlock.user_count += 1 lock = wlock.lock # otherwise create a new lock object else: wlock = WrappedLock() wlock.lock = threading.Lock() wlock.user_count = 1 self.key_lock[s3key] = wlock finally: self.global_lock.release() # Lock the key itself lock.acquire() and similarly def unlock_s3key(s3key): # Lock dictionary of lock objects self.global_lock.acquire() try: # Get lock object wlock = self.key_lock[s3key] # Unlock key wlock.lock.release() # We don't use the lock object any longer wlock.user_count -= 1 # If no other thread uses the lock, dispose it if wlock.user_count == 0: del self.key_lock[s3key] assert wlock.user_count >= 0 finally: self.global_lock.release() WrappedLock is just an empty class that allows me to add the additional user_count attribute. My questions: - Does that look like a proper solution, or does anyone have a better one? - Did I overlook any deadlock possibilities? Best, Nikolaus [1] Actually, it's not really files (because in that case I could use fcntl) but blobs stored on Amazon S3. -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From fredrik at pythonware.com Tue Aug 5 10:37:07 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 05 Aug 2008 16:37:07 +0200 Subject: Python FTP - NameError: name 'mydpa' is not defined In-Reply-To: References: Message-ID: Ej wrote: > I have a similar problem. I need to download the same file every hour > so it will be nice to be able to rename the downloads with a variable > name. > > For example in this case: > > from ftplib import FTP > ftp=FTP('tgftp.nws.noaa.gov') > ftp.login() > ftp.cwd('SL.us008001/DF.of/DC.radar/DS.81dpr/SI.kbuf') > ftp.retrbinar('RETR sn.last', open('sn','wb').write) > ftp.quit() > > Question: How to achive rename the downloaded files as sn1, sn2, > sn3.... or with a timestamp? you're downloading to the file name you pass to open ("sn" in your case), so to download to a different file, just pass in another name. to rename an existing file on the local file system, use os.rename. From claird at lairds.us Sat Aug 23 11:29:35 2008 From: claird at lairds.us (Cameron Laird) Date: Sat, 23 Aug 2008 15:29:35 +0000 Subject: rules of thumb for cross os code References: <76c97ae9-2ca0-4419-8630-c7cf6159811a@v16g2000prc.googlegroups.com> Message-ID: In article <76c97ae9-2ca0-4419-8630-c7cf6159811a at v16g2000prc.googlegroups.com>, DwBear75 wrote: >I am considering using python as a replacement for a lot of bash >scripting that I have been doing. I would like to be as cross platform . . . >2) nifty lambda's or other things to create functions fit for the >environment >3) capturing return codes of other executables called from python; ie >use os.system, or popen? or ? I don't understand 2); maybe is a response, although I suspect it's at a different level than you had in mind. For 3), read on "Replacing os.system()", although I have several personal quibbles with details of the subprocess reference documentation. From deets at nospam.web.de Fri Aug 22 10:49:46 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 22 Aug 2008 16:49:46 +0200 Subject: Should Python raise a warning for mutable default arguments? In-Reply-To: <00becb2d$0$20312$c3e8da3@news.astraweb.com> References: <00becb2d$0$20312$c3e8da3@news.astraweb.com> Message-ID: <6h820aFjrnqtU1@mid.uni-berlin.de> Steven D'Aprano schrieb: > Sometimes it seems that barely a day goes by without some newbie, or not- > so-newbie, getting confused by the behaviour of functions with mutable > default arguments. No sooner does one thread finally, and painfully, fade > away than another one starts up. > > I suggest that Python should raise warnings.RuntimeWarning (or similar?) > when a function is defined with a default argument consisting of a list, > dict or set. (This is not meant as an exhaustive list of all possible > mutable types, but as the most common ones that I expect will trip up > newbies.) The warning should refer to the relevant FAQ or section in the > docs. I just suggested a documentation enhancement in one of the plethora of threads... so I'm certainly +1 for any enhancement in this area. Diez From siona at chiark.greenend.org.uk Fri Aug 29 09:14:03 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 29 Aug 2008 14:14:03 +0100 (BST) Subject: file data to list References: <8804b75e-0dd9-4d3a-be69-ccb6c12f6a9d@b1g2000hsg.googlegroups.com> Message-ID: Emile van Sebille wrote: >data = zip(*[xx.split() for xx in open('data.txt').read().split("\n")]) Files are iterable: data = zip(*[xx.rstrip().split() for xx in open('data.txt')]) saves you creating the extra intermediate list resulting from split("\n"). -- \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" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From http Wed Aug 27 01:39:56 2008 From: http (Paul Rubin) Date: 26 Aug 2008 22:39:56 -0700 Subject: atomic increment References: <6297cf93-5eec-4bf3-9104-0605a82f7186@p10g2000prf.googlegroups.com> <6hinduFmfmsrU1@mid.uni-berlin.de> <63533495-5cca-4430-9c9d-fbe1cfee0e1e@s50g2000hsb.googlegroups.com> Message-ID: <7xd4jvqamr.fsf@ruckus.brouhaha.com> Frank Millman writes: > Just out of interest, would the following, without a lock, be safe? > old, atomic_int = atomic_int, atomic_int+1 No I don't think so. But I'm told that in CPython, you can say counter = iter(xrange(10000000)) # some number that exceeds what you'll use ... atomic_int = counter.next() and the GIL keeps it safe. When in doubt, use a lock or communicate with other threads through Queues. From sln at netherlands.com Fri Aug 22 18:56:09 2008 From: sln at netherlands.com (sln at netherlands.com) Date: Fri, 22 Aug 2008 22:56:09 GMT Subject: The Importance of Terminology's Quality References: <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: On Thu, 21 Aug 2008 09:11:48 -0500, rpw3 at rpw3.org (Rob Warnock) wrote: >sln at netherlands.com> wrote: >+--------------- >| rpw3 at rpw3.org (Rob Warnock) wrote: >| >In the LGP-30, they used hex addresses, sort of[1], but the opcodes >| >(all 16 of them) had single-letter mnemonics chosen so that the >| >low 4 bits of the character codes *were* the correct nibble for >| >the opcode! ;-} >... >| >[1] The LGP-30 character code was defined before the industry had >| > yet standardized on a common "hex" character set, so instead of >| > "0123456789abcdef" they used "0123456789fgjkqw". [The "fgjkqw" >| > were some random characters on the Flexowriter keyboard whose low >| > 4 bits just happened to be what we now call 0xa-0xf]. Even worse, >| > the sector addresses of instructions were *not* right-justified >| > in the machine word (off by one bit), plus because of the shift- >| > register nature of the accumulator you lost the low bit of each >| > machine word when you typed in instructions (or read them from >| > tape), so the address values you used in coding went up by *4*! >| > That is, machine locations were counted [*and* coded, in both >| > absolute machine code & assembler] as "0", "4", "8", "j", "10", >| > "14", "18", "1j" (pronounced "J-teen"!!), etc. >| >| Whats os interresting about all this hullabaloo is that nobody has >| coded machine code here, and know's squat about it. >+--------------- > >Think again! *BOTH* of the two examples I gave -- for the LGP-30 & the >IBM 1410 -- *WERE* raw machine code, *NOT* assembler!!! Please read again >what I wrote about the character codes for the instruction mnemonics >*BEING* the machine instruction codes. For the IBM 1410, the bootstrap >code that ones types in: > > v v > L%B000012$N > >*IS* raw machine code, *NOT* assembler!! [snip] I don't see the distinction. Just dissasemble it and find out. > >you're typing *RAW* machine code, *NOT* assembler!! You see, the >lower 4 bits of character "b" -- the "mnemonic" for "Bring" -- were >binary 0001, the *same* as the lower 4 bits of the digit "1" (and two >other characters as well). So when you typed a "b" in that position >in "4-bit input mode" you were typing the same thing as the character "1" >which was the same thing as *binary* 0001 which was the absolute machine >opcode for the ""Bring" instruction!! "No assembler required" (pardon >the pun). > >+--------------- >| I'm not talking assembly language. >+--------------- > >Neither was I. The fact that for the two machines I mentioned >absolute machine code was somewhat readable to humans seems to >have confused you, but that's the way some people liked to design >their hardware back in those days -- with clever punning of character >codes with absolute machine opcodes (for the convenience of the user). > >+--------------- >| Don't you know that there are routines that program machine code? >+--------------- > >What do you mean "routines"?!? For the above two machines, you can >enter machine code with *no* programs ("routines?") running; that is, >no boot ROM is required (or even available, as it happened). > [snip all the bullshit] Each op is a routine in microcode. That is machine code. Those op routines use machine cycles. You hit the wall of understanding along time ago, a wall you never looked past. sln From vbp6ynr02 at sneakemail.com Sun Aug 24 10:28:53 2008 From: vbp6ynr02 at sneakemail.com (twyk) Date: Sun, 24 Aug 2008 07:28:53 -0700 (PDT) Subject: PEP 8: Byte Order Mark (BOM) vs coding cookie Message-ID: <186d34d3-c3a9-4d95-984f-89ce36d7b64f@59g2000hsb.googlegroups.com> PEP 8 says ... Files using ASCII (or UTF-8, for Python 3.0) should not have a coding cookie. What about a BOM (Byte Order Mark)? Per Wikipedia ... http://en.wikipedia.org/wiki/Byte-order_mark#endnote_UTF-8) 'In UTF-8, this is not really a "byte order" mark. It identifies the text as UTF-8 but doesn't say anything about the byte order, because UTF-8 does not have byte order issues.' So is it good style to omit the BOM in UTF-8 for Python 3.0? From jldunn2000 at googlemail.com Thu Aug 21 10:53:39 2008 From: jldunn2000 at googlemail.com (loial) Date: Thu, 21 Aug 2008 07:53:39 -0700 (PDT) Subject: Question re ConfigParser References: <63c0f1df-404c-4e09-8605-0f8bdc6a333a@k13g2000hse.googlegroups.com> <0d5c1706-ca81-4e76-bce4-7e63ab915605@x16g2000prn.googlegroups.com> Message-ID: <75ddf31b-b2d6-4e75-b69a-6b093a32ad46@y38g2000hsy.googlegroups.com> On 20 Aug, 13:49, alex23 wrote: > On Aug 20, 5:34?pm, loial wrote: > > > Given a section like > > > [Data] > > value1 > > value2 > > value3 > > > Can ConfigParser be easily used to put the values in a dictionary? If > > so, how? > > Dictionaries are key/value pairs. Do you expect 'value1' to be a key > or a value? > > If the data is literally as you describe, and not key/value entries > (such as 'key1: value1' or 'key1=value1'), you would probably be > better off just stepping through the file, testing for the [data] > section and then reading the following lines into a list. Thanks. Thats what I did in the end From gagsl-py2 at yahoo.com.ar Tue Aug 12 01:23:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Aug 2008 02:23:46 -0300 Subject: Starting seperate programs References: Message-ID: En Thu, 07 Aug 2008 10:03:59 -0300, David Dean escribi?: > Is there a way for a python program start another python program, and > then continue, without waiting for the second program to finish? > os.startfile() seems to be what I want on windows, but I need it to work > on linux and mac as well. > Is there a function that does essentially the same as startfile, but > without needing an associtated program (i.e. asking for one)? os.system("python other_program.py") You may want to replace that "python" with sys.executable. -- Gabriel Genellina From shahmed at sfwmd.gov Thu Aug 14 11:50:57 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Thu, 14 Aug 2008 11:50:57 -0400 Subject: help with parsing email Message-ID: Hi all, I do appreciate if any one can help me for my following problem: I need to grab/parse numeric numbers such as app number from incoming emails stored in Microsoft Outlook (Microsoft Exchange server) with specified subject line. Any help with the python script is highly appreciated. The email body is like this myregion ; tst ; 11-Aug-2008 http://my.xyz.com/dddd/content/ifs/apps/myDocFolder/NoticeOfapplication/ 080612-21_test_337683.pdf I need to extract 080612-21_ number from above line from incoming emails. Thanks sk -------------- next part -------------- An HTML attachment was scrubbed... URL: From half.italian at gmail.com Thu Aug 7 11:51:00 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 7 Aug 2008 08:51:00 -0700 (PDT) Subject: Testing for the first few letters of a string References: Message-ID: try string1 = "My name is alex" string2 = "My name is alex, and I like pie" if string2.startswith(string1): process() or if you want to match a set number of characters you can use a slice: if string2[:15] == string1[:15]: process() or if you dont care where the characters appear in the string, beginning, middle, end, etc: if string2 in string1: process() Theres lots of other ways as well. http://docs.python.org/lib/string-methods.html ~Sean On Aug 7, 8:40?am, Alexnb wrote: > Okay, I have a fix for this problem, but it is messy and I think there might > be a better way. Heres an example: > > Lets say I have a string: "My name is alex" > > and I have another string "My name is alex, and I like pie". > > I want to test to see if just the "My name is alex" part is there. I don't > care about the pie part. > My first instinct was to just create a for loop and test for the string like > this: > > n = 0 > > for x in string1: > ? ? ? if string1[n] == string2[n] > ? ? ? ? ? ? n = n +0 > ? ? ? else: > ? ? ? ? ? ? break > and then later testing to see what n was = to and figuring out if it got > through the whole loop. I feel like there should be an easier way to do > this, and probably is. So Does anyone have a suggestion? > -- > View this message in context:http://www.nabble.com/Testing-for-the-first-few-letters-of-a-string-t... > Sent from the Python - python-list mailing list archive at Nabble.com. From castironpi at gmail.com Sun Aug 24 22:42:35 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 24 Aug 2008 19:42:35 -0700 (PDT) Subject: property() usage - is this as good as it gets? References: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> <9dc512a3-a0ba-461a-a242-c2681b7db42e@a8g2000prf.googlegroups.com> Message-ID: On Aug 24, 7:43?pm, alex23 wrote: > castironpi wrote: > > Python isn't as clever as you think. ?It's a language. ? > > Yet another non-sequitur response from you. At which point in my post > did I make any such claims about Python's 'cleverness'? > > > Do you want a > > link to clever code? ? > > Not if you wrote it or find it clever, no. > > To quote Kernighan: "Debugging is twice as hard as writing the code in > the first place. Therefore, if you write the code as cleverly as > possible, you are, by definition, not smart enough to debug it." > > When the code in question is one of the abstract monstrosities you > regularly post here - often in response to _new python users_ asking > _basic_ questions that _don't require metaclass solutions_ - I've > repeatedly found the cost in interpreting it is just never worth the > time and effort required. > > > I like to encourage creativity. > > Then why do you seem to stymie it? Care to go back through the > responses to your posts and tally up the "thanks, that makes sense!" > replies to the "I don't get what you mean here" ones? > > If you're seriously attempting to educate, you're failing. If you're > trying to show how blazingly clever you are, you're failing at that, > too. > > When people seem to generally consider you a markov chainer, that - > should- be a sign to work on the clarity of your communication. I'm baffled. I don't understand what you write. I think someone in my shoes would be justified in dismissing it as either malicious or a miscommunication. My typical response is, take something I've said in context, and show how it fulfills the criteria you describe. For instance, "I won't like it if you do" and "I won't think it's clever if you do" aren't consistent belief structures, they're fight structures. You have made such claims. In the post above, I make two claims, ask two questions, and encourage a brainstorm. I don't see how what you say applies to it. I am willing to change the way I communicate. I want to communicate effectively. But, until someone takes something I want to say, and says it the right way, I can't learn how. So I wait and write Python, and share my frustration with my peers. Lastly, in the syllogism you propose, "not smart enough to debug it", you equate maximally clever writing with maximally clever debugging, which is clearly wrong. They are distinct; someone could be better at either one than the other. And besides, your quoted premise "twice as hard" is assumed, not proven. From sjmachin at lexicon.net Mon Aug 18 19:35:14 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 18 Aug 2008 16:35:14 -0700 (PDT) Subject: Programming Languages Decisions References: Message-ID: <79db7bbe-a3dc-41d1-9b38-7b220116dd3c@a8g2000prf.googlegroups.com> On Aug 18, 10:59 pm, "E.D.G." wrote: > > If all goes according to plan, within a few weeks I will begin > circulating .exe copies of a Perl language disaster mitigation related > computer program that I have been developing during the past decade or so. A computer program that's related to "Perl language disaster mitigation"? I would have thought that it would take the average sentient being less than 10 *days* to nut out that the best strategy to mitigate Perl language disaster was to avoid using that language altogether. From wuwei23 at gmail.com Fri Aug 1 00:52:32 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 31 Jul 2008 21:52:32 -0700 (PDT) Subject: HELP - Attribute Error, no matter what I do on PAMIE... References: <38ed1b14-fb96-4891-9188-c62337aeef89@f36g2000hsa.googlegroups.com> Message-ID: On Aug 1, 1:00?am, frankrentef wrote: > Greetings all. I'm new to PAMIE and I've watched / followed to PAMIE > videos on Show me Do. I've tried to duplicate the "scriptWrite" > function in an attempt to automate the forms process... without > success. I haven't seen the video, bt by "duplicate the 'scriptWrite' function" do you mean you've implemented that yourself? I couldn't any such function in the PAMIE code. If so, could you throw that code into http://pastebin.com/ and link back to it here? That might help us with finding the problem. From dbickett at gmail.com Thu Aug 21 15:06:11 2008 From: dbickett at gmail.com (Daniel Bickett) Date: Thu, 21 Aug 2008 12:06:11 -0700 (PDT) Subject: Prevalent Python/Django academic software References: <3299bba4-b4fa-4c81-a5e2-b99ee4c5f8c2@w7g2000hsa.googlegroups.com> Message-ID: <4a6faa5c-663e-4ac5-bd84-c39eb3555861@l42g2000hsc.googlegroups.com> On Aug 21, 7:39 am, cla... at lairds.us (Cameron Laird) wrote: > I don't understand the question. YES, there are MANY > Python-based applications doing service in a variety > of academic contexts. No, there is no central index > of all such programs. Sorry if I was unclear. If there are many such applications, very good! I hope to use them. Certainly there seems not to be any sort of central index, which was why I hoped to hear the opinion of various c.l.py users. Tobias: No, money is not one of my objectives. Neither is paying for software, however, which is why I wondered if anyone was currently developing any relevant, open-source applications. I had not heard the name Moodle, thank you. dbickett From ramen at lackingtalent.com Thu Aug 21 01:17:35 2008 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 20 Aug 2008 22:17:35 -0700 Subject: Factory for Struct-like classes In-Reply-To: <3dec7f3e-0cd2-40ee-a4d4-74935eabae5a@k13g2000hse.googlegroups.com> References: <1N4rk.167$_s1.91@newsfe07.iad> <3dec7f3e-0cd2-40ee-a4d4-74935eabae5a@k13g2000hse.googlegroups.com> Message-ID: eliben wrote: >> Whaaa? Named tuples are being added to Python? Neat! Is there any >> documentation on this? I can't seem to find anything on the web... > > It's not easy to find unless you recall where you've seen it: > http://docs.python.org/dev/3.0/library/collections.html#collections.namedtuple Thanks! From deets at nospam.web.de Tue Aug 19 04:46:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 19 Aug 2008 10:46:26 +0200 Subject: Python Substitute for PHP GD, Resizing an image on the client side References: <02f733bb-e734-46a9-b42f-5b664cdddd3f@v26g2000prm.googlegroups.com> <6gv91bFhm5u5U1@mid.uni-berlin.de> <86256d88-2bf9-4818-9df9-d798ae9ff025@a2g2000prm.googlegroups.com> Message-ID: <6gvfkuFhki87U1@mid.uni-berlin.de> > Does anyone have any code that does the javascript "selecting the > rectangle bit" and uploading to the server. I've based my work in this field on some freely available JS, but don't know what it was called. Google is your friend here. > Also incidentally is ftp > or put the recommended way to go for uploading the reduced image to > the server? In the same way any other uploading is done in browsers when a website is involved: using HTTP POST. Use the -tag, and make sure the server-side will store a transmitted file properly. Frameworks such as TurboGears (1 or 2) and Django will do that for you. Diez From fredrik at pythonware.com Sat Aug 23 06:15:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 23 Aug 2008 12:15:06 +0200 Subject: Is my thinking Pythonic? In-Reply-To: <48ae84de$0$13858$426a34cc@news.free.fr> References: <638bf217-3eaf-43af-8604-4145aa156afe@m73g2000hsh.googlegroups.com> <39fcb558-2869-438b-9309-e55ccfed7ec6@i24g2000prf.googlegroups.com> <48add182$0$12232$426a74cc@news.free.fr> <48ae84de$0$13858$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Given the lack of proper support for the descriptor protocol in > old-style classes and a couple other diverging behaviors, I wouldn't say > that advising newcomers to use new-style classes is so pointless. Yeah, but if you don't need descriptors, new-style classes don't buy you anything (except a slight slowdown in certain situations). Dogmatic use of new-style classes (or any other "new" feature) isn't "pythonic". From anishchapagain at gmail.com Wed Aug 13 06:52:56 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Wed, 13 Aug 2008 03:52:56 -0700 (PDT) Subject: Parse error befor % token Message-ID: <7f97ab7f-4deb-491d-a729-bc7b560ff685@59g2000hsb.googlegroups.com> Hi, i tried to compile the swig .i file but am having probel with the error: parse error before % token example.i 1. %module example 2. %{ 3. #include 4. %} 5. 6. %include "header.h" i have setup.py file and am running through, >>python setup.py build_ext but is showing parse error before % token in example.i in line 1 and also in 4. Thank's for any help on this matter in advance also, is there any live example having multiple .i files in single interface SWIG file. cheer's From sjmachin at lexicon.net Sat Aug 9 17:43:36 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 9 Aug 2008 14:43:36 -0700 (PDT) Subject: Fastest way to store ints and floats on disk References: <489B41CE.8080909@shopzeus.com> <1ad14df7-09ea-4b1d-8fac-3025bdd2d522@f63g2000hsf.googlegroups.com> Message-ID: <380b121c-4595-4618-95f3-b8c50c8b39c8@k36g2000pri.googlegroups.com> On Aug 10, 4:58 am, castironpi wrote: > On Aug 7, 2:27 pm, "M.-A. Lemburg" wrote: > > > > > On 2008-08-07 20:41, Laszlo Nagy wrote: > > > > Hi, > > > > I'm working on a pivot table. I would like to write it in Python. I > > > know, I should be doing that in C, but I would like to create a cross > > > platform version which can deal with smaller databases (not more than a > > > million facts). > > > > The data is first imported from a csv file: the user selects which > > > columns contain dimension and measure data (and which columns to > > > ignore). In the next step I would like to build up a database that is > > > efficient enough to be used for making pivot tables. Here is my idea for > > > the database: > > > > Original CSV file with column header and values: > > > > "Color","Year","Make","Price","VMax" > > > Yellow,2000,Ferrari,100000,254 > > > Blue,2003,Volvo,50000,210 > > > > Using the GUI, it is converted to this: > > > > dimensions = [ > > > { 'name':'Color', 'colindex:0, 'values':[ 'Red', 'Blue', 'Green', > > > 'Yellow' ], }, > > > { 'name':'Year', colindex:1, 'values':[ > > > 1995,1999,2000,2001,2002,2003,2007 ], }, > > > { 'name':'Make', colindex:2, 'value':[ 'Ferrari', 'Volvo', 'Ford', > > > 'Lamborgini' ], }, > > > ] > > > measures = [ > > > { 'name', 'Price', 'colindex':3 }, > > > { 'name', 'Vmax', 'colindex':4 }, > > > ] > > > facts = [ > > > ( (3,2,0),(100000.0,254.0) ), # ( dimension_value_indexes, > > > measure_values ) > > > ( (1,5,1),(50000.0,210.0) ), > > > .... # Some million rows or less > > > ] > > > > The core of the idea is that, when using a relatively small number of > > > possible values for each dimension, the facts table becomes > > > significantly smaller and easier to process. (Processing the facts would > > > be: iterate over facts, filter out some of them, create statistical > > > values of the measures, grouped by dimensions.) > > > > The facts table cannot be kept in memory because it is too big. I need > > > to store it on disk, be able to read incrementally, and make statistics. > > > In most cases, the "statistic" will be simple sum of the measures, and > > > counting the number of facts affected. To be effective, reading the > > > facts from disk should not involve complex conversions. For this reason, > > > storing in CSV or XML or any textual format would be bad. I'm thinking > > > about a binary format, but how can I interface that with Python? > > > > I already looked at: > > > > - xdrlib, which throws me DeprecationWarning when I store some integers > > > - struct which uses format string for each read operation, I'm concerned > > > about its speed > > > > What else can I use? > > > >>> import marshal > > >>> marshal.dump(1, open('test.db', 'wb')) > > >>> marshal.load(open('test.db', 'rb')) > > 1 > > > It also very fast at dumping/loading lists, tuples, dictionaries, > > floats, etc. > > Depending on how hard-core you want to be, store the int, float, > string, and long C structures directly to disk, at a given offset. > Either use fixed-length strings, or implement (or find) a memory > manager. Anyone have a good alloc-realloc-free library, C or Python? A long time ago, when I last needed to bother about such things (to override the memory allocator in the DJGPP RTL), Doug Lea's malloc did the trick. A memory allocator written in Python? That's a novel concept. From bj_666 at gmx.net Mon Aug 25 17:30:13 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Aug 2008 21:30:13 GMT Subject: Private attribute References: <076a50cb-99ad-44c5-b4eb-17a45ee1abe9@c65g2000hsa.googlegroups.com> Message-ID: <6hgmj5Flo1i6U4@mid.uni-berlin.de> On Mon, 25 Aug 2008 21:44:49 +0100, Ken Starks wrote: >>> #################### >>> >>> def __getattr__(self,attrname): >>> if attrname == 'gridsize': >>> return 0.8 >>> >>> def __setattr__(self,attrname,value): >>> if attrname == 'gridsize': >>> pass >>> else: >>> self.__dict__[attrname]=value >> [?] > > I admit I haven't used properties, and had to look them up. Pretty cool > indeed ! But an extra unnecessary level of complexity for my needs > here, I feel. Compare this with your approach above and point out the extra complexity please: @property def gridsize(self): return 0.8 Ciao, Marc 'BlackJack' Rintsch From hanlray at gmail.com Tue Aug 12 04:42:26 2008 From: hanlray at gmail.com (ray) Date: Tue, 12 Aug 2008 01:42:26 -0700 (PDT) Subject: How to iterate a sequence, with skipping the first item? References: Message-ID: Thanks you guys. Now I understand the -for- loop mechanism. From cypriankumwaka at yahoo.com Wed Aug 13 01:58:38 2008 From: cypriankumwaka at yahoo.com (Cyprian Kumwaka) Date: Wed, 13 Aug 2008 05:58:38 -0000 Subject: Downloading and Installing gasp Message-ID: I am a beginner in Python. Please tell me how to go about in downloading and installing the module gasp.I am using Python 2.5.2. From bockman at virgilio.it Thu Aug 28 08:06:16 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Thu, 28 Aug 2008 05:06:16 -0700 (PDT) Subject: Python sockets UDP broadcast multicast question?? References: <57a408ba-2cfd-4b79-9832-f741a55ac18f@d1g2000hsg.googlegroups.com> Message-ID: On 28 Ago, 08:09, inorlando wrote: > Hi all, > > I have a question about python and sockets , UDP datagram in > particular. I'm new to socket programming so please bare with me. > > I am trying to write a simple application that broadcast files to > another computer on the same network/subnet but I do not want the > receiver computer to have to respond, I only want it to receive the > packet. > > So this was simple enough, but my problem is this when I send a file > that is say larger then 100K the receiver is not able to keep up with > the packets as they arrive. I get say 60 or so then the rest are > ignored. > > I have tried a couple of different approaches like threading and > queuing, ?but all ultimately have the same problem. > > So my question is how can I receive a continuous stream of UDP packets > to some kind of buffer for processing with out losing packets? > > Thank you for any help or guidance that you provide. > > - InOrlando The UDP protocol is defined 'unreliable' because it cannot guarantee in all conditions the delivery of all packets in the correct sequence. This means than in specific conditions, e.g. when the network or one of the communicating computers is overloaded, you can loose packets or receive them in the wrong order. So, first of all, if you cannon tolerate packet loss, consider switching the protocol to TCP. If you cannot change protocol (maybe because TCP has no multicast), then try to reduce the load on the computer and the network, e.g. by inserting a delay between two packet transmissions. But remember that this only reduce, does not cancel, the possibility of packet loss or packet mis-ordering. Of course, it could be a bug in your program, in which case none of the above matters ;) Ciao ----- FB From george.sakkis at gmail.com Fri Aug 29 13:42:11 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 29 Aug 2008 10:42:11 -0700 (PDT) Subject: When to use try and except? References: <8a2dd955-6641-493d-b7eb-3e29c14686a5@26g2000hsk.googlegroups.com> Message-ID: On Aug 29, 1:23 pm, cnb wrote: > If I get zero division error it is obv a poor solution to do try and > except since it can be solved with an if-clause. > > However if a program runs out of memory I should just let it crash > right? Because if not then I'd have to write exceptions everywhere to > prevent that right? > > So when would I actually use try-except? Whenever you can do something *meaningful* in the except block to handle the exception (e.g. recover). Is there any meaningful action you can take when you run out of memory ? If yes (e.g. write current data to the disk and open a popup window that informs ths user), then use try/except, otherwise don't. IOW code like the following try: ... except MemoryError: print "You ran out of memory!" is typically useless; better let the exception propagate to the top level with a full traceback. HTH, George From castironpi at gmail.com Sun Aug 24 10:12:22 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 24 Aug 2008 07:12:22 -0700 (PDT) Subject: Best way to set/get an object property References: Message-ID: On Aug 24, 5:07?am, Hussein B wrote: > Hey, > I noted that Python encourage the usage of: > -- > obj.prop = data > x = obj.prop > -- > to set/get an object's property value. > What if I want to run some logic upon setting/getting a property? > What is Python preferred method to do so (using the new feature > 'property')? > I don't think __getattr__ and __setattr__ are practical (I have to > code the property name into them). > Thanks. The answer Hussein is you have both options in Python. If neither one is clearly better-suited to your new application, pick one and go. From alan.franzoni.blahblah at example.com.invalid Fri Aug 1 11:57:10 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Fri, 01 Aug 2008 15:57:10 GMT Subject: Strong/weak typing References: <6727fa22-aee9-4a9b-b9c0-08534aab6b34@m45g2000hsb.googlegroups.com> Message-ID: <1gzggry4ihm6l.g9by2ktuome2$.dlg@40tude.net> MartinRinehart at gmail.com was kind enough to say: > I'm writing Python as if it were strongly typed, never recycling a > name to hold a type other than the original type. > > Is this good software engineering practice, or am I missing something > Pythonic? Python *is* strongly typed. You're talking about dynamic typing, but that's not about "name reuse". -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From norseman at hughes.net Wed Aug 27 17:51:17 2008 From: norseman at hughes.net (norseman) Date: Wed, 27 Aug 2008 14:51:17 -0700 Subject: finding out the number of rows in a CSV file [Resolved] In-Reply-To: References: <3aaa109e-9a7e-4d02-8af5-0161251d7678@t54g2000hsg.googlegroups.com> <0bc6097f-af52-4951-a413-e9a983df93c7@79g2000hsk.googlegroups.com> Message-ID: <48B5CC55.90308@hughes.net> Peter Otten wrote: > John S wrote: > >> [OP] Jon Clements wrote: >>> On Aug 27, 12:54 pm, SimonPalmer wrote: >>>> after reading the file throughthe csv.reader for the length I cannot >>>> iterate over the rows. How do I reset the row iterator? >> A CSV file is just a text file. Don't use csv.reader for counting rows >> -- it's overkill. You can just read the file normally, counting lines >> (lines == rows). > > Wrong. A field may have embedded newlines: > >>>> import csv >>>> csv.writer(open("tmp.csv", "w")).writerow(["a" + "\n"*10 + "b"]) >>>> sum(1 for row in csv.reader(open("tmp.csv"))) > 1 >>>> sum(1 for line in open("tmp.csv")) > 11 > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > ============================= Well..... a semantics's problem here. A blank line is just an EOL by its self. Yes. I may want to count these. Could be indicative of a problem. Besides sum(1 for len(line)>0 in ...) handles problem if I'm not counting blanks and still avoids tossing, re-opening etc... Again - it's how you look at it, but I don't want EOLs in my dbase fields. csv was designed to 'dump' data base fields into text for those not affording a data base program and/or to convert between data base programs. By the way - has anyone seen a good spread sheet dumper? One that dumps the underlying formulas and such along with the display value? That would greatly facilitate portability, wouldn't it? (Yeah - the receiving would have to be able to read it. But it would be a start - yes?) Everyone got the point? Just because it gets abused doesn't mean .... Are we back on track? Number of lines equals number of reads - which is what was requested. No bytes magically disappearing. No slight of hand, no one dictating how to or what with .... The good part is everyone who reads this now knows two ways to approach the problem and the pros/cons of each. No loosers. Steve norseman at hughes.net From fredrik at pythonware.com Tue Aug 19 05:51:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Aug 2008 11:51:37 +0200 Subject: Handling Property and internal ('__') attribute inheritance and creation In-Reply-To: References: Message-ID: Eric Brunel wrote: > To add to what others have already said, it is not only 'just extra > work', it is also quite dangerous. See: > > class A(object): > children = [] the OP is aware of that, of course: > I set anything that is constant but anything variable is set again in > __init__() as long as if you're aware of the issues involved (which you should be if you're using Python professionally), using class-level attributes is a perfectly valid Python style. From stef.mientki at gmail.com Wed Aug 20 14:37:15 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 20 Aug 2008 20:37:15 +0200 Subject: evaluating code lines above breakpoints ? Message-ID: <48AC645B.6050705@gmail.com> hello, I'm trying to create a high level debugger, based on rpd2. So when the debugger enters a breakpoint, I want to display the values of all variables in the, let's say, 5 lines above the breakpoint (if possible). Any hints on how I get a list of all vars in those lines ? My rough idea is to scan the lines, skip keywords, test type of each term ( by eval), if the term is var eval the value of it. Are there better ways ? Another idea, when hoovering over a variable during a breakpoint, a hint appears with the type and value of that var. thanks, Stef Mientki From eglyph at gmail.com Sat Aug 23 05:47:29 2008 From: eglyph at gmail.com (eglyph at gmail.com) Date: Sat, 23 Aug 2008 02:47:29 -0700 (PDT) Subject: problems debugging python script on server References: <5011f266-8c65-4507-8682-1e10d05584a7@b30g2000prf.googlegroups.com> Message-ID: > cgitb.enable() to try to find the error, but with no success. I'm > really at a loss as to why it's generating this error. Apache's error_log and access_log are your friends. In this particular case your script breaks something http-server related: premature end of headers, incorrect permissions on script, wrong interpreter script, etc. Anyway the right reason is in the http server's logs. From hanlray at gmail.com Tue Aug 12 02:51:17 2008 From: hanlray at gmail.com (ray) Date: Mon, 11 Aug 2008 23:51:17 -0700 (PDT) Subject: How to iterate a sequence, with skipping the first item? Message-ID: A container object provides a method that returns an iterator object. I need to iterate the sequence with that iterator, but need to skip the first item. I can only iterate the whole sequence with: for x in container.iterChildren(): How to skip the first item? It seems that it's a simple question. Could somebody help me? Thanks. From bdesth.quelquechose at free.quelquepart.fr Tue Aug 26 15:42:03 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 26 Aug 2008 21:42:03 +0200 Subject: dynamically adding some of one module's functions to another In-Reply-To: References: Message-ID: <48b45c9d$0$10780$426a74cc@news.free.fr> Gabriel Rossetti a ?crit : > Hello everyone, > > I'm trying to import some modules into another's namespace (network_utils) > > network_utils.py: > > import utils > import constants as main_const > from services import constants as srv_const > from plugins import constants as plg_const > > # > # Import all the message creation functions > # > f = dict([ (f, eval("utils." + f)) for f in dir(utils) if > f.startswith("create") ]) As usual, you don't need eval here. Use getattr instead: create_functions = dict( (name, getattr(utils, name) for name in dir(utils) if name.startswith('create') ) > __builtins__.update(f) Python 2.5.1 (r251:54863, Apr 6 2008, 17:20:35) [GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> __builtins__ >>> type(__builtins__) >>> __builtins__.update Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'update' >>> Anyway, adding to builtins is certainly not the best thing to do. I don't know what you're trying to do here, but looks like a very ugly mess to me. > del utils > > # > # Create a virgin namespace > # > class constants: > """ > An aggragation of L{constants}, > L{services.constants}, & > L{plugins.constants} > """ > pass > # > # Import all the constants into the new namespace > # > f = dict([ (f, eval("main_const." + f)) for f in dir(main_const) if > f.isupper() ]) > constants.__dict__.update(f) > del main_const > f = dict([ (f, eval("srv_const." + f)) for f in dir(srv_const) if > f.isupper() ]) > constants.__dict__.update(f) > del srv_const > f = dict([ (f, eval("plg_const." + f)) for f in dir(plg_const) if > f.isupper() ]) > constants.__dict__.update(f) > del plg_const Yuck. In your constants.py file, just add the relevant imports: from services.constants import * from plugins.constants import * And then in your network_utils file: import constants But this is still a mess to me. The nice point with explicit import and modules namespaces is that you at least have a chance to know where a given symbol comes from. > > now, if I import network_utils somewhere, and try to call > network_utils.myFunction() I get : > > >>> import network_utils > >>> network_utils.myFunction > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'myFunction' And ? Where is the name myFunction bound in the above code ? > but if I try to access the constants class: > > >>> from network_utils import constants > >>> constants.NO_DATA_TYPE > 'none' > > it works, how come? I suppose NO_DATA_TYPE is defined somewhere in one of your constants.py files. Instead of messing with eval and builtins and wonder why something "works" and why something else doesn't, I strongly suggest you (re)read the part about imports, packages, modules etc in the FineManual. From pythonnutter at gmail.com Wed Aug 13 23:53:06 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Thu, 14 Aug 2008 13:53:06 +1000 Subject: An FTP Client...My first real program! In-Reply-To: References: <228e4214-01cf-4152-acdb-3743594f0581@e53g2000hsa.googlegroups.com> Message-ID: sorry cut off due to original email being sent not to the list due to gmail: A second for that suggestion--the ftp module in the python standard library is very low level and not very useful for beginners as a lot of the heavy lifting and management is still left up to you, the programmer. 2008/8/14 Python Nutter : > ery low level and not very useful for beginners as a lot of the heavy > lifting and management is still left up to you, the programmer. > > The module ftputil is a high-level interface to the ftplib module. The > FTPHost objects generated from it allow many operations similar to > those of os and os.path. An example: > > # download some files from the login directory > host = ftputil.FTPHost('ftp.domain.com', 'user', 'secret') > names = host.listdir(host.curdir) > for name in names: > if host.path.isfile(name): > host.download(name, name, 'b') # remote, local, binary mode > # make a new directory and copy a remote file into it > host.mkdir('newdir') > source = host.file('index.html', 'r') # file-like object > target = host.file('newdir/index.html', 'w') # file-like object > host.copyfileobj(source, target) # similar to shutil.copyfileobj > source.close() > target.close() > > > Now if you are again purely in it for a challenge or for and > educational roller coaster ride, ignore the suggestion to look at > higher level ftp modules =) > > Cheers, > PN > From michele.simionato at gmail.com Thu Aug 7 09:59:05 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 7 Aug 2008 06:59:05 -0700 (PDT) Subject: python-mode is missing the class browser Message-ID: <6361fac8-3bfb-4d7e-b13b-84261ebeea10@b1g2000hsg.googlegroups.com> I have noticed that the python-mode for Emacs that comes with the latest Ubuntu is missing the class browser. Moreover if works differently from the python-mode I was used to (for instance CTRL-c-c works as CTRL-c-! whereas CTRL-c-! is missing, etc). How can I go back to the old python-mode or at least how do I get back the class browser? Michele Simionato From maric at aristote.info Thu Aug 28 10:31:50 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 28 Aug 2008 16:31:50 +0200 Subject: Multiple values for one key In-Reply-To: <48B602B4.5080800@hughes.net> References: <26c69b160808271326w2f53b6b8s6e4aa7f91071ac71@mail.gmail.com> <48B602B4.5080800@hughes.net> Message-ID: <200808281631.51234.maric@aristote.info> Le Thursday 28 August 2008 03:43:16 norseman, vous avez ?crit?: > Terry Reedy wrote: > > Ron Brennan wrote: > >> Hello, > >> > >> > >> How would I create a dictionary that contains multiple values for one > >> key. > > > > Make the value a collection object (set or list if you plan to add and > > delete). > > > >> I'd also like the key to be able to have duplicate entries. > > > > Dict keys must be hashable and unique. > > > > tjr > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > ================ > First part I understand, second is still giving me a problem. > > For some reason I still want keys to be dbf column headers. > like: > > name:address:zip so forth > ---- ------- --- ------------------ > guy: unknown:00000 > girl: 123 tiny street:12345 > boy:321 here:33333 > gal:999 over there: 55555 > so forth > > Thus one key has many values. And you can then index on whatever key(s) > you wish - name,zip... > > With billions plus records, trying to put a unique key on each entry > seems to preclude the need for a dictionary, just use the entries. > (Format to SDF and index on substr(line,1,24)+substr(line,48,+5) etc..) > name + zip > OK - I know I missed the whole concept of a Python Dictionary. I haven't > read anything as yet that gives a clear picture of what it is and what > it is for. Please, classroom concepts usually consist of a handful of > objects. I have files here that takes up multiple DVDs each, AFTER a 15 > to 1 compression. 3 bytes per pixel. I need to work with them. Things > like changing geobase projections and cookie cutting based on real world > coordinates and modifying the lumens and so forth. Based on what I've > read, the Python Dictionary concept flat will not work for such as this. > Yes - the example is overkill. But in my world it is reality. I deal > with sizeable things. Not all are raster. Most all are binary! Things > that work on massive text files - like banking and mortgage - simply > don't work here. There are seldom 'lines'. There are always bytes. Lots > of bytes. Things that form a group are not necessarily stored sequentially. > > Back to What Is A Python Dictionary: Somebody please enlighten me. > Disctionaries are hash tables with a unique key and constant time lookup. What you want could be implemented as a complex data structures with as many dict as needed keys, but it seems you really want a relational table and a rdbms. This is exactly what they are for. A short example with the new python2.5 sqlite package : >>>[107]: import sqlite3 >>>[108]: from string import letters >>>[109]: db = sqlite3.connect(':memory:') >>>[110]: db.execute("create table 'table1' ('name' text(20), 'address' text(100), primary key ('name', 'address'))") ...[110]: >>>[111]: db.executemany("insert into 'table1' values (?, ?)", ((letters[i%len(letters)]*i, "%d street" % i) for i in range(1000))).rowcount ...[111]: 1000 >>>[112]: for i in db.execute("select * from 'table1' where address like '99 %'") : print i .....: (u'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV', u'99 street') >>>[113]: for i in db.execute("select * from 'table1' where name like '___'") : print i .....: (u'ddd', u'3 street') >>>[114]: db.execute("insert into 'table1' values (?, ?)", ('ddd', '4 street')).rowcount ...[114]: 1 >>>[115]: for i in db.execute("select * from 'table1' where name like '___'") : print i .....: (u'ddd', u'3 street') (u'ddd', u'4 street') >>>[116]: db.execute("insert into 'table1' values (?, ?)", ('ddd', '4 street')).rowcount --------------------------------------------------------------------------- IntegrityError Traceback (most recent call last) /home/maric/ in () IntegrityError: columns name, address are not unique > > Steve > norseman at hughes.net > -- > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud From kmathew at envivio.fr Sat Aug 16 17:20:52 2008 From: kmathew at envivio.fr (Kurien Mathew) Date: Sat, 16 Aug 2008 23:20:52 +0200 Subject: Good python equivalent to C goto Message-ID: <48a744b6$0$299$7a628cd7@news.club-internet.fr> Hello, Any suggestions on a good python equivalent for the following C code: while (loopCondition) { if (condition1) goto next; if (condition2) goto next; if (condition3) goto next; stmt1; stmt2; next: stmt3; stmt4; } Thanks Kurien From sjmachin at lexicon.net Tue Aug 5 05:00:31 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 5 Aug 2008 02:00:31 -0700 (PDT) Subject: UnicodeDecodeError, how to elegantly deal with this? References: Message-ID: <85c55895-eea2-487c-baa6-6b72f0a4afc6@l33g2000pri.googlegroups.com> On Aug 5, 4:23 am, "Jorgen Bodde" wrote: > Hi All, > > I am relatively new to python unicode pains and I would like to have > some advice. I have this snippet of code: > thefile = args["file"] > filemask = u"%file%" > therep = arg.replace(filemask, thefile) ##### error here > It crashes on this: > > 20:03:49: File > "D:\backup\important\src\airs\webserver\webdispatch.py", line 117, in > playFile therep = arg.replace(filemask, thefile) > > 20:03:49: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in > position 93: ordinal not in range(128) > > 20:03:49: Unhandled Error: : > 'ascii' codec can't decode byte 0xc2 in position 93: ordinal not in > range(128) > > It chokes on a ` character in a file name. I read this file from disk, > and I would like to play it. However in the replace action it cannot > translate this character. How can I transparently deal with this issue > because in my eyes it is simply replacing a string with a string, and > I do not want to be bothered with unicode problems. I am not sure in > which encoding it is in, but I am not experienced enough to see how I > can solve this If you don't want to be bothered with "unicode problems": (1) Don't create a "unicode problem" when one doesn't exist. (2) Don't bother other people with *your* "unicode problems". > > Can anybody guide me to an elegant solution? > Short path: In this case, less is more; remove the u prefix in the line filemask = u"%file%" Long Path: Ignorance is not bliss. Lose the attitude. Unicode is your friend, not an instrument of Satan. Read this: http://www.amk.ca/python/howto/unicode By the way, how one's filesystem encodes file names can be a good thing to know; in your case it appears to be UTF-8. HTH, John From elessar at nienna.org Tue Aug 26 16:47:45 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Tue, 26 Aug 2008 14:47:45 -0600 Subject: Programmatically exit the REPL In-Reply-To: <48B35768.80304@nienna.org> References: <288810.50426.qm@web7904.mail.in.yahoo.com> <48B35768.80304@nienna.org> Message-ID: <48B46BF1.20408@nienna.org> Matthew Fitzgibbons wrote: > I've got a pretty complex interactive command line program. Instead of > writing my own REPL, I'm using the Python interpreter (an infinitely > better solution). This program has two threads, a background thread and > the REPL thread. When you call quit() or sys.exit() in the REPL thread, > everything is perfectly happy. However, the background thread does some > long-running jobs, and I want it to have the ability to exit the program > when the job is complete. When I call quit() or sys.exit() from the > background thread, the REPL merrily continues on its way. > > This is a very frustrating problem, so I'm hoping someone can shed some > light on it. Am I missing something simple? Or is this just impossible? > I don't see anything about breaking out of interact() in the code module > docs. > > > Here's a minimal example: > > #!/usr/bin/env python -i > # You get the same behavior using code.interact() > > import sys > import time > import threading > > def end_the_program(): > # works if you call it from the REPL thread, > # but not the background thread > print "called end_the_program()" > sys.exit() > # quit() # using quit() rather than sys.exit() > # results in identical behavior > > keep_going = True > def runner(): > while keep_going: > time.sleep(0.1) > end_the_program() > threading.Thread(target=runner).start() > > # end example > > > Here's the console session (edited for clarity): > > Desktop$ ./exit_repl.py > >>> keep_going = False > called end_the_program() > # notice we didn't exit here > >>> end_the_program() > called end_the_program() > # but we did exit here > Desktop$ > > > -Matt > Here's a modified example that _almost_ works: #!/usr/bin/env python import code import time import threading keep_going = True def runner(): while keep_going: time.sleep(0.1) ic.push("quit()") # this will exit the InteractiveConsole loop! threading.Thread(target=runner).start() ic = code.InteractiveConsole(locals()) ic.interact("InteractiveConsole") # end example It uses code.InteractiveConsole instead of python -i. When you push "quit()" to the InteractiveConsole, the loop exits, but the raw_input call is still blocking. Argh! Console session: Desktop$ ./exit_repl.py && echo done InteractiveConsole >>> keep_going = False >>> done Desktop$ Does anyone know how to make raw_input think it has gotten input? -Matt From abesto0 at gmail.com Sat Aug 2 08:45:42 2008 From: abesto0 at gmail.com (=?ISO-8859-1?Q?Zolt=E1n_Nagy?=) Date: Sat, 02 Aug 2008 14:45:42 +0200 Subject: Multiline text in XML file In-Reply-To: References: Message-ID: King wrote: > Is there any other way to define multiline text in a XML file: > > multiline > multiline > multiline > multiline > ... > ]]> > Unless someone has to edit the XML manually (which is bad anyway): first line\nsecond line From gagsl-py2 at yahoo.com.ar Wed Aug 20 02:46:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 20 Aug 2008 03:46:14 -0300 Subject: Newbie question about sending and receiving data to the command prompt. References: <73045cca0808191248o47d315d5wb9780b92e17dc684@mail.gmail.com> Message-ID: En Tue, 19 Aug 2008 16:48:26 -0300, aditya shukla escribi?: > I am using windows vista and i am trying to send data to the command > prompt > ,this is what is done. > > import subprocess > proc =subprocess.Popen('cmd.exe',stdin=subprocess.PIPE) > proc.communicate('abc') > when i run this the command prompt just blinks and disappears , can > anyone > explain what's going on? I don't have a Vista machine to test right now, but I'd expect the above sequence to hang indefinitely. If you want to execute something, don't forget the final \n On XP this works fine: import subprocess proc =subprocess.Popen('cmd.exe',stdin=subprocess.PIPE,stdout=subprocess.PIPE) output = proc.communicate('dir\n')[0] print repr(output) -- Gabriel Genellina From exarkun at divmod.com Fri Aug 22 14:32:27 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 22 Aug 2008 14:32:27 -0400 Subject: How to read and write the same socket in different threads? In-Reply-To: <4e307e0f0808221125j3083500bu2def39b8bf609a9d@mail.gmail.com> Message-ID: <20080822183227.29191.1770886464.divmod.quotient.17478@ohm> On Sat, 23 Aug 2008 02:25:17 +0800, Leo Jay wrote: >On Sat, Aug 23, 2008 at 1:58 AM, Jean-Paul Calderone wrote: >> On Sat, 23 Aug 2008 01:47:23 +0800, Leo Jay wrote: >>> >>> I'd like to read and write the same socket in different threads. >>> one thread is only used to read from the socket, and the other is only >>> used to write to the socket. >>> But I always get a 10022 'Invalid argument' exception. Anyone knows why? >>> >>> I'm using windows xp. >>> >>> my source code is here: >>> http://pastebin.com/m23e633a2 >>> >> >> You're connecting and accepting with the same socket. That's not a very >> good thing to do. You're not even reading and writing on the same socket, >> since you're writing to the socket which you get from accept (if the code >> could get that far). >> > >not exactly. the socket connecting to port 1 is listening to port 2. >port 1 and port 2 are not the same. No - it's just what I said. create_socket creates one socket and passes it to read_socket and write_socket. read_socket calls connect on the socket it is passed. write_socket calls accept on the socket it is passed. So a single socket has connect and accept called on it. Now, main does call create_socket twice, so this does happen to two sockets, but it's broken in each case. > >> What are you trying to do? Why are you connecting and accepting? Why do >> you need two threads? >> > >I'm migrating a java module to python. In the java code, after >creating a socket, >the code gets an InputStream and an OutputStream from that socket, >sends and receives data in different threads. >So I just want to do the same thing. (at least do the same thing >currently, I don't want to change all related projects at the same >time.) Two threads per socket is a bad design. :( > >> Have you seen Twisted? http://twistedmatrix.com/ >> > >not yet, but it seems that it's quite a complicated module, isn't it? >is it possible to get the work done without adopting such a monster? :) > It's complicated so that applications using it don't have to be. It's easier to write network code with Twisted than with the socket and threading modules. Jean-Paul From tom1189 at removethis.verizon.net Sun Aug 24 12:47:34 2008 From: tom1189 at removethis.verizon.net (tom) Date: Sun, 24 Aug 2008 16:47:34 GMT Subject: Filling in Degrees in a Circle (Astronomy) In-Reply-To: References: Message-ID: >> http://matplotlib.sourceforge.net/ >> > I'm using Python 2.4. The install looks pretty complicated for Windows. > It doesn't seem like matplotlib is a module. > Maybe going with the enthought edition would be easiest for you as it is a very complete set of tools all in one package. It's at http://www.enthought.com/products/epd.php These are really nice tools for scientific (and other) data analysis, and are very competitive with most professional packages. There are other bundles as well, like Sage. I've always used enthought. On the other hand, I think making tools that use these in a bundled exe might be more difficult, and if possible, might not be consistent with their license agreements, and might make for large packages. I never really looked into this. Also, with matplotlib, you might just try installing it without anything else and see how it goes. Just download the exe and double-click, or the egg file and do whatever one does with those. I bet it will work... I think it will just default to using Tk for the GUI, which you already have installed with Python, and it won't use agg (an anti-aliasing library), so your plots won't be quite as pretty. But they'll still be nice, and it will likely work. From adrian_p_smith at yahoo.com Tue Aug 26 18:30:28 2008 From: adrian_p_smith at yahoo.com (Adrian Smith) Date: Tue, 26 Aug 2008 15:30:28 -0700 (PDT) Subject: smart quotes References: <4188c027-3c64-429b-a1e6-a1f3a79060e8@a3g2000prm.googlegroups.com> Message-ID: <672a2ddc-a2ce-499a-b506-8eeb5ba4d578@a2g2000prm.googlegroups.com> On Aug 26, 4:13?pm, Peter Otten <__pete... at web.de> wrote: > Adrian Smith wrote: > > Can anyone tell me how to get rid of smart quotes in html using > > Python? I've tried variations on > > stuff = string.replace(stuff, "\?", "\""), but to no avail, presumably > > because they're not standard ASCII. > > Convert the string to unicode. For that you have to know its encoding. I > assume UTF-8: > > >>> s = "a ?smart quote? example" > >>> u = s.decode("utf-8") > > Now you can replace the quotes (I looked up the codes in wikipedia): > > >>> u.replace(u"\u201c", "").replace(u"\u201d", "") > > u'a smart quote example' > > Alternatively, if you have many characters to remove translate() is more > efficient: > > >>> u.translate(dict.fromkeys([0x201c, 0x201d, 0x2018, 0x2019])) > > u'a smart quote example' > > If necessary convert the result back to the original encoding: > > >>> clean = u.translate(dict.fromkeys([0x201c, 0x201d, 0x2018, 0x2019])) > >>> clean.encode("utf-8") > > 'a smart quote example' > > Peter Brilliant, thanks! From larry.bates at vitalEsafe.com Thu Aug 21 19:29:34 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Thu, 21 Aug 2008 18:29:34 -0500 Subject: 'While' question In-Reply-To: References: Message-ID: Ben Keshet wrote: > Thanks for the reference. I tried it with a general example and got it > to work - I used an index that counts up to a threshold that is set to > break. It does not work though with my real code. I suspect this is > because I cannot really read any lines from an empty file, so the code > gets stuck even before I get to j=j+1: > > line = f.readline()[:-1] > j=0 > while 'PRIMARY' not in line: > line = f.readline()[:-1] > j=j+1 if j==30: > break > Any suggestions? > > BK > > > Wojtek Walczak wrote: >> On Thu, 21 Aug 2008 18:01:25 -0400, Ben Keshet wrote: >> >>> somehow. I use 'while 'word' not in line' to recognize words in the >>> texts. Sometimes, the files are empty, so while doesn't find 'word' >>> and runs forever. I have two questions: >>> 1) how do I overcome this, and make the script skip the empty files? >>> (should I use another command?) >>> 2) how do I interrupt the code without closing Python? (I have >>> ActivePython) >>> >> >> Try the docs first. You need to read about 'continue' and >> 'break' statements: http://docs.python.org/tut/node6.html >> >> HTH. >> >> > You might consider turning this around into something like: for j, line in enumerate(f): if 'PRIMARY' in line: continue if j == 30: break IMHO this is MUCH easier to understand. -Larry From pavlovevidence at gmail.com Fri Aug 22 23:13:02 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 22 Aug 2008 20:13:02 -0700 (PDT) Subject: Filling in Degrees in a Circle (Astronomy) References: Message-ID: On Aug 22, 7:12?pm, "W. eWatson" wrote: > Is there some simple operational device in Python that would allow me to > create an array (vector) of 360 points from my data by interpolating between > azimuth points when necessary? All my data I rounded to the nearest integer. > Maybe there's an interpolation operator? There's nothing built in, but see the bisect module. It is a good way to determine which interval you are in, and you can interpolate the points yourself. Carl Banks From joefazee at gmail.com Fri Aug 8 14:47:36 2008 From: joefazee at gmail.com (A. Joseph) Date: Fri, 8 Aug 2008 11:47:36 -0700 Subject: I need a Python mentor Message-ID: *Please the first message i sent out contain error, i`m very very sorry.* Hello everybody, i`m new to this list. I was programming in PHP before, so just of recent I started learning python. I need someone who I can be giving me some assignment based on the chapter I read in the book, and tell person will sometime review my code and tell me if it well structured. Can you be my mentor? Abah Josep -------------- next part -------------- An HTML attachment was scrubbed... URL: From Shawn at Milochik.com Wed Aug 6 14:17:45 2008 From: Shawn at Milochik.com (Shawn Milochik) Date: Wed, 6 Aug 2008 14:17:45 -0400 Subject: Monitor and compare two log files in real time In-Reply-To: <6f11115b-6f19-4ca4-97e6-0a0781ed617c@b30g2000prf.googlegroups.com> References: <6f11115b-6f19-4ca4-97e6-0a0781ed617c@b30g2000prf.googlegroups.com> Message-ID: <2dc0c81b0808061117h2c24fc6emd112893f957b91fb@mail.gmail.com> Can you be more specific? That will also help you write your requirements, which will lead to your pseudo code and then your code. Do you want to search for a a pre-defined string (or set of strings), or just look for anything matching a pattern to appear in the first file? Related question: Can that string appear anywhere in the second file, or does it have to appear in a certain pattern (at the beginning of a line, followed by a colon or the word "error" or something? Do the log entries have timestamps, or will you be capturing the time your script found the string in file 1? What will you do if the script must be restarted and "forgets" what it found in the past eight minutes? If you're feeling ambitious, write some code. Figure out how to: 1. Read a file. 2. Locate the value(s) you are looking for and retain them somehow. Once you can do those two things, you can easily read the second file and seek the values you already found. A few lines to handle the eight-minute rule, and you're almost done. Post back when you have some code written. ShawnMilo From benjamin.kaplan at case.edu Tue Aug 5 19:38:00 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 5 Aug 2008 19:38:00 -0400 Subject: pyprocessing/multiprocessing for x64? In-Reply-To: <5cqdnSE547L0QgXVnZ2dnUVZ_sLinZ2d@comcast.com> References: <5cqdnSE547L0QgXVnZ2dnUVZ_sLinZ2d@comcast.com> Message-ID: On Tue, Aug 5, 2008 at 7:16 PM, pigmartian wrote: > I recently learned (from I response on this newsgroup to an earlier query) > of the processing module for working with subprocesses in a similar manner > to threading. For what I needed to do, it worked great --- until I tried to > run my code on an x64 box, for which that module isn't available*. So, I'm > just wondering if when processing is renamed to multiprocessing and included > in the standard lib for 2.6, will x64 be supported? > > > ~Scott > > *yes, yes, I know. download the source and compile it myself. > I'm not an expert on this, but I think that anything written for x86 (32 bit) machines can run on x64 machines. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 7 11:30:22 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 07 Aug 2008 17:30:22 +0200 Subject: python-mode is missing the class browser In-Reply-To: <6361fac8-3bfb-4d7e-b13b-84261ebeea10@b1g2000hsg.googlegroups.com> References: <6361fac8-3bfb-4d7e-b13b-84261ebeea10@b1g2000hsg.googlegroups.com> Message-ID: <489b1509$0$3481$426a74cc@news.free.fr> Michele Simionato a ?crit : > I have noticed that the python-mode for Emacs that comes with the > latest Ubuntu is missing the class browser. Moreover if works > differently from the python-mode I was used to (for instance CTRL-c-c > works as CTRL-c-! whereas CTRL-c-! is missing, etc). How can I go back > to the old python-mode > or at least how do I get back the class browser? I'm not really up2date wrt/ my ubuntu station here, but I remember having seen this somewhat different (emacs-provided IIRC) python-mode which I didn't like. I don't quite remember what I did, but I can at least tell you what I have actually have: - in /usr/share/emacs/site-lisp/python-mode/python-mode.el : the 'true' python-mode which header goes like this: """ ;;; python-mode.el --- Major mode for editing Python programs ;; Copyright (C) 1992,1993,1994 Tim Peters ;; Author: 2003-2006 http://sf.net/projects/python-mode ;; 1995-2002 Barry A. Warsaw ;; 1992-1994 Tim Peters ;; Maintainer: python-mode at python.org ;; Created: Feb 1992 ;; Keywords: python languages oop (defconst py-version "$Revision: 4.78 $" "`python-mode' version number.") """ - in /usr/share/emacs/22.0.91/site-lisp/python-mode/ : the corresponding byte-compiled python-mode.elc - in /etc/emacs/site-start.d/ : a 50python-mode.el file that reads: """ ;-*-emacs-lisp-*- (autoload 'python-mode "python-mode" "Python editing mode." t) (autoload 'py-shell "python-mode" "Interactive Python interpreter." t) (autoload 'doctest-mode "doctest-mode" "Python doctest editing mode." t) (setq load-path (append (list (concat "/usr/share/" (symbol-name debian-emacs-flavor) "/site-lisp/python-mode") (concat "/usr/share/" (symbol-name debian-emacs-flavor) "/site-lisp/pymacs") ) load-path)) (setq auto-mode-alist (append (list '("\\.py$" . python-mode) '("SConstruct$" . python-mode) '("SConscript$" . python-mode) ) auto-mode-alist)) (setq interpreter-mode-alist (append (list '("python" . python-mode) '("python2.1" . python-mode) '("python2.2" . python-mode) '("python2.3" . python-mode) '("python2.4" . python-mode) '("python2.5" . python-mode) ) interpreter-mode-alist)) """ emacs-version : GNU Emacs 22.0.91.1 (i486-pc-linux-gnu, GTK+ Version 2.10.6) of 2006-12-20 on rothera, modified by Debian ubuntu Feisty Fawn (7.04) FWIW and talking about class-browser, there's the IMHO very excellent emacs-code-browser too. HTH From Edwin.Madari at VerizonWireless.com Thu Aug 14 11:06:42 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Thu, 14 Aug 2008 11:06:42 -0400 Subject: Fixed-length text file to database script In-Reply-To: Message-ID: <20080814150654.32B5D1E4019@bag.python.org> here is a working code snippet to read from MySQL db. python tutorial has examples of reading from files. put them together to do your task. =================================================== import MySQLdb con = MySQLdb.connect(host='127.0.0.1', port=4321, user='joe', passwd='shmoe', db='tst') cursor = con.cursor() sql = 'select * from YOUR_TABLE' cursor.execute(sql) results = cursor.fetch() con.close() ===================================================== hope that helps. good luck Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of Diez B. Roggisch Sent: Thursday, August 14, 2008 7:11 AM To: python-list at python.org Subject: Re: Fixed-length text file to database script Stacey wrote: > Hi Guys, > > I'm new to Python (mostly) and I'm wanting to use it for a new project > I'm faced with. > > I have a machine (PLC) that is dumping its test results into a > fixed-length text file. I need to pull this data into a database > (MySQL most likely) so that I can access it with Crystal Reports to > create daily reports for my engineers. > > I've been reading the Python manual for about a week now and I'm > learning a lot. Unfortunately, I was given a deadline today that I > cannot meet without a little help. > > I need to know how to write a script that will DAILY pull this text > file into a MySQL database. > > Can anyone show me how to do this? Show us code & data, and we show you how to improve the code. Or would you be able to write the script with the above information? Diez -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From rschroev_nospam_ml at fastmail.fm Sun Aug 17 15:19:37 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 17 Aug 2008 21:19:37 +0200 Subject: how many nested for can we utilize? In-Reply-To: References: <27cbc0fa0808152200l4be2ca5gc24d8b01458b6e62@mail.gmail.com> Message-ID: Nick Dumas schreef: > A good quote I read (I can't remember who it was from, though) is "If > you need more than three levels of indentation, then something is > seriously wrong with your code." Possibly Guido himself? Linus Torvalds in the Linux kernel coding style document: "[...] The answer to that is that if you need more than 3 levels of indentation, you're screwed anyway, and should fix your program." (http://lxr.linux.no/linux/Documentation/CodingStyle) -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From clp at rebertia.com Sun Aug 31 21:50:24 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 31 Aug 2008 18:50:24 -0700 Subject: Some problems with classes In-Reply-To: References: Message-ID: <47c890dc0808311850i577a7e3drd09b43dc2481bc68@mail.gmail.com> On Sun, Aug 31, 2008 at 6:39 PM, ssecorp wrote: > Why/how is it possible to add variables like this? I don't understand > this mechanism: > http://docs.python.org/tut/node11.html#SECTION0011330000000000000000 Under the covers, Python objects are implemented using dictionaries, so adding an attribute just adds a new key-value pair to the object's internal dictionary (which, incidentally, you can access as someobj.__dict__). > > class Employee: > pass > > john = Employee() # Create an empty employee record > > # Fill the fields of the record > john.name = 'John Doe' > john.dept = 'computer lab' > john.salary = 1000 > > --------------------------------------------------------------------------- > > Also, I can't get multiple inheritance to work. > > Don't mind that the a vegan obviously don't inherit from an animal and > a vegetable. I didn't come up with anything better, it is just to > learn about inheritance. > > > class Animal(object): > def __init__(self, name, weight): > self.name = name > self.weight = weight > > def speak(self): > print "speak" > > class Vegetable(object): > def __init__(self, name, volume): > self.name = name > self.volume = volume > > def split(self): > print "tjoff" > > class Vegan(Animal, Vegetable): > #pass > def __init__(self, name, attacks): > self.name = name > self.attacks = attacks > >>>> > > Traceback (most recent call last): > File "C:/Python25/Progs/XXXX/Movie.py", line 42, in > class ActionComedy(Movie, ActionMovie): > TypeError: Error when calling the metaclass bases > Cannot create a consistent method resolution > order (MRO) for bases Movie, ActionMovie The class names in error message here don't match the classes you declared above. Give us the actual code you're using or at least a stub version. >>>> > > > also, when inheriting, can I inherit __init__() somehow? If I want the > same attributes but perhaps some additional methods for example. Use super() to call your superclasses' __init__() methods. See super()'s entry in http://docs.python.org/lib/built-in-funcs.html for more info. - Chris > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From victoryforever83 at gmail.com Wed Aug 6 00:43:38 2008 From: victoryforever83 at gmail.com (victory_forever_83) Date: Tue, 5 Aug 2008 21:43:38 -0700 (PDT) Subject: i Covert my car from gas fuel to water fuel Message-ID: <39f467c8-ba83-49b9-b4bf-f5ef55c03bcb@e39g2000hsf.googlegroups.com> HI Do you have a car ? Does gas and fuel price driving you crazy ? Do you want to SAVE 60% of your car fuel ? Do you want to help solve the Global Warming problem ? if yes so you Want to Covert you car from gas fuel to water fuel **not a necessary to have a technical knowledge** We will lead you to Convert Your Car/Truck to BURN WATER as well as Gasoline and BOOST YOUR GAS MILEAGE!!! SEE on YOUTUBE 1- http://www.youtube.com/v/GmhQ31Pu-78&hl=en&fs=1 2- http://www.youtube.com/v/wqlLuifrHQs&hl=en&fs=1 Our Offer 1-How to Save Tons of Fuel With Your Water-Hybrid (E-Book) 2-Modify Your Car to Save Gas USING WATER (E-Book) the two e-books now for only $97, one-time charge. Also give you the FREE updates at no extra charge. Click to See http://goofiy2k.water4gas.hop.clickbank.net/ Dont Forget That You Have ** 60 Day 100% Full Money Back ** From drkjam at gmail.com Fri Aug 22 12:18:31 2008 From: drkjam at gmail.com (David Moss) Date: Fri, 22 Aug 2008 09:18:31 -0700 (PDT) Subject: property() usage - is this as good as it gets? Message-ID: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> Hi, I want to manage and control access to several important attributes in a class and override the behaviour of some of them in various subclasses. Below is a stripped version of how I've implemented this in my current bit of work. It works well enough, but I can't help feeling there a cleaner more readable way of doing this (with less duplication, etc). Is this as good as it gets or can this be refined and improved especially if I was to add in a couple more attributes some fairly complex over-ride logic? #!/usr/bin/env python class A(object): def __init__(self): self._x = None self._y = None def _set_x(self, value): self._x = value def _get_x(self): return self._x x = property(_get_x, _set_x) def _set_y(self, value): self._y = value def _get_y(self): return self._y y = property(_get_y, _set_y) class B(A): def __init__(self): self._z = None super(B, self).__init__() def _set_x(self, x): # An example subclass 'set' override. if x == 10: raise Exception('%r is invalid!' % x) self._x = x x = property(A._get_x, _set_x) def _set_z(self, value): self._z = value def _get_z(self): return self._z z = property(_get_z, _set_z) del A._get_x, A._set_x, A._get_y, A._set_y del B._set_x, B._get_z, B._set_z From norseman at hughes.net Tue Aug 12 13:48:15 2008 From: norseman at hughes.net (norseman) Date: Tue, 12 Aug 2008 10:48:15 -0700 Subject: Broken examples In-Reply-To: <48A0E04B.1040006@probo.com> References: <48A0DAF6.4040207@hughes.net> <48A0E04B.1040006@probo.com> Message-ID: <48A1CCDF.50302@hughes.net> Tim Roberts wrote: > norseman wrote: >> Tim; >> Finally got a chance to test your snippet. Thank you for it! >> >> I took the liberty of flushing it out a bit. >> ================ >> #!/--- >> # >> import os >> import win32com.client >> >> excel = win32com.client.Dispatch( 'Excel.Application' ) >> excel.Visible=1 # shows the spreadsheet (can be handy) >> xlCSV = 6 >> # substitute for list generation >> list = ["c:\\temp\\test.xls", "c:\\temp\\test1.xls"] >> >> for nm in list: >> csv = os.path.splitext( nm )[0] + '.csv' >> print "Procesing file:", csv >> if os.path.exists(csv): # window$ won't auto overwrite >> os.unlink(csv) >> wb = excel.Workbooks.Open( nm ) >> wb.SaveAs( csv, xlCSV ) >> print wb.Close() # requires manual verification >> # eliminating unattended runs >> >> #wb.Exit() & wb.Quit() # generate ERROR(s) - no such thing(s) >> # leaving Excel open >> >> excel.Visible=0 # actually closes Excel if no sheet open >> # verified via task manager >> >> print "Check to see if this worked." >> >> # end of file >> ================= >> The above does in fact work. >> Using the above I have a few questions. >> Documentation on xlCSV came from where? >> " on .Workbooks.Open(file.xls) came from ??? >> " on .SaveAs( filename, xlCSV ) came from ??? >> " on .Close() came from ??? > > MSDN has rather extensive documentation on the Excel object model, > although it is somewhat spread out. Search for "Excel object model". > > I cheated on xlCSV. That's the name of the symbol, and I believe it > will even be available as win32com.client.constants.xlCSV after you > instantiate the application, but I just searched the web for "xlCSV" and > hard-coded the 6. > > >> Tell me about the lack of the .Exit() and/or .Quit(), please. > > Workbooks don't exit or quit. Workbooks can be closed, but exit is > something that applies to the application (excel, in your case). You > should also be able to say > excel = None > to get rid of the app. > > >> I ran out of time today. Is it possible to send something like an >> keystroke to a Window () box if it accepts same from >> actual keyboard? May not work anyway since .Close() hangs (in >> interactive) awaiting it's answer. > > The Workbook.Close method accepts parameters; you should be able to get > it to skip the dialog. I believe that wb.Close( False ) should do this. > ============== The wb.Close( False) works as predicted. The excel = None leaves Excel open. excel.Visible=0 does close it so I'm OK. excel.Quit() is probably the better choice. (learned via a comment above + Trial & Error) For the next person that might have need of this: >>>>>>>>>> tested/working final snippet #!/--- # import os import win32com.client excel = win32com.client.Dispatch( 'Excel.Application' ) excel.Visible=0 #=1 shows the spreadsheet (can be handy) xlCSV = 6 # substituted for list generation list = ["c:\\temp\\test.xls", "c:\\temp\\test1.xls"] # for nm in list: csv = os.path.splitext( nm )[0] + '.csv' print "Procesing file:", csv if os.path.exists(csv): # window$/Win-DOS won't auto overwrite os.unlink(csv) wb = excel.Workbooks.Open( nm ) wb.SaveAs( csv, xlCSV ) wb.Close( False ) # excel.Quit() # doing it right # print "Do a dir *.csv check to see if this worked." # end of file >>>>>>>>>>>>> Using the Python supplied CSV module now makes handling a variety of .xls files a real snap. "Variety" of real spread sheet types, yes. The butchered type that should have been done in Word - probably never. Thanks again! Steve norseman at hughes.net From bsder at allcaps.org Sat Aug 2 02:35:20 2008 From: bsder at allcaps.org (Andrew Lentvorski) Date: Fri, 01 Aug 2008 23:35:20 -0700 Subject: Interconvert a ctypes.Structure to/from a binary string? Message-ID: <48940028.8080201@allcaps.org> Basically, I'd like to use the ctypes module as a much more descriptive "struct" module. Is there a way to take a ctypes.Structure-based class and convert it to/from a binary string? Thanks, -a From bedouglas at earthlink.net Sun Aug 31 16:36:48 2008 From: bedouglas at earthlink.net (bruce) Date: Sun, 31 Aug 2008 13:36:48 -0700 Subject: parsing "&A" in a string.. In-Reply-To: Message-ID: <0d7e01c90ba9$4b8e10f0$0301a8c0@tmesa.com> Hi Fredrick Thanks for the reply. But since I don't have control of the initial text, is there something with python that will strip/replace this... or are you saying I should do a search/replace on the "&" char with the "amp&;" prior to parsing?? -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Fredrik Lundh Sent: Sunday, August 31, 2008 1:10 PM To: python-list at python.org Subject: Re: parsing "&A" in a string.. bruce wrote: > a pretty simple question, i'm guessing. > > i have a text/html string that looks like: > ....(A&E) > > the issue i have is that when i parse it using xpath/node/toString, > i get the following > > ...(A&E;). that's because your parser is interpreting the &E part as an entity reference, and the serializer is then adding the missing semicolon. bare ampersands must be written as "&" in the file. -- http://mail.python.org/mailman/listinfo/python-list From tjreedy at udel.edu Wed Aug 27 19:56:54 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 27 Aug 2008 19:56:54 -0400 Subject: Multiple values for one key In-Reply-To: <26c69b160808271326w2f53b6b8s6e4aa7f91071ac71@mail.gmail.com> References: <26c69b160808271326w2f53b6b8s6e4aa7f91071ac71@mail.gmail.com> Message-ID: Ron Brennan wrote: > Hello, > > > How would I create a dictionary that contains multiple values for one > key. Make the value a collection object (set or list if you plan to add and delete). > I'd also like the key to be able to have duplicate entries. Dict keys must be hashable and unique. tjr From bhood2 at comcast.net Tue Aug 26 00:11:10 2008 From: bhood2 at comcast.net (bhood2 at comcast.net) Date: Mon, 25 Aug 2008 22:11:10 -0600 Subject: Need help with extension modules built in debug mode Message-ID: I've come to the conclusion that posting about Embedded Python on the Python forums is a complete waste of time. I hope I can get some useful insights here. I'm looking for some help with extension modules built using Visual Studio. I'm using the simple extension module example "hello" (taken from the "Programming Python" book). I'm building it successfully in both release and debug mode using a Visual Studio project. I can successfully import the release build of the module into the release build of Python. For example: [E:\]python Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import hello >>> hello.message("Bob") 'Hello, Bob' >>> quit() I cannot, however, load the debug build of the exact same code (stored in the exact same location) into the debug build of Python: [E:\]python_d Python 2.5.1 (r251:54863, Jun 5 2007, 10:17:28) [MSC v.1400 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import hello Traceback (most recent call last): File "", line 1, in ImportError: No module named hello [26848 refs] >>> quit() [7826 refs] Does anybody know what tricks or coding magic might be required to get debug extension modules to load into debug Python? From sierra_mtnview at sbcglobal.net Sat Aug 23 09:27:38 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 23 Aug 2008 06:27:38 -0700 Subject: Python open of c:\ path Problem Message-ID: <48B0104A.4010303@sbcglobal.net> An HTML attachment was scrubbed... URL: From gminick at nie.ma.takiego.adresu.w.sieci.pl Thu Aug 14 06:10:56 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Thu, 14 Aug 2008 10:10:56 +0000 (UTC) Subject: Suggestion for improved ImportError message References: Message-ID: On Thu, 14 Aug 2008 01:35:44 +0000 (UTC), Kent Tenney wrote: >> > Then go for it You can prepare a patch and ask on python-dev >> > if the developers are interested. > > hehe, I'll get a C level patch accepted right after I > out-swim Mike Phelps. It's really not that hard. The only hard thing (harder than writing the code) might be to win the acceptance of the core developers that this change is really needed ;-) >> > I was never hacking the import things on C level before, >> > but a hint: you have to modify import_from function from >> > Python/ceval.c > > Am I correct in thinking that PyPy would mean low level > stuff like this will be Python instead of C? > That would be nice. I don't know PyPy, but I guess you're right here. -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From circularfunc at yahoo.se Mon Aug 25 21:58:56 2008 From: circularfunc at yahoo.se (cnb) Date: Mon, 25 Aug 2008 18:58:56 -0700 (PDT) Subject: Return a string result with out breaking loop References: <116e4423-44c5-4f13-ab2d-d8040b550a8e@2g2000hsn.googlegroups.com> Message-ID: ok post exactly what you do when this hapens: ault: :cannot marshal objects"> it complains you are trying to marshal a generator object rather than the file you are yielding. also, something I am not sure about: >>> def f(x): try: open("C:/ruby/progs/blandat/infixtoprefix.rb") or open(str(x)) except:print "hello" >>> f(12) >>> def f(x): try: (open(str(x)) or open("C:/ruby/progs/blandat/infixtoprefix.rb")) except:print "hello" >>> f(12) hello >>> the or doesnt seem to work as expected. but thats not the problem youa re experienceing From duncan.booth at invalid.invalid Sun Aug 10 07:31:58 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Aug 2008 11:31:58 GMT Subject: Missing exceptions in PEP 3107 References: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> Message-ID: Christoph Zwerschke wrote: > That would be possible. But I still think it makes sense to separate > them, like so: > > def foo(a: "a info", b: "b info") -> "ret info" raise "exc info": > return "hello world" > > And then the annotation dictionary would contain another key "raise" > containing the exc info. This cannot conflict with the name of any other > parameter either. > If you really want this then you can use a decorator to insert a 'raise' key into the annotations: @raises("exc info") def foo(a: "a info", b: "b info") -> "ret info": return "hello world" > I don't know how determined the "->" syntax is already. Consider the syntax set in concrete. The meaning of the annotations on the other hand is completely up for grabs. From gminick at nie.ma.takiego.adresu.w.sieci.pl Wed Aug 6 07:55:13 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Wed, 6 Aug 2008 11:55:13 +0000 (UTC) Subject: Help with mechanize References: Message-ID: Dnia Wed, 06 Aug 2008 07:16:37 -0400, Neal Becker napisa?(a): > I'm trying to use mechanize to read for a M$ mail server. I can get past the login page OK using: ... > Now it seems if I read b.links() I can see links to my mail. My question is, how do I now actually get the contents of this page? Have you tried follow_link() method? In your case it should be something like: response = b.follow_link(b.links()[0]) # I suppose links() # returns a list or tuple print response.info() # headers print response.read() # body IIRC, it's described in the documentation. -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From ggpolo at gmail.com Mon Aug 25 23:10:15 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 26 Aug 2008 00:10:15 -0300 Subject: SocketServer max connections In-Reply-To: <48B28784.2050209@seehart.com> References: <48B28784.2050209@seehart.com> Message-ID: On Mon, Aug 25, 2008 at 7:20 AM, Ken Seehart wrote: > I'm using SocketServer to implement a local server that serves comet > long-polling connections. > > How do I increase the maximum number of open connections? Currently it is > limited to about 8 I think. More than that and it seems to block on opening > more connections until one of the other connections releases. You need to change request_queue_size in your subclass, supposing you are directly or indirectly using a tcp server. The default is 5, rather low. The first attempt you can do is using the socket.SOMAXCONN value, but depending on your system you can set a number much higher than that one given by socket.SOMAXCONN. > > - Ken > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From tkpmep at hotmail.com Tue Aug 26 17:49:35 2008 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: Tue, 26 Aug 2008 14:49:35 -0700 (PDT) Subject: Identifying the start of good data in a list Message-ID: <94524253-b946-4ffa-ae2e-ae6a555d4e7c@a1g2000hsb.googlegroups.com> I have a list that starts with zeros, has sporadic data, and then has good data. I define the point at which the data turns good to be the first index with a non-zero entry that is followed by at least 4 consecutive non-zero data items (i.e. a week's worth of non-zero data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], I would define the point at which data turns good to be 4 (1 followed by 2, 3, 4, 5). I have a simple algorithm to identify this changepoint, but it looks crude: is there a cleaner, more elegant way to do this? flag = True i=-1 j=0 while flag and i < len(retHist)-1: i += 1 if retHist[i] == 0: j = 0 else: j += 1 if j == 5: flag = False del retHist[:i-4] Thanks in advance for your help Thomas Philips From gagsl-py2 at yahoo.com.ar Fri Aug 29 20:04:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 29 Aug 2008 21:04:47 -0300 Subject: no string.downer() ? References: <53a51084-8ec9-4069-99b6-7d494002a308@56g2000hsm.googlegroups.com> <9364d88d-6792-4398-8703-cad69b5be3f5@b38g2000prf.googlegroups.com> Message-ID: En Thu, 28 Aug 2008 02:52:42 -0300, Fredrik Lundh escribi?: > Asun Friere wrote: > >> Never ascribe to humour that which can be adequately explained by >> increadible stupidity! On the other hand given up/down vs. high/low, >> upper/downer might appear logical to someone who doesn't know that >> "downcase" is called 'lowercase.' > > prior exposure to Ruby might explain this, right? (iirc, they use > "upcase" and "downcase"). Yes. And Common Lisp has used the same very names for a longer time than Python itself existed, so I don't agree with many comments on this thread. -- Gabriel Genellina From jonathansamuel at yahoo.com Sun Aug 3 19:20:37 2008 From: jonathansamuel at yahoo.com (Jonathan Mark) Date: Sun, 3 Aug 2008 16:20:37 -0700 (PDT) Subject: How do I find out from inside pdb which namespace contains an object? References: Message-ID: Never mind. I had to run "import collective.dancing" first. From ryntech at gmail.com Wed Aug 27 09:52:59 2008 From: ryntech at gmail.com (rynt) Date: Wed, 27 Aug 2008 06:52:59 -0700 (PDT) Subject: GUI programming with python References: <1ff5e508-0fd8-44cf-9c82-3c85ded0ed2d@x16g2000prn.googlegroups.com> <1bs69ogq6nspt.136i7kvcux142$.dlg@40tude.net> Message-ID: <880f46a3-8c26-4ad1-891d-a593ff3de886@w1g2000prk.googlegroups.com> On Aug 26, 10:49?am, John Fabiani wrote: > Alan Franzoni wrote: > > zamil was kind enough to say: > > > [cut] > > > See the following link on the Python website. http://wiki.python.org/moin/GuiProgramming Google this list for GUI RC From paul at boddie.org.uk Fri Aug 15 09:42:26 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 15 Aug 2008 06:42:26 -0700 (PDT) Subject: getattr nested attributes References: Message-ID: <7229d7ab-c3df-4a6a-b050-65ca0b43ad9a@56g2000hsm.googlegroups.com> On 15 Aug, 10:35, Gregor Horvath wrote: > > : type object 'B' has no attribute > 'a.test' You have to realise that attributes can have names beyond those supported by the usual attribute access syntax. For example: class C: pass setattr(C, "x.y", 123) getattr(C, "x.y") # gives 123 setattr(C, "class $$$", 456) getattr(C, "class $$$") # gives 456 Note that there's no way of using the object.name syntax to access these attributes, although some proposals have been made to allow it in some fashion. What you should conclude from this is that the name argument to setattr and getattr is just a name, not an expression, even if you can construct names which look like expressions or other syntactically meaningful fragments of code. > Documentation says B.a.test and getattr(B, "a.test") should be equivalent. > > http://docs.python.org/lib/built-in-funcs.html No, the documentation says that the name must be "the name of one of the object's attributes", not an expression fragment that if combined with the name of the object and evaluated would yield an attribute from some object or other reachable via the original object. Paul From phillip.oldham at gmail.com Thu Aug 14 08:22:35 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Thu, 14 Aug 2008 05:22:35 -0700 (PDT) Subject: Trying ZODB, background in Relational: mimic auto_increment? Message-ID: Hi all. I'm playing with standalone ZODB at the moment trying to get a better understanding of its use in applications. I come from a PHP/MySQL background, and I'm taking my first steps with Python at the same time. One of the things I'm not understanding about ZODB is assigning incremental IDs to objects. For instance, if I were to be writing a support-ticket system I'd want to give each ticket a unique number, but one that's "human-useable" (otherwise you could just use a UUID - try giving one of those over the phone!). Also, how would one add a new item to the db in this way? For instance: class Ticket(Persistence): def __init__(self): self.id = '' # How do I add a new incremental ID here? # and later on in the app tkt = Ticket() dbroot[?????] = tkt How would one assign a unique ID to the root at that point? From teh.saber at gmail.com Sat Aug 9 22:20:02 2008 From: teh.saber at gmail.com (teh_sAbEr) Date: Sat, 9 Aug 2008 19:20:02 -0700 (PDT) Subject: The wrong approach to things Message-ID: <0c435465-b769-45b9-8c6e-57d57abc5c31@j33g2000pri.googlegroups.com> Ok, so this isn't necessarily a programming issue, but anyways. I've managed to write that random wallpaper changer i've been wanting to make, but i've run into a little problem. According to the MS Knowledge Base, SystemParametersInfo() can't take a .jpg file as an argument when changing the wallpaper (it doesn't work, i've tried it), only .bmps so i'm stuck converting one of my many wallpapers from .jpg to .bmp, passing that to SystemParametersInfo(), and deleting the previous .bmp so that i don't have any duplicates. The problem with this is that other members of my family use this computer too, and they sometimes set the desktop wallpaper to some other, usually funny picture they've got stored on the HD, and when I run this little script it'll delete whatever the current wallpaper is, regardless of whether its one of mine or not. Any suggestions on how to work around this problem? #random wallpaper changer! import win32gui #use this to change the wallpaper. import os import os.path import random import Image SPI_SETDESKWALLPAPER = 20 #It took me WAY too long to find them. SPI_GETDESKWALLPAPER = 115 #I should keep these handy. def RandomlySelectWallpaper(filePaths): CurrentWallpaper = win32gui.SystemParametersInfo(SPI_GETDESKWALLPAPER) while True: index = random.randint(0,len(filePaths)-1) RandomlySelectedWallpaper = filePaths[index] if RandomlySelectedWallpaper <> CurrentWallpaper: break print RandomlySelectedWallpaper return RandomlySelectedWallpaper #it should be a string... def ChangeDesktopWallpaper(RandomlySelectedWallpaper): #so the RIGHT way to do this would be to use #win32gui.SystemParametersInfo() to change the wallpaper. #1) we convert the image to .bmp. #Delete the old wallpaper, actual delete occurs after new wallpaper has been set. pathToCurrentWall = win32gui.SystemParametersInfo(SPI_GETDESKWALLPAPER) root,extension = os.path.splitext(RandomlySelectedWallpaper) newFileName = root + '.bmp' print "Wallpaper to delete: ", pathToCurrentWall try: #every so often something goes wrong at this stage in the script #and I can't figure out what. Something raises an IOError. Image.open(RandomlySelectedWallpaper).save(newFileName) print "File saved!" except IOError: print "Error while converting, please check filepath and permissions." print "Program will restart in an attempt to generate a correct wallpaper." Main() win32gui.SystemParametersInfo(SPI_SETDESKWALLPAPER,newFileName, 1+2) print "Removing: ", pathToCurrentWall os.remove(pathToCurrentWall) def Main(): #woot. listOfWallpaperPaths = GenerateListOfWallpapers() RandomlySelectedWall = RandomlySelectWallpaper(listOfWallpaperPaths) ChangeDesktopWallpaper(RandomlySelectedWall) Main() From claird at lairds.us Sun Aug 31 12:24:06 2008 From: claird at lairds.us (Cameron Laird) Date: Sun, 31 Aug 2008 16:24:06 +0000 Subject: python subprocess know how References: <997f0a34-6f38-4276-9107-2d5b725d1247@q26g2000prq.googlegroups.com> Message-ID: <66tqo5-cht.ln1@lairds.us> In article <997f0a34-6f38-4276-9107-2d5b725d1247 at q26g2000prq.googlegroups.com>, King wrote: >Hi, > >I am using subprocess module to execute a command and print results >back. > >startupinfo = subprocess.STARTUPINFO() >startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW >my_process = subprocess.Popen(cmnd, startupinfo=startupinfo) >print repr(my_process.communicate()[0]) > >This code executes on pressing a button (wxPython). The problem is >until command is not done >and it's results are not printed, program halts and button keep the >state of pushed. > >Is there any way to avoid this? . . . From bignose+hates-spam at benfinney.id.au Thu Aug 7 19:50:04 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 08 Aug 2008 09:50:04 +1000 Subject: how to find out if an object is a class? References: Message-ID: <871w105qs3.fsf@benfinney.id.au> szczepiq writes: > Pardon me for most likely a dummy question but how do I find out if > an object is a class? You can test using 'isinstance'. However, using that is a bad code smell, which requires investigation as to the reason. Presumably you want to know whether it's a class in order to use it for instantiating it. It is usually more Pythonic to use the object as intended, and allow the object itself to tell you (via exceptions) when it's not behaving as you expect. >>> def foo(spam_class): ... spam_arg = 10 ... spam_instance = spam_class(spam_arg) ... # ? do stuff with spam_instance ? ... >>> foo(int) >>> foo("not a class") Traceback (most recent call last): File "", line 1, in File "", line 3, in foo TypeError: 'str' object is not callable > I need something like that: > > def foo(self, obj): > if (obj is a class): > some stuff Why do you think you need to test whether an object is a class? What problem are you trying to solve? -- \ ?I got fired from my job the other day. They said my | `\ personality was weird. ? That's okay, I have four more.? | _o__) ?Bug-Eyed Earl, _Red Meat_ | Ben Finney From maric at aristote.info Sat Aug 16 10:02:26 2008 From: maric at aristote.info (Maric Michaud) Date: Sat, 16 Aug 2008 16:02:26 +0200 Subject: Dynamically defined functions via exec in imported module In-Reply-To: <979a8a16-0930-4838-9625-0a03784e590b@w7g2000hsa.googlegroups.com> References: <036d8731-5984-4c23-a15d-efe7e01b5d07@x35g2000hsb.googlegroups.com> <979a8a16-0930-4838-9625-0a03784e590b@w7g2000hsa.googlegroups.com> Message-ID: <200808161602.27642.maric@aristote.info> Le Saturday 16 August 2008 06:50:02 Michele Simionato, vous avez ?crit?: > On Aug 16, 4:48?am, Nadeem wrote: > > I understand the 99% rule... the example I gave was to simplify the > > issue. The full thing I'm working on is a library for an introductory > > CS class I'm teaching. I'm trying, essentially, to build a library of > > macros for students to use allowing them to define records (like > > structs in C) with selector functions. > > The namedtuple recipe by Raymond Hetting does > exactly that and, guess what, it uses exec! It uses exec, but could not, and IMO, should not, all of the cooking could be done in the closure. I join version of it without exec. Of course the only drawback is that you need to do the job of argument checking in __new__ and can't rely on a dynamically compiled arglist. But it is a common idiom I think. > Also the doctest module in the standard library > uses exec at good effect. So, I would say it is > not a 99% rule, let's say it is a 98% rule ;) Yes, but in doctest, exec is used for what it is intended to be use, execute arbitrary code provided by the user, this is legal and perfect use of exec because here the user is a trusted one (the programer himself). I'd say that everywhere exec/eval are used in a application/function/lib that doesn't mean to interpret arbitrary and user provided python code, it is a bad usage. -- _____________ Maric Michaud -------------- next part -------------- A non-text attachment was scrubbed... Name: namedtuple.py Type: application/x-python Size: 5644 bytes Desc: not available URL: From Slaunger at gmail.com Thu Aug 7 02:29:01 2008 From: Slaunger at gmail.com (Slaunger) Date: Wed, 6 Aug 2008 23:29:01 -0700 (PDT) Subject: Best practise implementation for equal by value objects References: <135eb396-6daa-4ff4-a722-253ba149889c@27g2000hsf.googlegroups.com> <00aa5a64$0$20317$c3e8da3@news.astraweb.com> Message-ID: <473d7c86-22f4-4992-989b-e2b9402fd10d@l64g2000hse.googlegroups.com> On 7 Aug., 04:34, Steven D'Aprano wrote: > On Wed, 06 Aug 2008 05:50:35 -0700, Slaunger wrote: > > Hi, > > > I am new here and relatively new to Python, so be gentle: > > > Is there a recommended generic implementation of __repr__ for objects > > equal by value to assure that eval(repr(x)) == x independet of which > > module the call is made from? > > In general, no. > > ... > OK. > > My question is: Is there a robust generic type of implementation of > > __repr__ which I can use instead? > > > This is something I plan to reuse for many different Value classes, so I > > would like to get it robust. > > I doubt you could get it that robust, nor is it intended to be. > > eval(repr(obj)) giving obj is meant as a guideline, not an invariant -- > there are many things that can break it. For example, here's a module > with a simple class: OK, I had not fully understood the implications of 'not' implementing __repr__ such that eval(repr(x)) == x, so I just tried to make it work to make sure life would be easy for me and my object as I went further into the Python jungle As mentioned above, i also find the eval(repr(x))==x condition convenient from a unit test point of view. > > # Parrot module > class Parrot(object): > ? ? def __repr__(self): > ? ? ? ? return "parrot.Parrot()" > ? ? def __eq__(self, other): > ? ? ? ? # all parrots are equal > ? ? ? ? return isinstance(other, Parrot) > > Now let's use it: > > >>> import parrot > >>> p = parrot.Parrot() > >>> s = repr(p) > >>> assert eval(s) == p > >>> del parrot > >>> assert eval(s) == p > > Traceback (most recent call last): > ? File "", line 1, in > ? File "", line 1, in > NameError: name 'parrot' is not defined > OK, I see, but this isn't exactly eval(repr(x))==x but s = repr(x) eval(s) == x so, of course, is s is deleted in between it won't work. In my implementation I only expect this should work as a one-liner. > If you look at classes in the standard library, they often have reprs > like this: > > >>> repr(timeit.Timer()) > > '' > Yes, I noticed that. But the example here is also an object, which is equal by reference, not value. And for these it does not make so much sense to evaluate the representation. > Certainly you can't expect to successfully eval that! > > I believe the recommendation for eval(repr(obj)) to give obj again is > meant as a convenience for the interactive interpreter, and even there > only for simple types like int or list. If you can do it, great, but if > it doesn't work, so be it. You're not supposed to rely on it, and it's > not meant as a general way to serialize classes. > > -- > Steven OK, I will put less emphasis on it in the future. Thank you for taking your time to answer. Slaunger From vijayakumar.subburaj at gmail.com Thu Aug 7 08:48:27 2008 From: vijayakumar.subburaj at gmail.com (v4vijayakumar) Date: Thu, 7 Aug 2008 05:48:27 -0700 (PDT) Subject: More Datastore Examples Please References: Message-ID: <9eed4339-587a-4405-8d38-7b2a80cefc29@j7g2000prm.googlegroups.com> On Aug 7, 11:38 am, Tim Roberts wrote: > v4vijayakumar wrote: > > >Google appengine datastore is not very clear, and I couldn't get much > >from API documents. It would be very helpful if there are some more > >detailed documents with examples. > > I would gently suggest that you are not trying hard enough. I had never > encountered the Google appengine datastore, but the first hit in Googling > that phrase took me to the Google documentation, which seems to be quite > thorough. Google documentation is not clear for me. Documentation provided there is not helping much with modeling entities. This requires some practice, so I thought that If there were some ways to access this APIs through Idle. This is not as simple as adding some directories to PYTHONPATH. There are some more things to be done before working directly on datastore through Idle. This is not documented, but luckily got some help from the group, google-appengine. > If you have never worked with a database before, then you might want to go > find a good book on databases first. No. That won't help, because this datastore is not a relational database, but Google's proprietary format called BigTable. > What are you trying to DO with the datastore? I am just experimenting with google-appengine, and building an application on it. From simon at mullis.co.uk Wed Aug 13 09:15:21 2008 From: simon at mullis.co.uk (Simon Mullis) Date: Wed, 13 Aug 2008 15:15:21 +0200 Subject: Regarding Telnet library in python In-Reply-To: <7412fd2f-b6b0-4b91-b05e-53b434d6fd2e@w24g2000prd.googlegroups.com> References: <7412fd2f-b6b0-4b91-b05e-53b434d6fd2e@w24g2000prd.googlegroups.com> Message-ID: <23d7e1bb0808130615s571a091fsa84124ad84e67a64@mail.gmail.com> Hi there, This works (but bear in mind I'm about only 30 minutes into my Python adventure...): ------ def connect(host): tn = telnetlib.Telnet(host) return tn def login(session,user,password): session.write("\n") session.read_until("Login: ") session.write(user + "\n") session.read_until("Password: ") session.write(password + "\n") session.read_until("#") def apply_command(session,command): session.write(command + "\n") response = str(session.read_until("#")) return response def cleanup(session): session.write("exit\n") session.close() tn = connect(1.1.1.1) login(tn,user,password) directory = apply_command(tn,"ls -l") kernel_release = apply_command(tn,"uname -r\n") cleanup(tn) ------ You'd probably need to apply a regex to the output of the apply_command method for it to make sense, and I am confident there is a much, much better way to do this! Cheers SM -------------- next part -------------- An HTML attachment was scrubbed... URL: From saswat at gmail.com Fri Aug 29 04:16:26 2008 From: saswat at gmail.com (saswat at gmail.com) Date: Fri, 29 Aug 2008 01:16:26 -0700 (PDT) Subject: Checking if the file is a symlink fails References: <803e077e-c0c9-43d3-b40a-99511c2e55f3@25g2000prz.googlegroups.com> Message-ID: On Aug 28, 10:20?pm, Fredrik Lundh wrote: > sas... at gmail.com wrote: > > Do you mean the following is deprecated ? > >http://docs.python.org/lib/module-stat.html > > >>From the documentation - > > > S_ISLNK( mode) > > ? ? Return non-zero if the mode is from a symbolic link. > > As that page states, that's a function used to interpret a mode flag > returned by os.stat, os.fstat, or os.lstat. ?It obviously won't give you > the result you're looking for if you use a stat function that *follows* > symbolic links. > > Thank you Fredrick and Miles, stat() is on the actual file and not on the symlink. That explains. -Saswat From modelnine at modelnine.org Sat Aug 2 12:14:33 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Sat, 02 Aug 2008 17:14:33 +0100 Subject: Help me In-Reply-To: <20080802200242.cn33gib7288s4sko@mail.svuonline.org> References: <20080802200242.cn33gib7288s4sko@mail.svuonline.org> Message-ID: Am 02.08.2008, 18:02 Uhr, schrieb : > I'll help you by giving some good advice: homework is meant to be homework, so you should get started reading and processing the assignment. If you have any specific questions besides text comprehension, come back to ask. --- Heiko. From george.sakkis at gmail.com Mon Aug 18 11:57:57 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 18 Aug 2008 08:57:57 -0700 (PDT) Subject: Weird expression result Message-ID: <83803185-725e-45bb-b2fe-1add2868bd34@c58g2000hsc.googlegroups.com> I'm probably missing something obvious but I can't put my finger on it: >>> (3 in [3]) == True True >>> 3 in ([3] == True) Traceback (most recent call last): File "", line 1, in TypeError: argument of type 'bool' is not iterable >>> 3 in [3] == True False How/why does the last one evaluate to False ? George From scottpig1 at comcast.net Wed Aug 6 18:34:07 2008 From: scottpig1 at comcast.net (pigmartian) Date: Wed, 06 Aug 2008 18:34:07 -0400 Subject: pyprocessing/multiprocessing for x64? In-Reply-To: <5cqdnSE547L0QgXVnZ2dnUVZ_sLinZ2d@comcast.com> References: <5cqdnSE547L0QgXVnZ2dnUVZ_sLinZ2d@comcast.com> Message-ID: Interesting, I see Christian's responses to Benjamin, but not Benjamin's posts themselves. Anyways, the question remains: will multiprocessing be supported for the x64 platform when it's released in 2.6? pigmartian wrote: > I recently learned (from I response on this newsgroup to an earlier > query) of the processing module for working with subprocesses in a > similar manner to threading. For what I needed to do, it worked great > --- until I tried to run my code on an x64 box, for which that module > isn't available*. So, I'm just wondering if when processing is renamed > to multiprocessing and included in the standard lib for 2.6, will x64 be > supported? > > > ~Scott > > *yes, yes, I know. download the source and compile it myself. From kmathew at envivio.fr Sat Aug 2 07:53:03 2008 From: kmathew at envivio.fr (Kurien Mathew) Date: Sat, 02 Aug 2008 13:53:03 +0200 Subject: Concise way to format list/array to custom(hex) string Message-ID: <48944aa1$0$289$7a628cd7@news.club-internet.fr> Hello, What will be a concise & efficient way to convert a list/array.array of n elements into a hex string? For e.g. given the bytes [116, 111, 110, 103, 107, 97] I would like the formatted string 0x74 0x6f 0x6e 0x67 0x6b 0x61 Is there an approach better than below: hex = '' for b in bytes: hex += ('0x%x '%b) Thanks Kurien Test program: import array import sys bytes = array.array('B') bytes.fromstring("tongka") print bytes hex = '' for b in bytes: hex += ('0x%x '%b) print hex From nandhini.ram8 at gmail.com Fri Aug 1 02:58:41 2008 From: nandhini.ram8 at gmail.com (nandhini.ram8 at gmail.com) Date: Thu, 31 Jul 2008 23:58:41 -0700 (PDT) Subject: http://makmoneyy.googlepages.com Message-ID: http://makmoneyy.googlepages.com ........................\.\.~.~././........................... ...........................(@.@)............................. ....======oOOo=(_)=oOOo=========. ...|........Se voc? ? como eu, que................| ...|.........fica super feliz ao perceber..........| ...|......e ver o quanto sua m?e trata.........| ...|.....bem o seu namorado e o quanto.....| ...|........ela gosta dele, participe, aqui.......| ...|.....? o seu lugar, sejam bem vindos.....| ...=================Oooo=======| http://makmoneyy.googlepages.com/.................ooo0...............(........)................ .................(.......)..............)...../................... ..................\.....(..............(__./..................... ...................\.__)....................................... http://makmoneyy.googlepages.com/ From norseman at hughes.net Tue Aug 12 19:25:26 2008 From: norseman at hughes.net (norseman) Date: Tue, 12 Aug 2008 16:25:26 -0700 Subject: Broken examples In-Reply-To: <362180a2-c3da-4a71-b41d-6b02e2d800ee@v26g2000prm.googlegroups.com> References: <362180a2-c3da-4a71-b41d-6b02e2d800ee@v26g2000prm.googlegroups.com> Message-ID: <48A21BE6.6070908@hughes.net> John Machin wrote: > On Aug 12, 10:36 am, norseman wrote: >> Tim; >> Finally got a chance to test your snippet. Thank you for it! >> >> I took the liberty of flushing it out a bit. >> ================ ...(snip) >> > > Why do you want to save as CSV? Would you be happier with a simple > reliable method to extract information from Excel files without all > that bother? If so, consider the xlrd package (http://www.lexicon.net/ > sjmachin/xlrd.htm). If you really do need CSV files, still consider > xlrd in combination with the Python csv module -- remove all that user > involvement, allow the user to use Excel for other purposes while the > job is running (instead of filing), programatically handle exception > conditions (like more than one worksheet in the workbook), run it on > Linus or a Mac if you want to, ... > > -- > http://mail.python.org/mailman/listinfo/python-list > ====================== Why do you want to save as CSV? There is a ton of text processing programs that suit various people and thus text lends itself to a greater audience and massive amounts of processing tools. Tools people already know how to use. Would you be happier with a simple reliable method to extract information from Excel files without all that bother? In truth - perhaps on occasion. But take a look at the following*. I can process 1,000's of files while I am asleep and I don't even need to know the internal layout. Secretaries, Clerks and even Student help can use their favorite text program to search and replace whatever. Massive amounts of data can be reviewed and corrected by non-special computer users. Not to mention my use of things like sed for the bulk work. If so, consider the xlrd package (http://www.lexicon.net/sjmachin/xlrd.htm). I did download it. I'll give it a "test drive" as soon as I can. Then I can comment on it. There are times when it could be handy. If you really do need CSV files, still consider xlrd in combination with the Python csv module -- remove all that user involvement... Point here is I need human review. What I don't need is typos. The intent in the original Clerk statement was to poke fun at Window$. Microsoft "point'n'click" is very non-production oriented. "The following*" ==================== #!/--- # import os import win32com.client excel = win32com.client.Dispatch( 'Excel.Application' ) excel.Visible=0 #=1 shows the spreadsheet (can be handy) xlCSV = 6 # a substitute for the list generator list = ["c:\\temp\\test.xls", "c:\\temp\\test1.xls"] for nm in list: csv = os.path.splitext( nm )[0] + '.csv' print "Procesing file:", csv if os.path.exists(csv): os.unlink(csv) wb = excel.Workbooks.Open( nm ) wb.SaveAs( csv, xlCSV ) wb.Close( False ) excel.Quit() print "Check to see if this worked for you." # end of file ==================== The case at hand is that The State of California has been keeping weather records for awhile. The more reliable stations date from the 1920's. Others go back into the latter 1800's. Satellite reporting is rather new. Before that one took a horse or a buckboard and went off to check things. Daily data is missing (even now) for various reasons. The human can do what computers cannot - think (we hope) :). Some forms of omissions can be bulk checked. Some cannot. It is counter productive to try to create 'the all encompassing program'. The 'do all' does, as yet, not exist. If someone reading this got lost, try this; would you consider taking your brand new Ferrari 4-wheeling in the Grand Canyon? Or would you prefer that beat-up old jeep over there? Sometimes just getting out and walking around accomplishes more. Maybe not as fast, but usually better. The trick is knowing which to program and which to give to the kid. It is also counter productive to force people well trained on Tool A to only use Tool B. Better to find a common zone and let each use their respective favorite. "If you are not converting data, you are not producing anything useful." -- Me John - Thanks for the link. I will test the library. Steve norseman at hughes.net From rw at smsnet.pl Wed Aug 27 05:30:09 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 27 Aug 2008 02:30:09 -0700 (PDT) Subject: logging exceptions References: <3c8c0b98-54ea-4112-8db9-e0040929e558@w1g2000prk.googlegroups.com> <200e9b4d-c062-4984-bcec-581666458071@79g2000hsk.googlegroups.com> Message-ID: <1868e033-8313-414c-a82a-35a8852ffb77@v57g2000hse.googlegroups.com> Vinay Sajip napisa?(a): > On Aug 26, 10:36 am, Alexandru Mosoi wrote: > > why doesn'tloggingthrow any exception when it should? how do I > > configureloggingto throw exceptions? > > > > >>> try: > > > > ... logging.fatal('asdf %d', '123') > > ... except: > > ... print 'this line is never printed' > > ... > > Traceback (most recent call last): > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > python2.5/logging/__init__.py", line 744, in emit > > msg = self.format(record) > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > python2.5/logging/__init__.py", line 630, in format > > return fmt.format(record) > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > python2.5/logging/__init__.py", line 418, in format > > record.message = record.getMessage() > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > python2.5/logging/__init__.py", line 288, in getMessage > > msg = msg % self.args > > TypeError: int argument required > > Was your traceback from the snippet you posted? If it was, then the > exception (a TypeError) *is* being raised from logging. So I don't > understand your question "why doesn't logging throw any exception when > it should?", because logging is raising an exception here. No, it isn't. This traceback is *printed* in `Handler.handleError` method: __version__ = "0.5.0.2" [...] def handleError(self, record): """ Handle errors which occur during an emit() call. This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method. """ if raiseExceptions: ei = sys.exc_info() traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr) del ei > > To cause logging to *not* raise exceptions, set > logging.raiseExceptions to 0 (default is 1). The raiseExceptions > variable would normally be set to 0 in a production environment, where > you don't want logging-related exceptions to bring an application > down. Well, I think that it will not help. The exception will be printed not raised. The only solution is to redefine `handleError` method or maybe I've missed something? Br, Rob From nytrokiss at gmail.com Thu Aug 28 19:21:23 2008 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 28 Aug 2008 16:21:23 -0700 Subject: eval() == evil? --- How to use it safely? In-Reply-To: References: Message-ID: <8a6b8e350808281621u80b0222w3117acb75706535b@mail.gmail.com> I had an issue once that i was getting true and false statements in text and needed to convert them into Python boolean objects. So i wrote a function to parse the text. and return True or False based on the text. On Thu, Aug 28, 2008 at 3:09 PM, Guilherme Polo wrote: > On Thu, Aug 28, 2008 at 6:51 PM, Fett wrote: > > I am creating a program that requires some data that must be kept up > > to date. What I plan is to put this data up on a web-site then have > > the program periodically pull the data off the web-site. > > > > My problem is that when I pull the data (currently stored as a > > dictionary on the site) off the site, it is a string, I can use eval() > > to make that string into a dictionary, and everything is great. > > However, this means that I am using eval() on some string on a web- > > site, which seems pretty un-safe. > > > > I read that by using eval(code,{"__builtins__":None},{}) I can prevent > > them from using pretty much anything, and my nested dictionary of > > strings is still allowable. What I want to know is: > > > > What are the dangers of eval? > > - I originally was using exec() but switched to eval() because I > > didn't want some hacker to be able to delete/steal files off my > > clients computers. I assume this is not an issue with eval(), since > > eval wont execute commands. > > - What exactly can someone do by modifying my code string in a command > > like: thing = eval(code{"__builtins__":None},{}), anything other than > > assign their own values to the object thing? > > By "disabling" __builtins__ you indeed cut some obvious tricks, but > someone still could send you a string like "10 ** 10 ** 10". > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > -- Guilherme H. Polo Goncalves > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Tue Aug 12 08:32:59 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 12 Aug 2008 14:32:59 +0200 Subject: Help counting the total number of dictionaries inside a list that contain a specified key value In-Reply-To: <8d37bc060808120519n7f7cefban136469c49265391a@mail.gmail.com> References: <8d37bc060808120409r70fb5469kb56186b812dcc434@mail.gmail.com> <8d37bc060808120506n5e94819cp42b99c048bffc903@mail.gmail.com> <8d37bc060808120519n7f7cefban136469c49265391a@mail.gmail.com> Message-ID: Jon Bowlas wrote: > I'm afraid I can't use Peters suggestion as I'm using python 2.3 and > it doesn't have the collection module. Thanks anyway. Python 2.3 is the reason. It doesn't support the generator expression syntax. Try sum([u'Level 2 Courses' in dct for dct in yourlist]) or len([1 for dct in yourlist if u'Level 2 Courses' in dct]) Christian From BjornSteinarFjeldPettersen at gmail.com Sat Aug 9 18:14:06 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sat, 9 Aug 2008 15:14:06 -0700 (PDT) Subject: Class definition attribute order References: <5fb776ae-e3d7-49ec-9ebf-350b9bf9cac1@l42g2000hsc.googlegroups.com> <64ce3665-c76a-4ee1-b7cf-be5eef7e793f@z72g2000hsb.googlegroups.com> Message-ID: On Aug 9, 7:55?am, Michele Simionato wrote: > On Aug 5, 5:05?am, Michele Simionato > > > Yep. Seehttp://stacktrace.it/articoli/2008/01/metaclassi-python-3000 > > (I am working on an English translation these days, > > but for the moment you can use Google Translator). > > > ?M. Simionato > > FWIW, I have just finished translating the first > part of the article and I have posted it on my > blog on Artima: > > http://www.artima.com/weblogs/viewpost.jsp?thread=236234 Great feature and great article! I haven't used ABCs yet, so my initial instinct would be to derive odict from dict (it would obviate the conversions in the metaclass). Are you using ABCs just to play with all the new toys at the same time? ;-) -- bjorn From uclamathguy at gmail.com Wed Aug 6 01:20:06 2008 From: uclamathguy at gmail.com (Ryan Rosario) Date: Tue, 5 Aug 2008 22:20:06 -0700 (PDT) Subject: Trying to fix Invalid CSV File References: <0427191c-d493-442d-ba26-94802bc6062b@v13g2000pro.googlegroups.com> <078f7aad-3bba-49b4-8978-18ac5bfaa6f7@r15g2000prd.googlegroups.com> <6bade254-5001-4ae2-a000-003b84437a76@w1g2000prk.googlegroups.com> <42134ad4-ae35-4d25-94fc-2504d29003e6@r15g2000prh.googlegroups.com> Message-ID: <6bfd79e6-3b7c-4176-a3a9-941f8fa78e02@w1g2000prk.googlegroups.com> On Aug 4, 1:56?pm, Larry Bates wrote: > Ryan Rosario wrote: > > On Aug 4, 8:30 am, Emile van Sebille wrote: > >> John Machin wrote: > >>> On Aug 4, 6:15 pm, Ryan Rosario wrote: > >>>> On Aug 4, 1:01 am, John Machin wrote: > >>>>> On Aug 4, 5:49 pm, Ryan Rosario wrote: > >>>>>> Thanks Emile! Works almost perfectly, but is there some way I can > >>>>>> adapt this to quote fields that contain a comma in them? > >> > > >>> Emile's snippet is pushing it through thecsvreading process, to > >>> demonstrate that his series of replaces works (on your *sole* example, > >>> at least). > >> Exactly -- just print out the results of the passed argument: > > >> rec.replace(',"',",'''").replace('",',"''',").replace('"','""').replace("'''",'"') > > >> '123,"Here is some, text ""and some quoted text"" where the quotes > >> should have been doubled",321' > > >> Where it won't work is if any of the field embedded quotes are next to > >> commas. > > >> I'd run it against the file. ?Presumably, you've got a consistent field > >> count expectation per record. ?Any resulting record not matching is > >> suspect and will identify records this approach won't address. > > >> There's probably better ways, but sometimes it's fun to create > >> executable line noise. ?:) > > >> Emile > > > Thanks for your responses. I think John may be right that I am reading > > it a second time. I will take a look at theCSVreader documentation > > and see if that helps. Then once I run it I can see if I need to worry > > about the comma-next-to-quote issue. > > This is a perfect demonstration of why tab delimited files are so much better > than comma and quote delimited. ?Virtually all software can handle table > delimited as well as comma and quote delimited, but you would have none of these > problems if you had used tab delimited. ?The chances of tabs being embedded in > most data is virtually nil. > > -Larry Thank you for all the help. I wasn't using Emile's code correctly. It fixed 99% of the problem, reducing 30,000 bad lines to about 300. The remaining cases were too difficult to pin a pattern on, so I just spent an hour fixing those lines. It was typically just adding one more " to one that was already there. Next time I am going to be much more careful. Tab delimited is probably better for my purpose, but I can definitely see there being issues with invisible tab characters and other weirdness. Ryan From fredrik at pythonware.com Thu Aug 28 14:38:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 28 Aug 2008 20:38:42 +0200 Subject: no string.downer() ? In-Reply-To: References: <53a51084-8ec9-4069-99b6-7d494002a308@56g2000hsm.googlegroups.com> <9364d88d-6792-4398-8703-cad69b5be3f5@b38g2000prf.googlegroups.com> Message-ID: Tobiah wrote: >> Never ascribe to humour that which can be adequately explained by >> increadible stupidity! > > I love the irony. Muphry's law. From abesto0 at gmail.com Sat Aug 2 08:50:38 2008 From: abesto0 at gmail.com (=?ISO-8859-1?Q?Zolt=E1n_Nagy?=) Date: Sat, 02 Aug 2008 14:50:38 +0200 Subject: Concise way to format list/array to custom(hex) string In-Reply-To: <48944aa1$0$289$7a628cd7@news.club-internet.fr> References: <48944aa1$0$289$7a628cd7@news.club-internet.fr> Message-ID: Kurien Mathew ?rta: > Hello, > > What will be a concise & efficient way to convert a list/array.array of > n elements into a hex string? For e.g. given the bytes > [116, 111, 110, 103, 107, 97] > I would like the formatted string > 0x74 0x6f 0x6e 0x67 0x6b 0x61 > > Is there an approach better than below: > hex = '' > for b in bytes: > hex += ('0x%x '%b) > You should avoid multiple string additions, as each one creates a new string object (str objects are immutable). Try this: bytes = [116, 111, 110, 103, 107, 97] string = ''.join( ['0x%x '%b for b in bytes] ) From mattheww at chiark.greenend.org.uk Tue Aug 5 13:06:58 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 05 Aug 2008 18:06:58 +0100 (BST) Subject: URLs and ampersands References: <00a78f7e$0$20302$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I'm using urllib.urlretrieve() to download HTML pages, and I've hit a > snag with URLs containing ampersands: > > http://www.example.com/parrot.php?x=1&y=2 > > Somewhere in the process, urls like the above are escaped to: > > http://www.example.com/parrot.php?x=1&y=2 > > which naturally fails to exist. > > I could just do a string replace, but is there a "right" way to escape > and unescape URLs? I've looked through the standard lib, but I can't find > anything helpful. I don't believe there is a concept of 'escaping a URL' as such. How you escape or unescape a URL depends on what context you're embedding it in or extracting it from. In this case, it looks like you have URLs which have been escaped to go into an html CDATA attribute value (such as ). I believe there is no documented function in the Python standard library which reverses this escaping (short of putting your string into a larger document and parsing that with a full html or xml parser). -M- From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 20 05:31:59 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 20 Aug 2008 11:31:59 +0200 Subject: getattr() on nested functions? In-Reply-To: References: Message-ID: <48abe483$0$31875$426a74cc@news.free.fr> Gabriel Rossetti a ?crit : > Hello, > > I can't get getattr() to return nested functions, Of course. Nested functions are not attributes of their container function. > I tried this : > > >>> def toto(): > ... def titi(): > ... pass > ... f = getattr(toto, "titi") > ... print str(f) > ... > >>> toto() > Traceback (most recent call last): > File "", line 1, in > File "", line 4, in toto > AttributeError: 'function' object has no attribute 'titi' > >>> > > I thought that since functions are objects, that I could obtain it's > nested functions. Well, there's probably a very hackish way, but it's not worth the pain. The fact that functions are objects doesn't make nested functions methods of that object. If what you really want are methods, then you can write your own callable: class _Test(object): def request(self, params): pass def submit(self, params, values): pass def update(self, params, values): pass def delete(self, params): pass def __call__(self, action, *args): return resultToXml(getattr(self, action)(*args)) _test = _Test() But read the remaining before... > How come it doesn't work and what can I do to > fix/replace it? I'm using it in code that is like this : > > def __test(self, action, *args): > def request(params): > pass > def submit(params, values): > pass > def update(params, values): > pass > def delete(params): > pass > result = getattr(__test, action)(*args) > return resultToXml(result) > > where "action" is a string containing either "request", "submit", > "update", or "delete". I was using an evel() with this form : > > result = eval(action + "(params, values)") Wrong use case for eval, as usual. > but I didn't find that very clean. indeed !-) locals() is your friend. def _test(self, action, *args): def request(params): pass def submit(params, values): pass def update(params, values): pass def delete(params): pass result = locals()[action](*args) return resultToXml(result) HTH From pavlovevidence at gmail.com Fri Aug 1 17:13:04 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 1 Aug 2008 14:13:04 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> <5a0b303a-8324-4eeb-a975-397371bf2875@b1g2000hsg.googlegroups.com> Message-ID: <8956f8ca-1f5a-465a-9b02-5ad9b1c97876@l64g2000hse.googlegroups.com> On Aug 1, 4:45 pm, Carl Banks wrote: > On Aug 1, 3:36 pm, Terry Reedy wrote: > > In general, asking code to apply across numeric, container, and other > > classes is asking too much. Python code can be generic only within > > protocol/interface categories such as number-like, sortable, and > > iterable. But making tests too specific can unnecessarily prevent even > > that. > > At some point we have to throw our hands up and realize that if we're > working with custom classes with varying degrees of nonconformance, > there is nothing we can do that's safe. And I want to make clear I'm not trying to downplay your example here. The example you gave me definitely fits the criteria of being a useful "if x" that can't be replaced by a simple explicit test, at least after my alteration to a vector example. It's a concern when you write code that breaks realistic custom classes, but really concerning when it breaks built-in classes. Carl Banks From adityashukla1983 at gmail.com Sun Aug 17 18:14:56 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Sun, 17 Aug 2008 17:14:56 -0500 Subject: command line tool for process communication Message-ID: <73045cca0808171514j6ab1195ag7d0909a048bb51ea@mail.gmail.com> Hello guys, I have a program which is run through command line .I am trying to create another command line tools which controls this program. So for example in my new program when i give newprog -a then it should invoke the existing tool and perform one of its operation.eg existtprog -s How could this be done in python? Optparse can be used to make the new tool but what should be done to control the existing tool from the new tool? Thanks in advance. Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From jimgardener at gmail.com Wed Aug 27 12:57:15 2008 From: jimgardener at gmail.com (jimgardener) Date: Wed, 27 Aug 2008 09:57:15 -0700 (PDT) Subject: import error between 2 modules References: <98825d39-e457-4957-bfdc-846b7eca6ca9@w1g2000prk.googlegroups.com> Message-ID: <25c9bda7-7715-4fcf-bf74-34fdd91d55cc@n33g2000pri.googlegroups.com> On Aug 27, 5:37 pm, Laszlo Nagy wrote: > These constructors will be calling each other forever. This will be an infinite recursion. sorry,that was a quite stupid mistake on my part..thanks for pointing out.. jim From brennan.ron at gmail.com Wed Aug 27 16:26:45 2008 From: brennan.ron at gmail.com (Ron Brennan) Date: Wed, 27 Aug 2008 16:26:45 -0400 Subject: Multiple values for one key Message-ID: <26c69b160808271326w2f53b6b8s6e4aa7f91071ac71@mail.gmail.com> Hello, How would I create a dictionary that contains multiple values for one key. I'd also like the key to be able to have duplicate entries. Thanks, Ron -- FYI, my email address is changing. My rogers account will be deactivated shortly. From now on please use: brennan.ron at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sat Aug 30 03:11:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 30 Aug 2008 04:11:33 -0300 Subject: Which is faster? References: <00c8e015$0$20302$c3e8da3@news.astraweb.com> Message-ID: En Sat, 30 Aug 2008 03:15:30 -0300, Steven D'Aprano escribi?: > On Fri, 29 Aug 2008 21:26:35 -0700, cnb wrote: > >> def averageGrade(self): >> tot = 0 >> for review in self.reviews: >> tot += review.grade >> return tot / len(self.reviews) >> >> def av_grade(self): >> return sum(review.grade for review in self.reviews) / \ >> len(self.reviews) > > Re-writing the functions so they can be tested alone: > > def averageGrade(alist): > tot = 0.0 > for x in alist: > tot += x > return tot/len(alist) > > > def av_grade(alist): > return sum(alist)/len(alist) > > >>>> from timeit import Timer >>>> # small amount of items > ... alist = range(100) >>>> Timer('averageGrade(alist)', > ... 'from __main__ import alist, averageGrade').repeat(number=100000) > [3.9559240341186523, 3.4910569190979004, 3.4856188297271729] >>>> >>>> Timer('av_grade(alist)', > ... 'from __main__ import alist, av_grade').repeat(number=100000) > [2.0255107879638672, 1.0968310832977295, 1.0733180046081543] > > > The version with sum() is much faster. How about with lots of data? > >>>> alist = xrange(1000000) >>>> Timer('averageGrade(alist)', > ... 'from __main__ import alist, averageGrade').repeat(number=50) > [17.699107885360718, 18.182793140411377, 18.651514053344727] >>>> >>>> Timer('av_grade(alist)', > ... 'from __main__ import alist, av_grade').repeat(number=50) > [17.125216007232666, 15.72636890411377, 16.309713840484619] > > sum() is still a little faster. Mmm, in this last test you're measuring the long integer operations performance (because the sum exceeds largely what can be represented in a plain integer). Long integers are so slow that the difference between both loops becomes negligible. I've tried again using float values: alist = [float(x) for x in xrange(1000000)] and got consistent results for any input size (the version using sum() is about twice as fast as the for loop) -- Gabriel Genellina From code at pizzashack.org Wed Aug 20 18:46:42 2008 From: code at pizzashack.org (Derek Martin) Date: Wed, 20 Aug 2008 18:46:42 -0400 Subject: python custom command interpreter? In-Reply-To: References: Message-ID: <20080820224642.GD28038@dragontoe.org> On Wed, Aug 20, 2008 at 03:19:19PM -0400, joey boggs wrote: > In the end I'd like to be able to run a custom interpreter and just feed it > one command and a directory. The end result in the kickstart something like > this: > > %post --interpreter #!/usr/bin/myinterpreter > DROP /tmp/directory > DROP /tmp/directory2 What is the problem you are trying to solve? Are you asking how to write a shell in Python? > How would I setup the interpreter to take the DROP command? You wouldn't... "setup" is a noun. You might "set up" an interpreter though. > I've been reading and searching all day but I haven't found anything > close to what I'm doing. I realize that using custom commands in > this case is overkill but in the end is used to make the users life > easier. How so? What could be easier than "rm -rf directory"? > If anyone can point me to some documentation I would be more than > grateful. I'd be happy to, but I can't imagine what sort of documentation would help you. It sounds like what you want to do, basically, is write a program to read commands from stdin, parse them to make sure the syntax is right, and then execute the equivalent code in Python. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jianbing.chen at gmail.com Fri Aug 15 10:02:03 2008 From: jianbing.chen at gmail.com (jianbing.chen at gmail.com) Date: Fri, 15 Aug 2008 07:02:03 -0700 (PDT) Subject: help on import libxml2 References: <092ae320-f21b-473f-9c41-80da00568a12@f63g2000hsf.googlegroups.com> <1a760b5a-bec1-4221-a746-d10324b05ca8@t54g2000hsg.googlegroups.com> Message-ID: <38adeea7-2e04-408f-9f18-5121b3d86794@k7g2000hsd.googlegroups.com> Paul, Thanks. This helped. Jianbing On Aug 14, 4:10?pm, Paul Boddie wrote: > On 14 Aug, 22:43, jianbing.c... at gmail.com wrote: > > > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? File "/sea/local/lib/python2.5/site-packages/libxml2.py", line 1, in > > > > ? ? import libxml2mod > > ImportError: ld.so.1: python: fatal: relocation error: file /usr/local/ > > lib/python2.5/site-packages/libxml2mod.so: symbol > > xmlXIncludeProcessFlags: referenced symbol not found > > The symbol mentioned should be found in the libxml2.so library file > (which I discovered by running nm on the static libxml2.a file). On my > Ubuntu system, if I run the ldd program on the libxml2mod.so file (in > a different place to where yours lives), I get the following results: > > ? ldd /var/lib/python-support/python2.5/libxml2mod.so > ? ? ? ? linux-gate.so.1 => ?(0xffffe000) > ? ? ? ? libxml2.so.2 => /usr/lib/libxml2.so.2 (0xb7e0b000) > ? ? ? ? libc.so.6 => /lib/tls/i686/cmov/libc.so.6 (0xb7cca000) > ? ? ? ? libdl.so.2 => /lib/tls/i686/cmov/libdl.so.2 (0xb7cc5000) > ? ? ? ? libz.so.1 => /usr/lib/libz.so.1 (0xb7cb1000) > ? ? ? ? libm.so.6 => /lib/tls/i686/cmov/libm.so.6 (0xb7c8a000) > ? ? ? ? /lib/ld-linux.so.2 (0x80000000) > > I suggest you run ldd on /usr/local/lib/python2.5/site-packages/ > libxml2mod.so for each user and see what it tells you. Perhaps there > are permissions issues on the libxml2.so files, wherever they are > installed, or there's a LD_LIBRARY_PATH (or equivalent) setting that > one user has that the other doesn't. > > Paul From timothy.grant at gmail.com Thu Aug 7 18:15:33 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Thu, 7 Aug 2008 15:15:33 -0700 Subject: A question about string and float number In-Reply-To: References: <489A8A01.1050908@linkline.com> Message-ID: That's because s IS a string. It's not been converted to a float. In [1]: s = '3.1415' In [2]: n = float(s) In [3]: type(s) Out[3]: In [4]: type(n) Out[4]: Why are you avoiding the very simple try:/except: solution to this problem? On Thu, Aug 7, 2008 at 1:28 PM, Wei Guo wrote: > Hi I tried the first type method but it seens that it doesn't work. Could > anyone help me about it? > >>>> s = '3.145' >>>> type(s) == type(float()) > False >>>> type(s) > >>>> type(float()) > >>>> > > Best regards, > > Wei > > > On 8/7/08, Wei Guo wrote: >> >> Hi Thanks for Tyler and Edwin's help. >> >> For my questions, I need to import some xml file and there are floating >> number and strings in it. I need to process string and number differently. >> This is reason that I am asking question here. Is this background >> information we need for this quesions. >> >> Btw, which way is better? type or with exception ValueError? >> >> Thanks, >> >> Wei >> >> >> On 8/6/08, Tyler Breisacher wrote: >>> >>> It's generally a bad idea to use "except" without naming a specific >>> exception. The exception you might expect in this case is ValueError. Any >>> other exception *should* be uncaught if it happens. By the way, this method >>> will return true for integers as well as floats. For example, isFloat('3') >>> will return 3.0. So make sure this is what you want, since it wasn't 100% >>> clear from the original message. >>> >>> >>> Wei Guo wrote: >>>> >>>> #this is a better way of testing a string for float >>>> def isFloat(s): >>>> try: >>>> s = float(s) >>>> except: >>>> return False >>>> return True >>> >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Stand Fast, tjg. [Timothy Grant] From fredrik at pythonware.com Fri Aug 29 01:30:04 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 29 Aug 2008 07:30:04 +0200 Subject: Python in a Nutshell -- Book vs Web In-Reply-To: References: Message-ID: Cameron Laird wrote: > No. No, to an almost libelous extent. No matter what you write about, there's always a certain subcategory of potential readers who insist that collection, editing, filtering, structuring, clarification, and the author's real-life experience of the topic he's writing about has no value at all. My guess is that they don't value their own time very highly. From harrrrpo at gmail.com Sat Aug 30 08:49:01 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Sat, 30 Aug 2008 05:49:01 -0700 Subject: Fastest way to write huge files In-Reply-To: References: <538050a90808281735u51ce90d0o3db3945a6ed2b591@mail.gmail.com> <48B7A8DA.7050203@timgolden.me.uk> Message-ID: <538050a90808300549v62860522h51028513afbdf7ad@mail.gmail.com> > > If connection is over Internet via HTTP the connection speed is so slow in > relation to the speed of your CPU that it doesn't really matter. this is not always true , espicially when using a localhost or a local netwtork server the problem is the increase in cpu and memory usage make it a painful bug such that downloading a big file (say 1 GB ) would introduce a big cpu usage (already tested) Thanks , Regards, Mohamed Yousef From pavlovevidence at gmail.com Fri Aug 1 17:00:01 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 1 Aug 2008 14:00:01 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> <5a0b303a-8324-4eeb-a975-397371bf2875@b1g2000hsg.googlegroups.com> Message-ID: <391e0166-7a94-4302-97f1-dbf02cc6c756@8g2000hse.googlegroups.com> On Aug 1, 4:45 pm, Carl Banks wrote: > On Aug 1, 3:36 pm, Terry Reedy wrote: > > > > > > Nevertheless, I think this is probably the best example of the > > > enhanced polymorphism of "if x" yet. I'm kind of surprised no one > > > came up with it.) > > > I think of Python code as 'generic' rather than 'polymorphic'. I am not > > sure if that is a real difference or not, since I am a bit fuzzy on the > > meaning of 'polymorphic' in this context. > > > The generality of 'if x:' depends on the context. If x is defined as a > > number by doc or previous code (or possibly even by subsequent code), > > then 'if x:' is equivalent to 'if x != 0:'. At this point, it is a > > stylistic argument which to use. > > > But here is an example where 'if x:' is more generic. > > > def solve(a,b): > > 'a and b such that b/a exists' > > if a: > > return a/b > > else: > > raise ValueError('a not invertible, cannot solve' > > > Now suppose we have a matrix class (2x2 for simplicity and realism). > > Its __bool__ (3.0) method implements 'is non-singular'. As written > > above, solve(mat,vec) works (with compatible mat and vec sizes), but it > > would not with 'if a != 0:'. > > I see what you're saying, even though this example turns out to be > pretty bad in practice. > > (Practically speaking, you hardly ever write code for both matrices > and scalars, because the optimal way for matrices would be convoluted > and opaque for scalars, though scalars can sometimes be fed into > matrix code as a degenerate case. Also, checking the condition of the > matrix by calculating and comparing the determinant to zero is like > comparing float equality without a tolerance, only much, much worse.) > > But instead of a matrix, take a vector (which has a better chance of > being used in code designed for scalars) and define a zero-length > vector as false, and that could be a good example. > > > In general, asking code to apply across numeric, container, and other > > classes is asking too much. Python code can be generic only within > > protocol/interface categories such as number-like, sortable, and > > iterable. But making tests too specific can unnecessarily prevent even > > that. > > At some point we have to throw our hands up and realize that if we're > working with custom classes with varying degrees of nonconformance, > there is nothing we can do that's safe. > > > > Something versus nothing is a useless concept most of the time, but > > > occasionally finds use in human interaction cases such as printing. > > > It is sometimes useful within categories of classes, as in my solve example. > > I'm going to say no. > > Let's take your matrix example: you defined singularity to be false, > but singularity can't reasonably be mapped to the concept of nothing. > For "nothing" I would think you'd want a 0x0 matrix. Something vs > nothing also implies that all objects should have a boolean value. > So, assuming boolean is connected to a matrices singularity, what > should be the boolean value of non-square matrices? > > No, I'm going to have to disagree very strongly with this. > Nonzeroness is useful. Emptiness is useful. Singularity a kind of > useful. Nothing and something are vague, ill-defined, ad hoc concepts > that mean nothing to a computer. Have you ever seen an algorithm that > says "if x is something"? > > Something and nothing do seem to come into play occasionally in that, > when interacting with humans (be it the user or programmer), it > sometimes--not nearly always--makes sense to treat nonzero and empty > in the same way. But there's no particular reason to apply the > concepts of something and nothing beyond this pragmatic use. > > Carl Banks From elessar at nienna.org Fri Aug 1 16:20:18 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 01 Aug 2008 14:20:18 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <2a56bffc-6c11-474d-b2b1-ca344ff94f09@x41g2000hsb.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> <5a0b303a-8324-4eeb-a975-397371bf2875@b1g2000hsg.googlegroups.com> <9f920209-3080-470a-817b-9afadbecc453@j22g2000hsf.googlegroups.com> <2a56bffc-6c11-474d-b2b1-ca344ff94f09@x41g2000hsb.googlegroups.com> Message-ID: <48937002.2010600@nienna.org> Carl Banks wrote: > On Aug 1, 8:49 am, Matthew Fitzgibbons wrote: >> Carl Banks wrote: >>> On Jul 31, 11:44 pm, Carl Banks wrote: >>> [snip excellent explanation of why it's hard to for "if x" to be >>> extensively polymorphic] >>> By the way, one thing I forgot to mention is Matt Fitzgibbons' filter >>> example. >>> As I said, it's hard to write code that works for both numeric and >>> container types because they share so few methods. However, sometimes >>> you don't know ahead of time what methods are used! When you're doing >>> functional programming you might pass in a method that calls the >>> appropriate method, like so: >>> def apply_if_true(func,x): >>> if x: >>> func(x) >> I find myself doing things like this surprisingly often. All you've done >> is move the decision as to what function is applied to x elsewhere. Like >> a factory, for example. I could see using something like this where func >> prepares object x to be inserted into a database, and you want to make >> sure x is meaningful first. >> >> def add_to_db(prep_func, x): >> if x: >> entry = prep_func(x) >> add_to_db(entry) >> >> 'if x' strikes me as better for this case because you might want to >> accept a non-empty list (or some other objects) but reject non-empty >> lists. 'if x is None' would not work. It still may be susceptible to the >> empty iterator problem, depending on what prep_func does. > > What if what you consider to be "meaningful" doesn't happen to > coincide with what Python considers to be "something". For instance, > what if being non-negative is what makes an integer meaningful? You > can't use "if x" for that. What if any list, including an empty one, > is meaningful, but you want to indicate the possibility of an > unmeaningful value by passing None? You can't use "if x" for that. > > So, you might address this issue by doing something like this: > > def add_to_db(prep_func, is_meaningful, x): > if is_meaningful(x): > entry = prep_func(x) > add_to_db(entry > > But if you do that, what has the polymorphism of "if x" gained you? > > The thing it gained for you before is not having to pass in a > condition: whether x was a sequence, number, or whatever, the same > condition could be used, and thus you avoided considerable > complexity. But if you have to perform tests for which the implicit > boolean doesn't work, that complexity has to be added to the code > anyway. Of course. If a chunk of code already does what you want it to, then you can use it. Otherwise you have to do something different. I was just pointing out that 'if x' often does what I want it to. Sometimes it doesn't, so I do something different. > > That matters in the context of this discussion because it limits the > usefulness of the polymorphism of "if x" for this functional idiom: > "if x" only helps you if you have no need for tests that it can't > handle. > > [snip] > > Carl Banks > -- > http://mail.python.org/mailman/listinfo/python-list > By this argument, all code is limiting. Obviously, no code can do what it can't. We're not getting anywhere; it's past time to kill this one off. -Matt From wiggly at wiggly.org Wed Aug 13 11:51:53 2008 From: wiggly at wiggly.org (Nigel Rantor) Date: Wed, 13 Aug 2008 16:51:53 +0100 Subject: You advice please In-Reply-To: <76fd5acf0808130838r44590107t3297fb3f38d38f10@mail.gmail.com> References: <20080813110444.7b48ddbc.darcy@druid.net> <76fd5acf0808130811y7d7d6584m721096295a72af98@mail.gmail.com> <48A2FBAC.3000103@wiggly.org> <76fd5acf0808130838r44590107t3297fb3f38d38f10@mail.gmail.com> Message-ID: <48A30319.9030105@wiggly.org> Calvin Spealman wrote: > God forbid I try to make a joke. Ah, sorry, sense of humour failure for me today obviously. n From bdesth.quelquechose at free.quelquepart.fr Tue Aug 19 14:45:06 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 19 Aug 2008 20:45:06 +0200 Subject: who to call a list of method inside the class itself In-Reply-To: References: Message-ID: <48ab30a4$0$12032$426a34cc@news.free.fr> Edwin.Madari at VerizonWireless.com a ?crit : > maduma at pt.lu wrote: >> Hi, >> >> Is the following code is ok. who to call all method. >> It is working but the call to m() without a reference to self seems >> strange >> >> Thanks for your help >> >> class CustomMethod: >> def method1(self): >> .... >> def method2(self): >> .... >> def method3(self): >> .... >> >> def getAllMethod(self): >> return [self.method1, self.method2, self.method3] >> >> def applyAll(self): >> for m in self.getAllMethod(): >> # how to call all methods ? >> # is it correct >> m() > > 1. return string names of required methods in getAllMethod > return ['method1', 'method2', 'method3'] > 2. use gettattr on self and then exetute methods in applyAll > def applyAll(self): > for method_name in self.getAllMethod(): > method = gettattr(self,method_name) > method() #execute method now > > Except for extra lookup time, what would this buy you ??? From tshopshire at gmail.com Thu Aug 28 18:45:28 2008 From: tshopshire at gmail.com (Tyler Shopshire) Date: Thu, 28 Aug 2008 22:45:28 GMT Subject: PyDoc in Windows Vista Message-ID: I can't seem to access the pydoc sever from my web browser. I start the server from the command prompt and everything seems to be working fine, then I got to http://localhost:8888/ and it doesn't work. I also tried starting the graphical mode with the -g parameter but I still cannot use PyDoc. It works on my Ubuntu Partition so I do know how to use it. Any help is appreciated. From NO_Kroeger at gmx.de Tue Aug 19 14:58:11 2008 From: NO_Kroeger at gmx.de (=?UTF-8?B?TmlscyBPbGl2ZXIgS3LDtmdlcg==?=) Date: Tue, 19 Aug 2008 20:58:11 +0200 Subject: Python Query: Related to locking a resource in a multithreaded environment In-Reply-To: References: Message-ID: <48AB17C3.80408@gmx.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, I don't think the global interpreter lock is what you need ... read here for reference: http://docs.python.org/api/threads.html My approach what be to write one class for reading and writing to the configuration and make that class thread-safe using the RLock. Then you create one and only one instance of this class and let all your threads use (not import) that one instance. You could achieve that "one and only one" either by having a main program which creates the instance and pass the reference to each thread via its __init__ or you implement the Configuration class as a singleton like this: class Singleton(object): """ A simple example implementing the singleton design pattern in python """ #we need two class attributes (which translate to static attributes in java) __lock = Lock() #a lock for thread safety __instance = None #and to remember the one instance #first of all: make pythons usual way of creating objects # unusable because we cannot just hide them as one would in java # or C++ def __new__(cls, *args, **kwargs): pass def __init__(self): pass @classmethod def getInstance(cls, *args, **kwargs): """ The famous gatInstance method which resturns the one instance of our class. params: cls - reference to the class *args - the tuple of arguments paassed by position **kwargs - the dictionary of arguments passed by keyword """ #enter critical section cls.__lock.acquire() try: if cls.__instance is None: #use the superclasses __new__ for creation cls.__instance = object.__new__(cls, *args, **kwargs) #place initialisation code (everything which #would usually happen in __init__) here cls.__instance.SomeInt = 1 finally: #leave critical section cls.__lock.release() return cls.__instance Add your methods for accessing as instance methods to this class and get the same instance of this class in each thread by calling Singleton.getInstance(). Hope that helps Regards Nils tarun schrieb: > I think I need something called global interpreter lock which is > accessible to all the threads. But I am not sure how to implement this. > > > On Tue, Aug 19, 2008 at 11:28 AM, tarun > wrote: > > Hello All, > > I've a configuration.ini file. This particular can be accessed by > several threads of my application. Each thread can read/write > configuration parameters from/to the configuration.ini file. I am > using threading (Rlock) to lock the resource (configuration.ini > file) while accessing it from any thread. I use the file available > at http://www.voidspace.org.uk/python/configobj.html for read/write. > > I did the following in one of my files: > > import threading > class Synchronization: > def __init__(self): > self.mutex = threading.RLock() > > Now this I can create instances of the class Synchronization and use > acquire/release to work on the shared resource. But every thread > would need to import this class and hence each thread would create a > separate instance of the class. This means several lock variables. > But I think we need a global lock flag that is accessible across all > the threads. > > How do i do this? > > Please let me know ASAP. > > Thanks In Advance, > Tarun > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list -----BEGIN PGP SIGNATURE----- iD8DBQFIqxfCzvGJy8WEGTcRApe+AJ9MNqWI9FOsJIKuTKxy8ZNSGYTy2gCdHtGc clDPMMAPRoIxsBvVm4ygi6U= =vIPW -----END PGP SIGNATURE----- -------------- next part -------------- A non-text attachment was scrubbed... Name: NO_Kroeger.vcf Type: text/x-vcard Size: 162 bytes Desc: not available URL: From deets at nospam.web.de Mon Aug 4 14:08:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 04 Aug 2008 20:08:29 +0200 Subject: Garbage collection of recursive inner function In-Reply-To: <784c3984-b32e-466a-8542-f93f2dc453d1@27g2000hsf.googlegroups.com> References: <784c3984-b32e-466a-8542-f93f2dc453d1@27g2000hsf.googlegroups.com> Message-ID: <6foustFcj6oaU1@mid.uni-berlin.de> from.future.import at gmail.com schrieb: > Hi, > > I encountered garbage collection behaviour that I didn't expect when > using a recursive function inside another function: the definition of > the inner function seems to contain a circular reference, which means > it is only collected by the mark-and-sweep collector, not by reference > counting. Here is some code that demonstrates it: > > === > def outer(): > > def inner(n): > if n == 0: > return 1 > else: > return n * inner(n - 1) > > return 42 > > import gc > gc.set_debug(gc.DEBUG_SAVEALL) > print outer() > gc.collect() > print gc.garbage > === > > Output when executed: > $ python internal_func_gc.py > 42 > [, ( 0xb7dec3ec: function object at 0xb7dbd3ac>,), 0xb7dbd3ac>] > > Note that the inner function is not called at all, it is only defined. > If the inner function is moved outside the scope of the outer > function, gc.garbage will be empty. If the inner function is inside > but not recursive, gc.garbage will also be empty. If the outer > function is called twice, there will be twice as many objects in > gc.garbage. > > Is this expected behaviour? Collecting an object when its refcount > reaches zero is preferable to collecting it with mark-and-sweep, but > maybe there is a reason that a circular reference must exist in this > situation. I want to check that first so I don't report a bug for > something that is not a bug. The reference comes from the closure of inner. And inner is part of the closure, so there is a circular reference. I don't see a way to overcome this - consider the following code: def outer(): def inner(): inner() if random.random() > .5: return inner How is the GC/refcounting to know if it can create a reference or not? Diez From castironpi at gmail.com Sat Aug 9 00:47:42 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 8 Aug 2008 21:47:42 -0700 (PDT) Subject: interpreter vs. compiled References: <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <4rl294duo83eujnq6tjbk215mavpl87o9r@4ax.com> <43f519dd-6763-4cc0-a6d2-1e671da54c2c@d45g2000hsc.googlegroups.com> <1fdd10ae-581c-428d-9268-8fca8b99aff4@2g2000hsn.googlegroups.com> <5f742714-1d29-467e-82fe-d88253542657@79g2000hsk.googlegroups.com> <33d58bd6-ba49-4517-9d79-884988025e50@r66g2000hsg.googlegroups.com> <8df89e54-b106-4bfb-9937-974c8d2d4776@j22g2000hsf.googlegroups.com> Message-ID: <6486eee8-fcc8-4b6b-8cf9-b6dae3dd9b41@m3g2000hsc.googlegroups.com> On Aug 5, 2:09?pm, "paulo.jpi... at gmail.com" wrote: > Regarding exploring processor instructions. > > Lets say you compile a C program targeting x86 architecture, with > optimizations > turned on for speed, and let the compiler automatic select MMX and SSE > instructions > for numeric code. > > I have now a program that executes very fast, and does what I want > very well. Now > when I execute it on a x86 processor with the new SSE 4 instructions, > it will not > matter, because it cannot take advantage of them. > > With a JIT is different. Assuming that the JIT is also aware of the > SSE 4 instructions, > it might take advantage of this new set, if for a given instruction > sequence it is better > to do so. > > For the usage of the profile guided optimizations, here go a few > examples. > > The JIT might find out that on a given section, the vector indexes are > always correct, so > no need for bounds verification is needed. Or if the language is a OOP > one, it might come > to the conclusion that the same virtual method is always called, so > there is no need for > a VMT lookup before calling the method, thus it replaces the already > generated code by > a direct call. > > Or that a small method is called enough times, so it would be better > to inline it instead. > > Here are a few papers about profile guided optimizations: > > http://rogue.colorado.edu/EPIC6/EPIC6-ember.pdfhttp://www.cs.princeton.edu/picasso/mats/HotspotOverview.pdf > > Of course most of these optimizations are only visible in applications > that you use for longer > that 5m. > > -- > Paulo There are two things I can emphasize after reading the papers and your post. One is the benefit of distributing an incompletely compiled module, which is that it makes machine-targeted specializations possible right then and there, and does not require recompiling from the source on the original author's/distributor's budget. Even if there's no YOURSUITE.EXE built, the code is still in a state where you can make one, by only needing JIT.LIB on your machine. The second is the massive use of lightweight profiling in choosing optimizations in JIT. One of the advantages is inlining common function sequences, that you would either have to detect yourself, or inline everything, to achieve. What are some others? From ndbecker2 at gmail.com Wed Aug 6 08:44:21 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 06 Aug 2008 08:44:21 -0400 Subject: Find class of an instance? Message-ID: Sounds simple, but how, given an instance, do I find the class? From lists at cheimes.de Sat Aug 16 17:42:19 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 16 Aug 2008 23:42:19 +0200 Subject: Good python equivalent to C goto In-Reply-To: <48a744b6$0$299$7a628cd7@news.club-internet.fr> References: <48a744b6$0$299$7a628cd7@news.club-internet.fr> Message-ID: Kurien Mathew wrote: > Hello, > > Any suggestions on a good python equivalent for the following C code: > There are various ways to write your example in Python. For example while loopCondition: condition = 1 while condition: if condition1: break if condition2: break if condition3: break stmt1 stmt2 condition = 0 else: stmt3 stmt4 The else block of while isn't execute if you break out of while. You can emulate multiple gotos with exceptions. In general you shouldn't try to mimic C in Python code. C like Python code is often hard to read and slower than well designed Python code. From deets at nospam.web.de Wed Aug 27 03:42:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 27 Aug 2008 09:42:00 +0200 Subject: unexpected from/import statement behaviour In-Reply-To: <1a66cf9d-88e3-437f-aa4d-ec13a153cab1@25g2000prz.googlegroups.com> References: <42780654-8a54-470e-a494-ca53fd0504f5@p25g2000hsf.googlegroups.com> <1a66cf9d-88e3-437f-aa4d-ec13a153cab1@25g2000prz.googlegroups.com> Message-ID: <6hkeq8Flqcu4U2@mid.uni-berlin.de> alex23 schrieb: > nisp wrote: >> I've always been convinced of the equivalence of the two ways of using >> the import statement but it's clear I'm wrong :-( > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> from sys import stderr >>>> import sys >>>> sys.stderr is stderr > True > > Behaviourly, I'm finding no difference between the two either. > > Could you cut & paste a minimal example that isn't producing the > correct behaviour, and perhaps mention what type of OS you're using? You did not read this part of the post: """ I'm not able to capture its stderr and of course I would like not to do this kind of change. """ He tries to set sys.stderr to a new stream and capture the print statements, but fails to do so because he created a local alias. Diez From matthew at woodcraft.me.uk Thu Aug 28 15:58:10 2008 From: matthew at woodcraft.me.uk (Matthew Woodcraft) Date: Thu, 28 Aug 2008 19:58:10 GMT Subject: Python svn bindings for Subversion? References: <9bfdb452scm8ks5ci27a6so2f3rc3nsvv2@4ax.com> Message-ID: <873ako6hf1.fsf@golux.woodcraft.me.uk> Mike B writes: > I'm trying to get Subversion 'hook scripts' working on an Ubuntu box and the > following fails. > > from svn import fs, repos, core, delta [...] > 'svn' appears to be a SWIG wrapper and could be what I'm looking for, but I > cannot find it anywhere. > > Can anyone point me in the right direction. It's maintained as part of the main Subversion distribution. http://svn.collab.net/viewvc/svn/trunk/subversion/bindings/swig/ In Ubuntu, it should be in the python-subversion package. -M- From castironpi at gmail.com Sat Aug 16 18:20:52 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 16 Aug 2008 15:20:52 -0700 (PDT) Subject: mmap and ctypes References: <48a74b26$0$23839$426a34cc@news.free.fr> Message-ID: On Aug 16, 4:42?pm, "Michel Claveau - NoSpam SVP ; merci" wrote: > Hi! > > I use mmap for interchange data between Python & Autoit. ?For that, I > use (Autoit's side) a little DLL. > This DLL can, perhaps, be used with ctypes. > > @-salutations > -- > Michel Claveau Say more-- what DLL? @-greetings From fabiofz at gmail.com Fri Aug 1 13:36:20 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Fri, 1 Aug 2008 14:36:20 -0300 Subject: Pydev 1.3.19 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.19 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Code Analysis: Not all unused imports are shown in the message anymore (could give problems saving workspace). * Code Analysis: Fixed problem on double cycle in list comprehension. * Interpreter config: The initial parse of the modules is much faster. Release Highlights in Pydev: ---------------------------------------------- Pydev 1.3.19 Release highlights ---------------------- * Eclipse 3.2: Interactive console working * Eclipse 3.4: Hyperlinks working * Eclipse 3.4: Move / rename working * raw_input() and input(): functions are now changed when a program is launched from eclipse to consider a trailing '\r' * Ctr+/: Changed to toggle comment (instead of only comment) -- patch from Christoph Pickl * Pydev package explorer: Link working with compare editor * Auto-indent: Fixed problem when smart indent was turned off * Debugger: Better inspection of internal variables for dict, list, tuple, set and frozenset * Console: When a parenthesis is entered, the text to the end of the line is no longer deleted * Code Formatter: can deal with operators (+, -, *, etc) * Code Formatter: can handle '=' differently inside function calls / keyword args * Problem while navigating pydev package explorer fixed * Race condition fixed in PythonNatureStore/PythonNature (thanks to Radim Kubacki) * Halt fixed while having multiple editors with the same file (with the spell service on) * Pythonpath is no longer lost on closed/imported projects * Applying a template uses the correct line delimiter * NPE fixed when creating editor with no interpreter configured * Hyperlink works in the same way that F3 (saves file before search) What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From med.swl at gmail.com Fri Aug 22 18:43:22 2008 From: med.swl at gmail.com (Medardo Rodriguez (Merchise Group)) Date: Fri, 22 Aug 2008 18:43:22 -0400 Subject: >> and << operators? In-Reply-To: References: Message-ID: <4891add70808221543w195fb88am2d4f84a52c6eb195@mail.gmail.com> On Fri, Aug 22, 2008 at 6:30 PM, defn noob wrote: > What does >> and << do? Normally they are bitwise operators: >> Shifts bits right << Shifts bits left print 1 << 3 8 because 8 = 00001000 in binary Regards From wtanksleyjr at gmail.com Mon Aug 4 12:39:28 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Mon, 4 Aug 2008 09:39:28 -0700 (PDT) Subject: Bidirectional Generators References: <8e2cf6b7-4b5f-4701-8a4c-bc779ed7305c@m45g2000hsb.googlegroups.com> <976df308-3855-4f2b-a82a-dacba480e7d7@i76g2000hsf.googlegroups.com> Message-ID: <4f1ac687-2401-4ee7-acd9-b0eb3ef8e910@v39g2000pro.googlegroups.com> Paddy wrote: > What's one of them then? I'm sorry, I don't know what you mean. Meanwhile, more pertinently: I did get my generator working, and then I replaced it with a class that did the same thing in less than a quarter of the number of lines. So... I'm not going to worry about that anymore. My use case obviously wasn't the right one for them. I'm still curious, though, whether anyone's written any code that actually uses yield _and_ send() to do anything that isn't in the original PEP. > - Paddy. -Wm From google at mrabarnett.plus.com Wed Aug 20 05:56:07 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 20 Aug 2008 02:56:07 -0700 (PDT) Subject: How to stop iteration with __iter__() ? References: <836a8d0a-ce00-40da-bc7c-f390ead0acfe@w7g2000hsa.googlegroups.com> <92953733-f834-4e84-a83c-eb0edc9a8a05@1g2000pre.googlegroups.com> Message-ID: <7cf65c80-8667-45fb-88b3-795c9c6c4ecc@m36g2000hse.googlegroups.com> On Aug 20, 12:11?am, John Machin wrote: > On Aug 20, 5:06 am, Terry Reedy wrote: > > > In your case, the standard Python idiom, as Jon said, is > > > it = iter(iterable) > > next(it) # 2.6, 3.0 > > for for item in iterable: > > ? ?f(item) > > or, perhaps, for completeness/paranoia/whatever: > > it = iter(iterable) > try: > ? ?headings = it.next() # < 2.5 > except StopIteration: > ? ?# code to handle empty > for item etc etc > I think it needs to be: it = iter(iterable) try: headings = it.next() # < 2.5 except StopIteration: # code to handle empty else: for item etc etc because you don't want to iterate over the remainder if it has already stopped yielding! :-) > > The alternative is a flag variable and test > > > first = True > > for for item in iterable: > > ? ?if first: > > ? ? ?first = False > > ? ?else: > > ? ? ?f(item) > > > This takes two more lines and does an unnecessary test for every line > > after the first. ?But this approach might be useful if, for instance, > > you needed to skip every other line (put 'first = True' after f(item)). > > and change its name from 'first' to something more meaningful ;-) > > Cheers, > John From vinay_sajip at yahoo.co.uk Mon Aug 25 19:57:57 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Mon, 25 Aug 2008 16:57:57 -0700 (PDT) Subject: Why do all my loggers start auto-disabled? References: <13922a38-da45-4608-9bab-2bc153a07eae@k7g2000hsd.googlegroups.com> Message-ID: Calling fileConfig() disables any loggers existing at the time of the call. Make sure you call fileConfig() before instantiating any loggers; after that you can instantiate as many as you like, and they will all be enabled. Make sure you don't call fileConfig() again, as in that call all loggers which are not named in the configuration will be disabled. The reason why fileConfig() disables existing loggers is that it was designed as a one-off configuration (which completely replaces any existing configuration with that specified in the config file) - not as an incremental configurator. Best regards, Vinay Sajip From bearophileHUGS at lycos.com Fri Aug 8 15:31:03 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 8 Aug 2008 12:31:03 -0700 (PDT) Subject: Psycho question References: Message-ID: <476017db-4872-4cf5-a1cc-b3fc81ecaaf0@f36g2000hsa.googlegroups.com> John Krukoff: > One possibility for the performance difference, is that as I understand > it the psyco developer has moved on to working on pypy, and probably > isn't interested in keeping psyco updated and optimized for new python > syntax. > Somebody correct me if I'm wrong, but last I heard there's no > expectation of a python 3.0 compatible version of psyco, either. But for me on the short term Python 3 is probably more important than pypy, and I'd like to keep using Psyco... Bye, bearophile From cjw at ncf.ca Sat Aug 9 08:47:35 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 09 Aug 2008 08:47:35 -0400 Subject: Why is ::= used as assignment operator in doc statements? In-Reply-To: <8763qa4n03.fsf@benfinney.id.au> References: <8763qa4n03.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > schaffe at gmail.com writes: > >> Why is statments expressed with ::= as the assigning operator? >> like: http://docs.python.org/ref/grammar.txt > > That page is part of the language reference. It shows, not Python > code, but a description of part of the Python grammar. See ??1.2 > . > Of historic interest is Extended Bachus-Naur Normal Form (EBNF): http://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form Colin W. From deets at nospam.web.de Mon Aug 18 04:52:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 18 Aug 2008 10:52:02 +0200 Subject: Bizarre method keyword-arg bug. In-Reply-To: References: Message-ID: <6gsrhiFh98kpU1@mid.uni-berlin.de> Jasper schrieb: > I'm stumped. I'm calling a method that has keyword args, but not > setting them, and yet one of them starts off with data?! > > The class definition begins like so: > > class BattleIntentionAction( BattleAction ): > def __init__( self, factionName, location, tactic='hold', > targetFacName='', terrainArgs=[], garrisonIds=[] ): > self.terrainArgs = terrainArgs > print terrainArgs > > The constructor is called somewhere else, like so: > act = BattleIntentionAction( facName, self.location ) > > > During this object's construction, terrainArgs is set to a list with > values corresponding to a previously created BattleIntentionAction! > Even more bizarre, the terrainArgs param is a testing formality, and > doesn't actually get used anywhere in my code -- the corresponding > attribute is always modified after object creation. Furthermore, this > doesn't happen with the other keyword args... > > Obviously, I'm glossing over a ton of code here, but I'm having a > tough time isolating this problem, as it seems to be very dependent on > events leading up to it. It feels like the sort of memory stomping > bug I remember seeing from days of yore when I hacked C++. :-( > > > I frankly don't understand how "terrainArgs" can have a value if > nothing is passed for it on the calling invocation, short of some > obscure compiler bug (this is Python 2.4.3). Am I being naive? Is > there some way I could be bringing this about myself? > > I can easily work around this weirdness by having the caller set > terrainArgs explicitly, but I can't shake the sensation that this > "fix" just masks some deeper flaw in my code. > This is a FAQ: http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm Diez From castironpi at gmail.com Wed Aug 6 13:04:51 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 6 Aug 2008 10:04:51 -0700 (PDT) Subject: Limits of Metaprogramming References: <0c56829a-7ad2-4ff2-b225-7981538e7c7a@j22g2000hsf.googlegroups.com> <07c3d5f8-563c-43bc-8772-5eb60de52c82@8g2000hse.googlegroups.com> <95cebacd-6221-478f-81ae-1040b1711b40@k13g2000hse.googlegroups.com> Message-ID: <5306b80e-81ff-43a5-a472-4f9f05764e4a@e39g2000hsf.googlegroups.com> On Aug 6, 7:24?am, Wilson wrote: > On Aug 4, 9:23?pm, castironpi wrote: > > > > > On Aug 4, 1:57?pm, Wilson wrote: > > > > On Aug 4, 6:49?pm, castironpi wrote: > > > > > Two, if all your methods will have uniform signatures and closures, > > > > you can store class methods as only their co_code objects: > > > > > >>> C.g.im_func.func_code.co_code > > > > > 'd\x00\x00S' > > > > > And fabricate them dynamically into full live types as needed. > > > > Thanks for your comments and advice. This second option intrigues me; > > > could you elaborate further, I don't follow you... > > > > Thanks Paul > > > Depending on the complexity of the functions, a code string could be > > all you need to store to determine (redetermine) a function's > > behavior. ?For something moderately simple, > > > def trans1( self, prev, trans ): > > ? ? ? ? if prev== 0 and trans== 'a': > > ? ? ? ? ? ? ? ? return 1 > > ? ? ? ? if prev== 1 and trans== 'b': > > ? ? ? ? ? ? ? ? return 0 > > ? ? ? ? return prev > > > I found you need to store code.co_nlocals, code.co_code, and > > code.co_consts, to distinguish from a blank stub. ?With extra > > variables, I needed code.co_names and code.co_varnames too. ?To > > recreate a code object completely, you need 12 variables (14 to > > include closures), some of which are composite objects and would need > > to be pickled to be stored. > > Still don't really understand this so I'm going to admit defeat. > Thanks all for your advice... Very much appreciated! I was describing an alternative to storing functions in a way that wasn't in serial in plain text. It was off-topic from state-machine transitions. Can you start with this? # state, input, next state transitions= [ ( 0, 'a', 1 ), ( 1, 'a', 2 ), ( 2, 'a', 0 ), ( 0, 'b', 0 ), ( 1, 'b', 0 ), ( 2, 'b', 2 ) ] What further? From anartz at anartz.cjb.net Mon Aug 11 11:30:06 2008 From: anartz at anartz.cjb.net (anartz at anartz.cjb.net) Date: Mon, 11 Aug 2008 09:30:06 -0600 Subject: =?UTF-8?B?UmU6IGR5bmFtaWNhbGx5IGNyZWF0aW5nIGh0bWwgY29kZSB3aXRoIHB5dGhvbi4uLg==?= In-Reply-To: <200808111315.m7BDFjqs045647@cjb.net> References: <200808111315.m7BDFjqs045647@cjb.net> Message-ID: <200808111530.m7BFUBbS047579@cjb.net> Sorry, my fault... I am trying to build a web application for data analysis. Basically some data will be read from a database and passed to a python script (myLibs.py) to build an image as follows. [CODE] f=urllib.urlopen("http://localhost/path2Libs/myLibs.py",urllib.urlencode(TheData)) print "Content-type: image/png\n" print f.read() f.close() [/CODE] This section behaves as expected, and I can see the chart on the web-page. Now, I would like to add some text and possibly more charts (generated in the same way) to my web-page. This is what I need help with. I tried to add some html code to the f variable (file-type variable) before and after the plot generated (see first post). When I load the page in a browser, I get a blank page, not even the chart (that I used to get) appears any more. There is no error messages in the server's error log, and when I run it as a python script I get the following output: Content-type: image/png\n My question: How can I use python to dynamically add descriptive comments (text), and possibly more charts to the web-page? Hope this is more explanatory. Thanks Anartz at anartz.cjb.net wrote : > Hi, > > how can I combine some dynamically generated html code (using python) with the output of a urllib.openurl() call? > > I have tried to use the StringIO() class with .write functions, but it did not work. Below is the code that does not work. > > [CODE] > f=StringIO.StringIO() > f.write('data analysis') > f.write(urllib.urlopen("http://localhost/path2Libs/myLibs.py", urllib.urlencode(TheData))) > f.write("") > > print "Content-type: text/html\n" > print f.read() > f.close() > [/CODE] > > What is wrong with this approach/code? Is there an easier way of doing it? > > Thanks. > > > > -- > http://mail.python.org/mailman/listinfo/python-list From dudeja.rajat at gmail.com Thu Aug 21 04:07:45 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Thu, 21 Aug 2008 09:07:45 +0100 Subject: Tkinter/WindowsXP - how to use checkbutton to toggle a label in GUI? Message-ID: Hi, I've a checkbutton in my GUI application which I want to work as: 1. it should be un-ticked by default, 2. should display a label in Gui, by default, 3. when user ticks the check button this should the above label goes off the screen and not longer is displayed. Please suggest how could I do this: my code for the check button and label is : #Check button varTestAll = IntVar() self.cbTestAll = Checkbutton(master, text="Test All", variable=varTestAll ) self.cbTestAll.grid(row = 12, column = 1, sticky = W, pady = 30, padx = 30) #Label - Version under Test self.lblVersionUnderTest = Label(master, \ text = "v2.1.5.0") self.lblVersionUnderTest.grid(row = 15, \ column = 2, \ sticky = W, \ padx = 30) Please suggest. Thanks, Rajat From deets at nospam.web.de Sun Aug 10 07:24:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 10 Aug 2008 13:24:53 +0200 Subject: some kind of trace facility ? In-Reply-To: References: Message-ID: <6g81g6Febc52U1@mid.uni-berlin.de> Stef Mientki schrieb: > hello, > > I want to investigate on a regular base the flow of my Python (most of > them using wxPython) programs. > So I want to have some log facilty, that logs things like > - every time a function / method is called > - the time spent in that function / method (or even better start / > finish time) > - in case the function / method has some predefined variables, the > values of these variables > - the caller > > As an extra condition, I'm only interested in my own program modules > (located in a specific subdirectory). > > Is there a module available that can perform such a task ? > Any hints to get started ? THere is the module profile and the sys.trace-hook. Diez From greg at cosc.canterbury.ac.nz Wed Aug 27 05:48:59 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 27 Aug 2008 21:48:59 +1200 Subject: ANN: Pyrex 0.9.8.5 Message-ID: Pyrex 0.9.8.5 is now available: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ Various minor bug fixes and improvements. What is Pyrex? -------------- Pyrex is a language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. From tarundevnani at gmail.com Tue Aug 19 01:58:43 2008 From: tarundevnani at gmail.com (tarun) Date: Tue, 19 Aug 2008 11:28:43 +0530 Subject: Python Query: Related to locking a resource in a multithreaded environment Message-ID: Hello All, I've a configuration.ini file. This particular can be accessed by several threads of my application. Each thread can read/write configuration parameters from/to the configuration.ini file. I am using threading (Rlock) to lock the resource (configuration.ini file) while accessing it from any thread. I use the file available at http://www.voidspace.org.uk/python/configobj.html for read/write. I did the following in one of my files: import threading class Synchronization: def __init__(self): self.mutex = threading.RLock() Now this I can create instances of the class Synchronization and use acquire/release to work on the shared resource. But every thread would need to import this class and hence each thread would create a separate instance of the class. This means several lock variables. But I think we need a global lock flag that is accessible across all the threads. How do i do this? Please let me know ASAP. Thanks In Advance, Tarun -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Aug 28 12:10:43 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 28 Aug 2008 18:10:43 +0200 Subject: List of modules available for import inside Python? In-Reply-To: <0f716a9c-8c24-4765-a8ca-381b09575d93@w7g2000hsa.googlegroups.com> References: <0f716a9c-8c24-4765-a8ca-381b09575d93@w7g2000hsa.googlegroups.com> Message-ID: pruebauno at latinmail.com wrote: >> Is there a way to view all the modules I have available for import >> from within Python? >> Like writing in the interpreter: >> import.modules >> >> Also, is there anything like Cpan for Python? > > Isn't the most obvious answer to the first question this link? depends on whether you want a list of the modules that you might be able to import, or the modules that are actually present on your system. From fredrik at pythonware.com Thu Aug 14 09:36:27 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 15:36:27 +0200 Subject: reading plist files In-Reply-To: References: Message-ID: William Purcell wrote: > This is how it cut and pasted.. > bplist00? > This is what it looks like in a text editor (emacs)... > bplist00\324^@^A^@^B^@^C^@^D^@^E^C1^@ looks like a binary file, and is definitely not XML. probably a binary property list: http://developer.apple.com/documentation/Cocoa/Conceptual/PropertyLists/Articles/SerializedPListsConcept.html From bearophileHUGS at lycos.com Sat Aug 30 10:04:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 30 Aug 2008 07:04:58 -0700 (PDT) Subject: Advice on the style to use in imports References: <3f0d61c40808300512x1dcd5061t19ad7323b7ef15e9@mail.gmail.com> Message-ID: Marco Bizzarri: > I'm just confused because PEP8 seems to suggest that the from module > import Class style is acceptable; is there a big "if you know what are > doing" before, which I'm unable to see? from somemodule import somename is often acceptable IHMO, but there are some things to consider: - you and the person that reads your code have to remember where somename comes from. So you can do it for well known names like izip or imap, but if you import lots of names from lots of modules, things may become too much complex. So often it can be better to import just the modules, and use somemodule.somename. - somemodule.somename is longer to write and to read, and if it's repeated many times it may worsen the program readability, making lines of code and expressions too much long and heavy. So you have to use your brain (this means that you may have to avoid standard solutions). Note that you can use a compromise, shortening the module name like this: import somemodule as sm Then you can use: sm.somename - somemodule.somename requires an extra lookup, so in long tight loops (if you don't use Psyco) it slows down the code. This can be solved locally, assigning a local name into a function/method (or even in their argument list, but that's a hack to be used only once in a while): localname = somemodule.somename Bye, bearophile From bearophileHUGS at lycos.com Wed Aug 13 13:35:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 13 Aug 2008 10:35:11 -0700 (PDT) Subject: Replace Several Items References: <513926b0-64fe-4fdc-bb33-bc4b8ad3ab10@a70g2000hsh.googlegroups.com> Message-ID: gjhames: > What's the better way to do it? Better is a relative term. If with better you mean "faster" (in some circumstances), then the translate method is your friend, as you can see its second argument are the chars to be removed. As first argument you can use something like: "".join(map(chr, xrange(256))) If your strings are unicode you will need something different (a dict with Null values for the key chars you want to remove). Bye, bearophile From bignose+hates-spam at benfinney.id.au Tue Aug 12 20:53:42 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 13 Aug 2008 10:53:42 +1000 Subject: Free software and video codecs References: <024fd4b4-2823-47f8-bd60-e6fd65db596a@b1g2000hsg.googlegroups.com> <4e28ce82-306d-4a53-84c1-37ac3642ee17@x41g2000hsb.googlegroups.com> <87r68wxgwn.fsf_-_@benfinney.id.au> <0125ce9e-edad-4413-b40b-67162a0c7def@r66g2000hsg.googlegroups.com> Message-ID: <87prodwx9l.fsf@benfinney.id.au> mimiyin at gmail.com writes: > Do you have a recommendation for how I can convert the quicktime and > flash movies to ogg? That would produce an inferior result, since the Quicktime and Flash movies have (I assume) already been converted to a lossy codec . To process that data again through another lossy codec will cause a poor result, similar to making a photocopy of a photocopy. Much better would be to start with the video in its non-lossy form (either uncompressed, or compressed only with some lossless codec) and use that as the source for conversion to Dirac or Theora. This is the same principle as making a photocopy from the original, rather than from another photocopy. Presumably the Quicktime and Flash videos were created from some original lossless data source. Any further encoding should be done from a source as close to the original as possible. > I've had a hard time finding conversion apps for the Mac.I'd also be > happy to turn over the original movies to anyone who can help me > convert them. I don't know anything about MacOS applications. I do know that the BBC developed the "Schroedinger" (Schr?dinger) implementation for encoding video to Dirac; you may want to see if that's available for your OS. -- \ ?I cannot conceive that anybody will require multiplications at | `\ the rate of 40,000 or even 4,000 per hour ?? ?F. H. Wales, 1936 | _o__) | Ben Finney From srikrishnamohan at gmail.com Tue Aug 19 09:27:58 2008 From: srikrishnamohan at gmail.com (km) Date: Tue, 19 Aug 2008 18:57:58 +0530 Subject: ANN: Resolver One 1.2 released In-Reply-To: <59f2f4c8-5713-4779-8bcf-e1683645bd64@a70g2000hsh.googlegroups.com> References: <59f2f4c8-5713-4779-8bcf-e1683645bd64@a70g2000hsh.googlegroups.com> Message-ID: Hi, sounds great - but disappointing to find it only available on window$. Is there any Linux release in near future ??? KM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ On Tue, Aug 19, 2008 at 6:10 PM, giles.thomas at gmail.com < giles.thomas at gmail.com> wrote: > We are proud to announce the release of Resolver One, version 1.2 - > the largest IronPython application in the world, we think, at 38,000 > lines of production code backed up by 150,000 lines of unit and > functional tests. > > Resolver One is a Rapid Application Development tool for analysing and > presenting business data, using a familiar spreadsheet interface > combined with a powerful IronPython-based scripting capability that > allows you to insert your own code directly into the recalculation > loop. > > For version 1.2, we have on big headline feature; a new function > called > RunWorkbook that allows you to "call" one spreadsheet from another, > passing in parameters and pulling out results - just like functions, > but > without having to code the function by hand. This allows you to mix > spreadsheet-based and code-based logic, using the best paradigm for > the job in hand. > > We've also added a whole bunch of usability enhancements - the full > (long!) changelist is up on our website, or you can see a screencast: > > > It's free for non-commercial use, so if you would like to take a > look, > you can download it from our website: > (registration no longer > required). > > > Best regards, > > Giles > -- > Giles Thomas > MD & CTO, Resolver Systems Ltd. > giles.tho... at resolversystems.com > +44 (0) 20 7253 6372 > > Try out Resolver One! > > 17a Clerkenwell Road, London EC1M 5RD, UK > VAT No.: GB 893 5643 79 Registered in England and Wales as company > number 5467329. > Registered address: 843 Finchley Road, London NW11 8NA, UK > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lanny at freshells.ch Wed Aug 13 19:13:14 2008 From: lanny at freshells.ch (Lanny) Date: Wed, 13 Aug 2008 16:13:14 -0700 Subject: Random Problems Message-ID: Well the othe day I was making a program to make a list of all the songs in certian directorys but I got a problem, only one of the directorys was added to the list. Heres my code: import random import os import glob songs = glob.glob('C:\Documents and Settings\Admin\My Documents\LimeWire\Saved\*.mp3') asongs = glob.glob('C:\Documents and Settings\Admin\My Documents\Downloads\*\*.mp3') songs.append(asongs) asongs = glob.glob('C:\Documents and Settings\Admin\My Documents\Downloads\*\*\*.mp3') songs.append(asongs) asongs = glob.glob('C:\Documents and Settings\Admin\My Documents\Downloads\*\*\*\*.mp3') songs.append(asongs) pick = random.choice(songs) all goes well but pick awalys is from the first directory but songs awalys includes all the files I want it to. Im baffaled. -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- From mccredie at gmail.com Thu Aug 28 18:54:58 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 28 Aug 2008 15:54:58 -0700 (PDT) Subject: Python in a Nutshell -- Book vs Web References: Message-ID: On Aug 28, 3:05?pm, "W. eWatson" wrote: > I read an Amazon of Python in a Nutshell. The first edition is supposedly > much like the web site. What web site? The second edition apparently adds > more to the book than the web site. O'Reilly seems to just read all of the available documentation and regurgitate it in book form. The "in a nutshell" series being the worst offender. Most of "Python in a Nutshell" tells you the same information that you can find at http://docs.python.org, which is probably "the web site" being referenced. Matt From mathieu.prevot at gmail.com Thu Aug 7 15:56:14 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Thu, 7 Aug 2008 21:56:14 +0200 Subject: kill thread Message-ID: <3e473cc60808071256g6b359032tb72115a2d86fad37@mail.gmail.com> Hi, I have a threading.Thread class with a "for i in range(1,50)" loop within. When it runs and I do ^C, I have the error [1] as many as loops. I would like to catch this exception (and if possible do some cleanup like in C pthreads) so the program finishes cleanly. Where and how can I do this ? in __run__ ? __init__ ? a try/except stuff ? Thanks, Mathieu [1]: ^CException in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 486, in __bootstrap_inner self.run() File "./youfetch.py", line 148, in run self.getids() File "./youfetch.py", line 145, in getids self.ids.append(self.getidsatpage(i)) File "./youfetch.py", line 138, in getidsatpage self.child = subprocess.Popen(cmd.split(),stdout=subprocess.PIPE) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/subprocess.py", line 594, in __init__ errread, errwrite) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/subprocess.py", line 1011, in _execute_child self.pid = os.fork() KeyboardInterrupt From Lie.1296 at gmail.com Thu Aug 28 08:52:18 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 28 Aug 2008 05:52:18 -0700 (PDT) Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> <6fe0scFaus40U1@mid.uni-berlin.de> <6bc8bc07-eab0-4303-b8a4-c9470f96038d@c65g2000hsa.googlegroups.com> <6fe1n2Faus40U3@mid.uni-berlin.de> <6ff0ifFbbpfbU1@mid.uni-berlin.de> Message-ID: On Aug 1, 6:35?am, "Diez B. Roggisch" wrote: > squishywaf... at gmail.com schrieb: > > > On Jul 31, 10:47 am, "Diez B. Roggisch" wrote: > >> I take the freedom to do so as I see fit - this is usenet... > > > Fine, then keep beating a dead horse by replying to this thread with > > things that do nobody any good. It seems like there are a lot better > > way to waste time, though. > > You mean like trying to wrap ones head around the rather simple Python C > API, not getting a callback mechanism implemented? > > For the record: I've wrapped C-libs myself, including callbacks. Been > there, done that, discovered (years later) cytpes, been there for good. > > > The Python/C API can get me back further without reliance on third- > > party libraries than ctypes. > > You don't consider your own library a third party lib? And unless you're > wrapping C++, you're opinion is as uninformed as it is wrong. > > > It also isn't subject to the quirks that > > ctypes is on platforms other than Windows (the target application runs > > on Windows, Mac, and eventually Linux once the original distributor > > has drivers for the device). I'm not even sure ctypes could load the > > lib/driver the distributor packaged. > > Oh please. I'm 98% working on linux & osx. ctypes does a great job on > these platforms. > > Regarding your objections I can only say: whatever the python runtime > can load because of the underlying ld, ctypes can load. simply because > they are the same. If *that* was the actual cause of problems, we > wouldn't even talk about callbacks here. > > > So really, I appreciate the option in ctypes, it's good stuff. But > > it's not for this project. > > Stop finding lame excuses for not wanting to ditch the work you've done > in favor of a easier solution. You like your code, you want to keep it, > you want to discover the intricasies of the Python C API? Be my guest. > > But stop embarassing yourself inventing reasons like licensing or linker > problems you don't support with any facts whatsoever. > > > Once again, the original question stands for anyone who has experience > > with the Python/C API callbacks. > > You know what? Just for the fun of it, I'll take a stab at it. > > ? It's easy: Create a "proxy-function" that matches the prototype of the > c8allback which converts the passed arguments to python values using the > C-api. Then call the registered python function using > PyObject_CallFunction. > > Convert the return-value back to C, and return it. > > Make the function get the PyObject* for the call fetch from a global > variable you set in the register-callback function, where you also > register the proxy-function for the first time, or de-register if the > passed value is None or such. > > Have fun. > > Diez Zen's lesson for today: THOU SHALT NOT MESS WITH ANY PYTHON'S SEMI-GODS, DEMI-GODS, AND PYTHON'S GOD. You're lucky Diez still want to help you with your attitude like that. May I remind you that we here helps you for free in our free time, be rude, especially to a frequent member, and you'll get what you deserve. From pavlovevidence at gmail.com Fri Aug 29 21:45:27 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 29 Aug 2008 18:45:27 -0700 (PDT) Subject: When to use try and except? References: <8a2dd955-6641-493d-b7eb-3e29c14686a5@26g2000hsk.googlegroups.com> <914fde08-5084-455f-ac68-bef7e06cc3dc@i76g2000hsf.googlegroups.com> Message-ID: <3a6cde6c-885e-470f-a7b1-0752b63e8f94@y21g2000hsf.googlegroups.com> On Aug 29, 1:56?pm, cnb wrote: > On Aug 29, 7:40?pm, Daniel wrote: > > > > > On Aug 29, 11:23?am, cnb wrote: > > > > If I get zero division error it is obv a poor solution to do try and > > > except since it can be solved with an if-clause. > > > > However if a program runs out of memory I should just let it crash > > > right? Because if not then I'd have to write exceptions everywhere to > > > prevent that right? > > > > So when would I actually use try-except? > > > > If there can be several exceptions and I just want to catch 1 or 2? > > > Like > > > try: > > > ? ? blahaba > > > except SomeError: > > > ? ? do something > > > I'm not sure whay you're trying to do, but I think catching a > > ZeroDivisionError exception is a good use of try-except. > > > I'm also not sure that I would say you just let a program crash if it > > runs out of memory. ?I would think that from the user perspective, you > > would want to check memory conditions and come up with an exception > > indicating that some memory threshold has been reached. ?When that > > exception is raised you should indicate that to the user and exit > > gracefully. > > A ZeroDivisionError is better avoided wth an if-clause, don't you > think? It is a predictable exception... Many Pythonistas would disagree with that. Anyway there are some types of errors for which catching exceptions is more robust because there's a gap between the time something is checked and the time it's used, between which the circumstances can change. For instance, the following test can be subject to sporadic failures: if os.path.exists(filename): f = open(filename) Between the call to os.path.exists and the call to open, the file could be removed by another process, which will result in an unhandled exception. Also, sometimes files fail to open for other reasons, such as permissions. For things like divide-by-zero, there's no way a local value can change between the zero test and the operation (except in uncommon situations), so it's just a matter of style which way you do it. Carl Banks From maduma at pt.lu Tue Aug 19 10:45:12 2008 From: maduma at pt.lu (maduma at pt.lu) Date: Tue, 19 Aug 2008 07:45:12 -0700 (PDT) Subject: who to call a list of method inside the class itself References: <95910272-2045-4170-ab6e-549489b12108@d77g2000hsb.googlegroups.com> Message-ID: On Aug 19, 4:33 pm, Fredrik Lundh wrote: > mad... at pt.lu wrote: > > Is the following code is ok. who to call all method. > > It is working but the call to m() without a reference to self seems > > strange > > > Thanks for your help > > > class CustomMethod: > > def method1(self): > > .... > > def method2(self): > > .... > > def method3(self): > > .... > > > def getAllMethod(self): > > return [self.method1, self.method2, self.method3] > > > def applyAll(self): > > for m in self.getAllMethod(): > > # how to call all methods ? > > # is it correct > > m() > > what happens when you run the code? > > The code it is running fine but i just wondering if it's the syntax is correct (avoid any side effect) -Stephane From brtzsnr at gmail.com Wed Aug 27 07:49:40 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Wed, 27 Aug 2008 04:49:40 -0700 (PDT) Subject: use of Queue References: Message-ID: <39824ccb-7e35-4ef4-a150-692af64c0ba5@j1g2000prb.googlegroups.com> On Aug 27, 1:06?pm, Gerhard H?ring wrote: > Alexandru Mosoi wrote: > > how is Queue intended to be used? I found the following code in python > > manual, but I don't understand how to stop consumers after all items > > have been produced. I tried different approaches but all of them > > seemed incorrect (race, deadlock or duplicating queue functionality) > > > ? ? def worker(): > > ? ? ? ? while True: > > ? ? ? ? ? ? item = q.get() > > ? ? ? ? ? ? ? ?if item is None: > ? ? ? ? ? ? ? ? ? ?break > > > ? ? ? ? ? ? do_work(item) > > ? ? ? ? ? ? q.task_done() > > > ? ? q = Queue() > > ? ? for i in range(num_worker_threads): > > ? ? ? ? ?t = Thread(target=worker) > > ? ? ? ? ?t.setDaemon(True) > > ? ? ? ? ?t.start() > > > ? ? for item in source(): > > ? ? ? ? q.put(item) > > # stop all consumers > for i in range(num_worker_threads): > ? ? ?q.put(None) > > > > > ? ? q.join() ? ? ? # block until all tasks are done > > This is how I do it. > > -- Gerhard Your solution works assuming that you know how many consumer threads you have :). I don't :). More than that, it's not correct if you have more than one producer :). Having a sentinel was my very first idea, but as you see... it's a race condition (there are cases in which not all items are processed). From ewertman at gmail.com Sat Aug 30 10:57:50 2008 From: ewertman at gmail.com (Eric Wertman) Date: Sat, 30 Aug 2008 10:57:50 -0400 Subject: Writing to ms excel In-Reply-To: References: Message-ID: <92da89760808300757n5f4f05dpad8c16e8a61bd36e@mail.gmail.com> > I'm trying to find a way to write data to excel cells (or to be more > specific to an .xls file), let's say for the sake of argument, data > readen from a file (although it will be calculated in the process). > I've been searching, but couldn't find any examples which allows that. The answer will depend on your base os.. if you are on windows there will be some options using the COM interfaces I bet.. but I don't know anything about them. If you are on a unix based os, your choices are limited. If you can, I would just write to a csv file and open it with Excel. If you have to interface with an exsisting excel file, you can try http://pypi.python.org/pypi/xlrd , but it may not support writing xls files, still. From gagsl-py2 at yahoo.com.ar Sun Aug 24 06:32:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 24 Aug 2008 07:32:47 -0300 Subject: EOF References: Message-ID: En Fri, 22 Aug 2008 16:53:58 -0300, Wojtek Walczak escribi?: > On Fri, 22 Aug 2008 22:18:37 +0530, Anjanesh Lekshminarayanan wrote: > >> Im trying to download a file from a server. But how do I detect EOF ? > > Whenever read() method returns empty string/list. > > >> while f1: # When to stop ? > retval = f1.read() > if not retval: > break > f2.write(retval) Those read() should be read(size) - read() tries to get the whole contents in memory. Anyway, shutil.copyfileobj already implements that logic. -- Gabriel Genellina From http Fri Aug 29 02:42:29 2008 From: http (Paul Rubin) Date: 28 Aug 2008 23:42:29 -0700 Subject: Lining Up and PaddingTwo Similar Lists References: <4mKtk.11732$vn7.11459@flpi147.ffdc.sbc.com> Message-ID: <7x4p54fhka.fsf@ruckus.brouhaha.com> "W. eWatson" writes: > [a.dat, c.dat, g.dat, k.dat, p.dat] > [a.txt, b.txt, g.txt, k.txt r.txt, w.txt] > > What I need is to pair up items with the same prefix and use "None", > or some marker, to indicate the absence of the opposite item. This is functionally influenced but should be straightforward: dat = ['a.dat', 'c.dat', 'g.dat', 'k.dat', 'p.dat'] txt = ['a.txt', 'b.txt', 'g.txt', 'k.txt', 'r.txt', 'w.txt'] # just get the portion of the filename before the first period def prefix(filename): return filename[:filename.find('.')] # make a dictionary mapping prefixes to filenames def make_dict(plist): return dict((prefix(a),a) for a in plist) pdat = make_dict(dat) ptxt = make_dict(txt) # get a list of all the prefixes, use "set" to remove # duplicates, then sort the result and look up each prefix. for p in sorted(set(pdat.keys() + ptxt.keys())): print pdat.get(p), ptxt.get(p) From ptmcg at austin.rr.com Wed Aug 6 19:24:03 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 6 Aug 2008 16:24:03 -0700 (PDT) Subject: Parsing of a file References: Message-ID: On Aug 6, 3:14?pm, "Shawn Milochik" wrote: > Regular expressions will do the trick nicely. > Or just use str.split, and create dicts using dict(list_of_tuples) constructor. This code creates a single dict for the input lines, keyed by id. Each value contains elements labeled 'id', 'ra', and 'mjd'. -- Paul data = """\ Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames 5 Set 1 Field f31448: Ra=20:24:58.13 Dec=+79:39:43.9 MJD=53370.06811620 Frames 5 Set 2 Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames 5 Set 3 Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames 5 Set 4 Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames 5 Set 5 Field f30560: Ra=20:27:01.82 Dec=+74:47:50.3 MJD=53370.06860400 Frames 5 Set 6 Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames 5 Set 7 Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames 5 Set 8 Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames 5 Set 9 Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames Set 10 """.splitlines() d = dict( (rec.split()[1][:-1], dict([('id',rec.split()[1][:-1])] + [map(str.lower,f.split('=')) for f in rec.split()[2:5]] ) ) for rec in data ) print d.keys() for id in d.keys(): print d[id].items() From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 13 03:13:33 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 13 Aug 2008 09:13:33 +0200 Subject: Python web framework choice In-Reply-To: References: Message-ID: <48a28992$0$19706$426a74cc@news.free.fr> david.lyon at preisshare.net a ?crit : > Quoting Mahdi : > >> I need to develop a medium-sized database web application for my >> company. Given that: >> I don't know much about building web UI(s) but i have fair knowledge >> about HTML & My schedule is tight. >> >> a recommendation is v v v appreciated. > > I'm in the same boat.... a few weeks in..... > > I've found that most of the python frameworks are based on the python > cherrypy server. "most" ? Turbogears < 2.x set aside (TG2 runs on top of pylons), I didn't heard of much cherrypy-based frameworks (except possibly for home-grown unpublished ones). > Thats a good place to work out how the webserver part > of the non-zope systems work. ie django etc Django was initially designed to run on mod_python, then added support for fcgi and wsgi IIRC. > So that is the webserver part.... > > then you need to build your webpages.... > > I have found Cheetah.... which is pretty powerful... that is a > templating system to build the actual pages from the database content... from whatever content... > that works nicely... There are quite a couple other templating systems. One could mention Mako, Genshi, TAL, Breve, Jinja, etc... > obviously django and pylons wrap all these basics into a 'product'... Django has it's own templating system (and it's own ORM)[1]. Pylons (which is a 100% wsgi-based framework) default to Mako (templating) and SQLAlchemy (ORM), but these are only defaults [1] you can of course use other templating systems and ORMs with it, but then you'd loose most of what makes Django interesting... From tjreedy at udel.edu Fri Aug 8 17:08:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 08 Aug 2008 17:08:57 -0400 Subject: small issue with Idle In-Reply-To: References: <2c192ba3-bc94-4f55-9d59-0fe14b8069a0@z6g2000pre.googlegroups.com> Message-ID: Mike Driscoll wrote: > There's a free version of Wing IDE that has an IDLE-like interface > that doesn't have this issue...or you could just use the command line > version of IDLE. What are you referring to? From deets at nospam.web.de Tue Aug 26 11:56:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Aug 2008 17:56:13 +0200 Subject: atomic increment References: <6297cf93-5eec-4bf3-9104-0605a82f7186@p10g2000prf.googlegroups.com> Message-ID: <6hinduFmfmsrU1@mid.uni-berlin.de> Alexandru Mosoi wrote: > how can i do an atomic read+increment? something like > > with lock: > old = atomic_int > atomic_int += 1 > > but in one operation As above - the lock (under the assumption that it is actually a threading.Lock) will ensure that. Diez From gagsl-py2 at yahoo.com.ar Fri Aug 22 12:59:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 22 Aug 2008 13:59:41 -0300 Subject: urllib2 HTTPBasicAuthHandler and resumingbroken downloads References: <63d6d10e-c023-4ec6-9f11-0687d7ae8254@k37g2000hsf.googlegroups.com> Message-ID: En Fri, 22 Aug 2008 08:55:57 -0300, Brendan escribi?: > On Aug 21, 3:57?pm, "Gabriel Genellina" > wrote: >> En Thu, 21 Aug 2008 15:37:41 -0300, Brendan >> ? >> escribi : >> >> > Is there any way to resume an https file download using urllib2 and an >> > HTTPBasicAuthHandler? >> >> You should provide the Range header (and probably If-Range too) in the ? >> request.http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 > > Ug. Why does everything in Python boil down to reading rfcs? It really > slows us non computer science types down. I'll probably spend a day on > this instead of an hour. I did search the web but had no luck finding > an example, so I posted here as a last resort. The easy way is to use wget... If you want a Python example, go to the Python cookbook: http://code.activestate.com/recipes/langs/python/ enter "resume download" in the search box, and the very first recipe shows how to use the Range header. -- Gabriel Genellina From grflanagan at gmail.com Mon Aug 18 04:11:18 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Mon, 18 Aug 2008 01:11:18 -0700 (PDT) Subject: online tutorials? References: <6013d717-7c4b-4f34-8f58-d9a1e7387f5c@k37g2000hsf.googlegroups.com> Message-ID: On Aug 18, 12:53?am, Gits wrote: > I want to learn how to program in python and would like to know if you > guys know of any free online tutorials. ?Or is it too complicated to > learn from a site or books? Some texts and examples here: http://thehazeltree.org/ hth G. From gustavo at grahal.net Tue Aug 12 17:18:48 2008 From: gustavo at grahal.net (Gustavo Rahal) Date: Tue, 12 Aug 2008 21:18:48 +0000 (UTC) Subject: xmlrpc client through proxy to https server Message-ID: Hi I'm trying to build a xmlrpc client that uses a proxy to connect to a xmlrpc server in https. I've googled and came up with a code snippet that doesn't actually work. What is missing? class ProxiedTransport(xmlrpclib.Transport): def set_proxy(self, proxy): self.proxy = proxy def make_connection(self, host): self.realhost = host # i've also tried httplib.HTTPS, in this case I get # "socket.sslerror: (1, 'error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol')" h = httplib.HTTP(self.proxy) #trivial setup for ssl socket # proxy_connect='CONNECT %s:%s HTTP/1.1\r\n'%('ftp3.linux.ibm.com', '443') # user_agent='User-Agent: python\r\n' # proxy_pieces=proxy_connect+user_agent+'\r\n' # proxy=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # proxy.connect(('9.47.67.150', 3128)) # proxy.sendall(proxy_pieces) # response=proxy.recv(8192) # ssl = socket.ssl(proxy, None, None) # sock = httplib.FakeSocket(proxy, ssl) # h.sock = sock return h def send_request(self, connection, handler, request_body): connection.putrequest("POST", 'https://%s%s' % (self.realhost, handler)) def send_host(self, connection, host): connection.putheader('Host', self.realhost) p = ProxiedTransport() p.set_proxy('9.47.67.150:3128') server = xmlrpclib.Server('https://ftp3.linux.ibm.com/rpc/index.php', transport=p) print server.user.ingroup("username", "group") ------------------- The Result: xmlrpclib.ProtocolError: The method i'm calling is "implemented". If I try straight xmlrpc connection through a machine that is not behind a firewall things work fine. Appreciate help Thanks Gustavo From pw at panix.com Fri Aug 22 21:52:27 2008 From: pw at panix.com (Paul Wallich) Date: Fri, 22 Aug 2008 21:52:27 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: Martin Gregorie wrote: > On Fri, 22 Aug 2008 22:56:09 +0000, sln wrote: > >> On Thu, 21 Aug 2008 09:11:48 -0500, rpw3 at rpw3.org (Rob Warnock) wrote: >> >>> sln at netherlands.com> wrote: >>> *IS* raw machine code, *NOT* assembler!! >> [snip] >> >> I don't see the distinction. >> Just dissasemble it and find out. >> > There's a 1:1 relationship between machine code and assembler. > Unless its a macro-assembler, of course! > >> Each op is a routine in microcode. >> That is machine code. Those op routines use machine cycles. >> > Not necessarily. An awful lot of CPU cycles were used before microcode > was introduced. Mainframes and minis designed before about 1970 didn't > use or need it and I'm pretty sure that there was no microcode in the > original 8/16 bit microprocessors either (6800, 6809, 6502, 8080, 8086, > Z80 and friends). > > The number of clock cycles per instruction isn't a guide either. The only > processors I know that got close to 1 cycle/instruction were all RISC, > all used large lumps of microcode and were heavily pipelined. > > By contrast the ICL 1900 series (3rd generation mainframe, no microcode, > no pipeline, 24 bit word) averaged 3 clock cycles per instruction. > Motorola 6800 and 6809 (no microcode or pipelines either, 1 byte fetch) > average 4 - 5 cycles/instruction. One problem with this discussion is that the term "microcode" isn't really well-defined. There's the vertical kind, the horizontal kind, with and without internal control-flow constructs, and then there are various levels of visibility to the user -- see e.g. the pdp-8 manual, where "microcoding" is used to mean piling the bits for a bunch of instructions together in the same memory location, which works fine as long as the instructions in question don't use conflicting sets of bits. paul From fredrik at pythonware.com Wed Aug 13 18:39:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 00:39:37 +0200 Subject: Can't use DB name with dashes using pymssql ??? In-Reply-To: <65c3648d0808131530w29728a78ib646dde89481e656@mail.gmail.com> References: <65c3648d0808131354x333a7e0cica29217a26f4ce42@mail.gmail.com> <65c3648d0808131530w29728a78ib646dde89481e656@mail.gmail.com> Message-ID: Samuel Morhaim wrote: > I believe there is a bug in Python.. _mssql ... I am not too familiar > with Python yet, but after adding several breakpoints and watching the > variable, the last step of pymssql.py is > > # open the connection > con = _mssql.connect(dbhost, dbuser, dbpasswd) > > > con.select_db(dbbase) > At this point the contents of dbbase is "Gcare4UI-B6_3_dev" (no > quotes)... however, the immediate error is that > "Gcare4UI" does not exist. reading the documentation might help: http://pymssql.sourceforge.net/troubleshooting.html#dbid From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 28 09:49:42 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 28 Aug 2008 15:49:42 +0200 Subject: PYTHONPATH and modules In-Reply-To: <954d5e6f-f809-483f-ab6c-4d5c14f8c809@m36g2000hse.googlegroups.com> References: <954d5e6f-f809-483f-ab6c-4d5c14f8c809@m36g2000hse.googlegroups.com> Message-ID: <48b6acba$0$18567$426a74cc@news.free.fr> Juan a ?crit : > Hi > > I am programming a little script that makes use of a module I > developed before. The utils are inside the directory src of the > directory utils, and the package is nutum.utils. The script is in the > directory src inside the directory sysinfo, and the package is > nutum.sysinfo. Won't work, cf below. > Well, if not clear, this is the list of files: > > ls -lR ~/workspace (imaginary output): > > utils/src/nutum/__init__.py > utils/src/nutum/utils/__init__.py > utils/src/nutum/utils/general.py > utils/src/nutum/utils/elapsed_time.py > utils/src/nutum/utils/execute_command.py > utils/src/nutum/utils/size_units.py > > sysinfo/src/nutum/__init__.py > sysinfo/src/nutum/sysinfo/__init__.py > sysinfo/src/nutum/sysinfo/sysinfo.py > sysinfo/src/nutum/sysinfo/modules/__init__.py > sysinfo/src/nutum/sysinfo/modules/base_module.py > sysinfo/src/nutum/sysinfo/modules/os.py A Python package is a filesystem directory with an __init__.py file in it. In your above layout, you have two *distinct, unrelated* packages both named nutum. The first found in sys.path will shadow the second. You either need to rename one, or "refactor" your layout to have utils and sysinfo under the same root package, ie: workspace/src/nutum/__init__.py workspace/src/nutum/utils/__init__.py workspace/src/nutum/utils/general.py workspace/src/nutum/utils/elapsed_time.py workspace/src/nutum/utils/execute_command.py workspace/src/nutum/utils/size_units.py workspace/src/nutum/sysinfo/__init__.py workspace/src/nutum/sysinfo/sysinfo.py workspace/src/nutum/sysinfo/modules/__init__.py workspace/src/nutum/sysinfo/modules/base_module.py workspace/src/nutum/sysinfo/modules/os.py HTH From goldnery at gmail.com Fri Aug 22 09:09:10 2008 From: goldnery at gmail.com (Gandalf) Date: Fri, 22 Aug 2008 06:09:10 -0700 (PDT) Subject: gridSizer inside a panel element Message-ID: <8d7dd1ee-596c-4810-b03c-97f3a00d2c7b@56g2000hsm.googlegroups.com> why when I try to insert gridSizer to a panel which already inside another panel the gridSizer doesn't work? this is the code: panel3= wx.Panel(self, -1, (0, 60), size=(400, 240) , style=wx.SIMPLE_BORDER); panel3.SetBackgroundColour('#dadadb') panel = wx.Panel(panel3, wx.ID_ANY, style=wx.SIMPLE_BORDER, size=(150, 60)) panel.SetBackgroundColour("#fffFFF") bmp = wx.ArtProvider.GetBitmap(wx.ART_TIP, wx.ART_OTHER, (16, 16)) inputIco = wx.StaticBitmap(panel, wx.ID_ANY, bmp) labelThree= wx.StaticText(panel, wx.ID_ANY, 'Hello') label2=wx.StaticText(panel, wx.ID_ANY, 'Pease, Quite, Hello, Shalom') topSizer = wx.BoxSizer(wx.VERTICAL) gridSizer = wx.GridSizer(rows=2, cols=1, hgap=5, vgap=5) input = wx.BoxSizer(wx.HORIZONTAL) output = wx.BoxSizer(wx.HORIZONTAL) input.Add((20,20), 1, wx.EXPAND) # this is a spacer input.Add(inputIco, 0, wx.ALL, 5) input.Add(labelThree, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5) output.Add((20,20), 1, wx.EXPAND) # this is a spacer output.Add(label2, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5) gridSizer.Add(input, 0, wx.ALIGN_LEFT) gridSizer.Add(output, 0, wx.ALIGN_RIGHT) topSizer.Add(gridSizer, 0, wx.ALL|wx.EXPAND, 5) panel.SetSizer(topSizer) From aahz at pythoncraft.com Sun Aug 10 20:06:46 2008 From: aahz at pythoncraft.com (Aahz) Date: 10 Aug 2008 17:06:46 -0700 Subject: ANN: Chandler 1.0 References: Message-ID: In article , Heikki Toivonen wrote: > >The Chandler Project is pleased to announce the release of Chandler >Desktop 1.0! Congrats! It's been a long, strange road.... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From grante at visi.com Sun Aug 3 18:57:10 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 03 Aug 2008 17:57:10 -0500 Subject: Decimals not equalling themselves (e.g. 0.2 = 0.2000000001) References: Message-ID: On 2008-08-03, Larry Bates wrote: >> However, it appears that when n in 1/n is a power of two, the decimal >> does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2 >> and not 0.20000000000000001? >> >> This discrepancy is very minor, but it makes the whole n-th root >> calculator inaccurate. :\ > > What are they teaching in computer science classes these days? When I was an undergrad the only courses that dealt with FP issues were classes on numerical analysis. I don't even know if numerical analysis classes were required for CS majors. I think most of us in that class were engineering majors. -- Grant Edwards grante Yow! I wish I was a at sex-starved manicurist visi.com found dead in the Bronx!! From Scott.Daniels at Acm.Org Sat Aug 23 09:55:07 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 23 Aug 2008 06:55:07 -0700 Subject: Using Tkinter In-Reply-To: <78a600a0-1285-4659-92b1-ffca44410750@o40g2000prn.googlegroups.com> References: <78a600a0-1285-4659-92b1-ffca44410750@o40g2000prn.googlegroups.com> Message-ID: J-Burns wrote: > Hello. Im a bit new to using Tkinter and im not a real pro in > programming itself... :P. Need some help here. OK, looks like you are getting direct answers, but I thought I'd mention an easy way to experiment with Tkinter programming. If you start Idle with the "-n" switch (*), then anything you do shares the same "mainloop" as Idle, and your window manipulation is "live". This means, that immediately after typing in: >>> import Tkinter >>> f = Tkinter.Frame() You will see the frame f show up. You can experiment directly with watching the effects of calls that you make in the interactive interpretter. (*) Easy way to do this: On some systems, associate a button with "pythonw -m idlelib.idle -n". On a Windows system with an Idle shortcut/button/icon already: Copy the shortcut/button/icon Right-click the shortcut and select the "properties" menu. On the "General" tab of the Properties window: Give the shortcut a nicer name (I use Idle25-n for mine). On the "Shortcut" tab of the properties window, add a space and a -n to the target line. Click OK, and try out your new button. --Scott David Daniels Scott.Daniels at Acm.Org From hdante at gmail.com Wed Aug 6 19:00:05 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Wed, 6 Aug 2008 16:00:05 -0700 (PDT) Subject: Parsing of a file References: Message-ID: On Aug 6, 3:55?pm, Tommy Grav wrote: > I have a file with the format > > Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames ? > 5 Set 1 > Field f31448: Ra=20:24:58.13 Dec=+79:39:43.9 MJD=53370.06811620 Frames ? > 5 Set 2 > Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames ? > 5 Set 3 > Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames ? > 5 Set 4 > Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames ? > 5 Set 5 > Field f30560: Ra=20:27:01.82 Dec=+74:47:50.3 MJD=53370.06860400 Frames ? > 5 Set 6 > Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames ? > 5 Set 7 > Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames ? > 5 Set 8 > Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames ? > 5 Set 9 > Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames ? > 5 Set 10 > > I would like to parse this file by extracting the field id, ra, dec ? > and mjd for each line. It is > not, however, certain that the width of each value of the field id, ? > ra, dec or mjd is the same > in each line. Is there a way to do this such that even if there was a ? > line where Ra=****** and > MJD=******** was swapped it would be parsed correctly? > > Cheers > ? ?Tommy Did you consider changing the file format in the first place, so that you don't have to do any contortions to parse it ? Anyway, here is a solution with regular expressions (I'm a beginner with re's in python, so, please correct it if wrong and suggest better solutions): import re s = """Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames 5 Set 1 Field f31448: Ra=20:24:58.13 Dec=+79:39:43.9 MJD=53370.06811620 Frames 5 Set 2 Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames 5 Set 3 Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames 5 Set 4 Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames 5 Set 5 Field f30560: Dec=+74:47:50.3 Ra=20:27:01.82 MJD=53370.06860400 Frames 5 Set 6 Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames 5 Set 7 Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames 5 Set 8 Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames 5 Set 9 Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames 5 Set 10""" s = s.split('\n') r = re.compile(r'Field (\S+): (?:(?:Ra=(\S+) Dec=(\S+))|(?:Dec=(\S+) Ra=(\S+))) MJD=(\S+)') for i in s: match = r.findall(i) field = match[0][0] Ra = match[0][1] or match[0][4] Dec = match[0][2] or match[0][3] MJD = match[0][5] print field, Ra, Dec, MJD From p at ulmcnett.com Thu Aug 28 19:28:03 2008 From: p at ulmcnett.com (Paul McNett) Date: Thu, 28 Aug 2008 16:28:03 -0700 Subject: [1,2,3] exactly same as [1,2,3,] ? In-Reply-To: References: Message-ID: <48B73483.1020000@ulmcnett.com> mh at pixar.com wrote: > x=[1,2,3] > and > x=[1,2,3,] > > are exactly the same, right? When confronted with this type of question, I ask the interpreter: {{{ mac:~ pmcnett$ python Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> [1,2,3] == [1,2,3,] True }}} Paul From flarefight at googlemail.com Wed Aug 27 12:51:29 2008 From: flarefight at googlemail.com (ff) Date: Wed, 27 Aug 2008 09:51:29 -0700 (PDT) Subject: Custom PyQt4 TableWidget References: Message-ID: <00ef9f45-0b92-481d-b3a8-8bff98b3c0ed@m45g2000hsb.googlegroups.com> > > setSelectionMode()? > > Phil Ive tried that, it does half the job, it stops you selecting more than one item in the table at any one time but it doesnt stop the top-left 'thing', thanks though, From a.schmolck at gmail.com Fri Aug 8 12:37:01 2008 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Fri, 08 Aug 2008 17:37:01 +0100 Subject: python-mode is missing the class browser References: <6361fac8-3bfb-4d7e-b13b-84261ebeea10@b1g2000hsg.googlegroups.com> Message-ID: "Adam Jenkins" writes: > On Fri, Aug 8, 2008 at 7:32 AM, Michele Simionato > wrote: >> On Aug 7, 5:55 pm, Alexander Schmolck wrote: > ... >> >> I have solved by using ipython.el which was already installed. For the >> sake of >> future googlers using Ubuntu 8.04, emacs and ipython, it is enough if >> you just add >> >> (setq ipython-command "/usr/bin/ipython") >> (require 'ipython) >> >> to your .emacs. It is nice since I get the occasion to try ipython.el >> which I am >> sure I will like ;) > > So, I'm looking at the .el, but I'm not sure. What else does > ipython.el give you than just the ipython shell? What else could you possibly want? :) Seriously, ipython.el is a simple kludge whose only function is to make python-mode work with ipython (rather than python[*]). Despite this certain primitiveness (c.f. slime), Emacs+ipython makes quite a powerful development environment, significantly more so than ipython alone or emacs + python. Most importantly thre is: 1. debug. Try it: write some code that will throw an unhandled exception, and just type ``debug``. Type ``u`` and ``d`` to go up and down the stack frame, and see the right file and line pop up in emacs. I really find that combined with the ability to do arbitrary things with the things I find on the stack incredibly useful for development. 2. ? and ?? as well as ed. To get help on foo you just write ``foo?``. To get its source code as well type ``foo??``. Finally to edit the code that correspond's to foo's class or function definition (also works on class instances)) type ``ed foo`` (IIIRCk the default behavior is autoexecution, so you might want to re-alias). 3. Autocompletion with tab. 4. run (including -d and -p options). Try ``run?`` 5. Matplotlib and gui stuff works interactively. (-pylab cmdline option) 6. Convenient Shell interaction (ls, !, int) and interpolation from and too python 7. Pretty printing. But there's plenty more stuff. The most useful in terms of added functionality via emacs is 1, but isearch and emacs editing power make the ipython shell output also noticably more useful (and thus things like ?, ?? and pretty printing). cheers, 'as [*] Inter alia the prompt parsing stuff needs to be different and the ansi color formatting needs to be dealt with. From fredrik at pythonware.com Tue Aug 19 10:33:10 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Aug 2008 16:33:10 +0200 Subject: who to call a list of method inside the class itself In-Reply-To: <95910272-2045-4170-ab6e-549489b12108@d77g2000hsb.googlegroups.com> References: <95910272-2045-4170-ab6e-549489b12108@d77g2000hsb.googlegroups.com> Message-ID: maduma at pt.lu wrote: > Is the following code is ok. who to call all method. > It is working but the call to m() without a reference to self seems > strange > > Thanks for your help > > class CustomMethod: > def method1(self): > .... > def method2(self): > .... > def method3(self): > .... > > def getAllMethod(self): > return [self.method1, self.method2, self.method3] > > def applyAll(self): > for m in self.getAllMethod(): > # how to call all methods ? > # is it correct > m() what happens when you run the code? From alia_khouri at yahoo.com Wed Aug 27 19:01:26 2008 From: alia_khouri at yahoo.com (Alia Khouri) Date: Wed, 27 Aug 2008 16:01:26 -0700 (PDT) Subject: doctesting practices Message-ID: <037c599c-5e64-4527-b112-95d57c6f8531@f63g2000hsf.googlegroups.com> I was wondering the other day how other pythonistas incorporate doctests into their coding practices. I have acquired the habit of keeping an editor open in one window and an ipython instance open in another and then using something similar to the format of the module below. In this case, I incorporate a switch in the _test function whereby covered=False means the doctest is still being written (and is easy to test using the command line) and covered=True means it is somewhat complete and ready to be incorporated into a test suite. This still seems to me to be somewhat hackish and convoluted (execing into globals() and all), and one wonders if there are better coding workflows out there that specifically incorporate doctests as the primary means of testing. Thanks in advance for any feedback AK ''' Simple doctest of a module usage:: >>> fib(0) 0 >>> fib(1) 1 >>> fib(10) 55 >>> fib(15) 610 ''' def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) def _test(covered=False): import doctest if covered: doctest.testmod() else: exec doctest.script_from_examples(__doc__) in globals() if __name__ == '__main__': _test() From Lie.1296 at gmail.com Fri Aug 15 06:56:26 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 15 Aug 2008 03:56:26 -0700 (PDT) Subject: You advice please References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> Message-ID: <8ca31461-4ae7-4cbe-87ea-3aa25570df9e@p31g2000prf.googlegroups.com> On Aug 13, 6:14?pm, Hussein B wrote: > Hey, > I'm a Java/Java EE developer and I'm playing with Python these days. > I like the Python language so much and I like its communities and the > Django framework. > My friends are about to open a Ruby/Rails shop and they are asking me > to join them. > I don't know what, sure I'm not leaving Java, but they are asking me > to stop learning Python and concentrate on Ruby/Rails. A real programmer can learn as much language as he pleases and tell him that concentrating on one language is always a bad idea, since that narrows the mind and diversing language learning is great since it allows you to think of a problem from different angles (especially if the nature of the languages are very different, like one object oriented language and one functional language and one procedural and another dynamic language and another static language). > The sad fact (at least to me), Ruby is getting a lot of attention > these days. I don't know, but the data (http://www.tiobe.com/index.php/content/ paperinfo/tpci/index.html and http://www.langpop.com/) shows that python is more popular than ruby in most cases, nearly by a factor of two. > Why Python isn't getting this attention although is a much more mature > language and it is used by many big, big names? > And do I dare to say it is much more charming? > What do you think of Ruby/Rails? do they worth learning and working > with? Yes, every language have its own good and bad (yeah, even assembly). I have only brushed Ruby once though, so I can't give detailed explanation about it. A good teacher would encourage his students to learn from other masters even though he might be one of the most prominent expert in the subject, a good teacher would even encourage his students to learn from sides that opposed his side of view (learn from your enemy[1]). [1] The usage of the word "enemy" is over-exaggerated. > Any way, I'm not leaving Python and I will try to study it every time > I get a chance... > Thanks. From gagsl-py2 at yahoo.com.ar Thu Aug 14 23:34:44 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 15 Aug 2008 00:34:44 -0300 Subject: Cutting and Pasting in Windows IDLE References: <4dc0cfea0808120904o507da4tdf855e01994802ff@mail.gmail.com> Message-ID: En Tue, 12 Aug 2008 13:04:05 -0300, Victor Subervi escribi?: > A couple of weeks ago I asked how to cut and paste multiple lines in the > Windows IDLE interface. I can only paste one line at a time! > Frustrating. I > want it to work like my Linux interpreter. Why doesn?t it? Please help. Instead of complaining here, report a bug at http://bugs.python.org/ -- Gabriel Genellina From coolman.guron at gmail.com Thu Aug 14 04:47:16 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Thu, 14 Aug 2008 01:47:16 -0700 (PDT) Subject: Read from serial port References: <4ddf48b8-983a-44bf-a579-fd58a16feb3a@x41g2000hsb.googlegroups.com> Message-ID: On Aug 14, 6:11 am, mmrash... at gmail.com wrote: > Hi, > I am newbie in python. I am working on Telit GM862 GPS/GPRS module > which has python interpreter built in. But it seems this problem is > pretty much related to general python structure. > > I need a promt/terminal when the device is connected to PC. If user > enters a command by serial port and press "Enter" then the data is > read by the device and work on the command. This is similar to > readline() function. Unfortunately there is no readline() function for > GM862 device. The following functions are available for serial port > data receive- > > SER.read() - reads whole string at a time from buffer > SER.receive(timeout) - reads if there is any input in the buffer > andwait for the input upto timeout > SER.receivebyte(timeout) - reads if there is any byte sent in the > buffer and wait for the input upto timeout > > Now, is this possible to build a readline() using the functions above? > Can I redirect the terminal or serial port data to receive it as a > whole string when entered "\n"? > > Please advise me how can I solve this problem. > > Thanks a lot. Well i dont think its much of a problem. What i think you should be doing is to read the data into a secondary buffer. it could be a simple string or a specialized buffer class. You would need a method to update() this secondary buffer. ie read from port and append the read data to our buffer. That done you can easily make a readline function. lol i think even a 15yr old can make a readline() from here. btw does ur gm862 support multiple thread? if yes u can put the update() function code and also a method launcher when ever a particular command is sent to the device using a serial connection! hope it helps ! BJ From ewertman at gmail.com Thu Aug 14 14:39:08 2008 From: ewertman at gmail.com (Eric Wertman) Date: Thu, 14 Aug 2008 14:39:08 -0400 Subject: a question about mysqldb In-Reply-To: <20080814183036.DB3D21E4007@bag.python.org> References: <20080814183036.DB3D21E4007@bag.python.org> Message-ID: <92da89760808141139s4ee9ec98w4c59cc2d3a35a939@mail.gmail.com> Just to make sure I understand what you are showing me here: > columns = ('tID', 'tNote') > table_name = 'tmp' > sql = 'select %s from %s where tID=:1' % ( ', '.join(columns), table_name) > cursor.execute(sql, (1,)) > > # sql is now 'select tID, tNote from tmp where tID=:1' > # note the comma in argument tuple to execute (1,) This means I could use this type of syntax? sql = 'SELECT (date,time,name,size,count,stuff,flavor) FROM crazyTable where monster=:1 and feet=:2 and price=:3' cursor.execute(sql,('cookie','3',77.44)) ? I've not encountered that argument style before. From castironpi at gmail.com Sat Aug 30 00:28:43 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 29 Aug 2008 21:28:43 -0700 (PDT) Subject: struct.Struct random access References: <4beb85a8-38eb-4f8e-bc30-024fe3e3b8fa@y21g2000hsf.googlegroups.com> Message-ID: <71141c6e-32d4-4cb3-89da-15c2a1ea07b4@b1g2000hsg.googlegroups.com> On Aug 29, 10:30?pm, Tim Roberts wrote: > castironpi wrote: > > >CMIIW correct me if I'm wrong, I don't think that pack_into returns a > >value the way that pack does. > > Sorry, I was not aware that struct.pack_into and struct.unpack_from already > existed (they were added in Python 2.5). ?I thought you were proposing them > as new additions. > > Because of that, the rest of my post doesn't make much sense. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. I was a lot less enthusiastic too when I discovered 'PyObject_AsWriteBuffer'. Nevertheless I think it could be instructive as well as a benefit. The ctypes conversion, cast( buffer_p + offset ), is a bit of a kludge. With the introduction of 'namedtuple' type, I think it falls right in line with the direction Python is going in. It might suffice to merely expose the 'offset' member of the items in the array of 'formatcode'. Though, the addition of the dictionary to lookup offsets by field name could offset the benefit somewhat. From tjreedy at udel.edu Fri Aug 29 14:56:20 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 29 Aug 2008 14:56:20 -0400 Subject: Using class-attribute as key to sort? In-Reply-To: <712b9e5d-9127-4213-8478-8cf49349068e@a1g2000hsb.googlegroups.com> References: <712b9e5d-9127-4213-8478-8cf49349068e@a1g2000hsb.googlegroups.com> Message-ID: cnb wrote: > In median grade, can I sort on Review-grade somehow? Google "Python sort key attribute" the first hit (after your post) is http://wiki.python.org/moin/HowTo/Sorting Find 'attribute' on that page for your answer (two options). From timothy.grant at gmail.com Mon Aug 11 11:33:54 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Mon, 11 Aug 2008 08:33:54 -0700 Subject: Wildcards for regexps? In-Reply-To: <7de4bd2e-bb0e-44b8-b7ed-24ca7f46ab2b@25g2000hsx.googlegroups.com> References: <7de4bd2e-bb0e-44b8-b7ed-24ca7f46ab2b@25g2000hsx.googlegroups.com> Message-ID: On Sun, Aug 10, 2008 at 9:10 PM, ssecorp wrote: > If I have an expression like "bob marley" and I want to match > everything with one letter wrong, how would I do? > so "bob narely" and "vob marley" should match etc. At one point I needed something like this so did a straight port of the double-metaphone code to python. It's horrible, it's ugly, it's non-pythonic in ways that make me cringe, it has no unit tests, but it does work. -- Stand Fast, tjg. [Timothy Grant] From bj_666 at gmx.net Thu Aug 28 01:12:55 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Aug 2008 05:12:55 GMT Subject: [Q] How to ignore the first line of the text read from a file References: Message-ID: <6hmqenFmpekqU1@mid.uni-berlin.de> On Wed, 27 Aug 2008 21:11:26 -0700, youngjin.michael at gmail.com wrote: > I want to read text line-by-line from a text file, but want to ignore > only the first line. I know how to do it in Java (Java has been my > primary language for the last couple of years) and following is what I > have in Python, but I don't like it and want to learn the better way of > doing it. > > file = open(fileName, 'r') > lineNumber = 0 > for line in file: > if lineNumber == 0: > lineNumber = lineNumber + 1 > else: > lineNumber = lineNumber + 1 > print line > > Can anyone show me the better of doing this kind of task? input_file = open(filename) lines = iter(input_file) lines.next() # Skip line. for line in lines: print line input_file.close() Ciao, Marc 'BlackJack' Rintsch From dblubaugh at belcan.com Tue Aug 26 17:41:04 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Tue, 26 Aug 2008 17:41:04 -0400 Subject: Using Python to shared memory resources between Linux and Windows In-Reply-To: <6hj8rvFmlbhkU1@mid.uni-berlin.de> References: <6hj8rvFmlbhkU1@mid.uni-berlin.de> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3804CF5B81@AWMAIL04.belcan.com> Diez, What you have said is extremely concerning. I am now using VMware. With Linux as the Master and windows as the guest operating system. I was wondering if you have ever had to develop a share memory resource between Linux and windows within a Vmware setup? Thanks for the help. I will not be forgotten, David Blubaugh -----Original Message----- From: Diez B. Roggisch [mailto:deets at nospam.web.de] Sent: Tuesday, August 26, 2008 4:54 PM To: python-list at python.org Subject: Re: Using Python to shared memory resources between Linux and Windows Blubaugh, David A. schrieb: > To All, To whom else if I may ask? > I was wondering if it was possible to utilize python to share a memory > resource between a linux and windows system?? It should be stated > that both the Linux (CENTOS 5) and windows are physically located on > the same computer. Is any of this possible? No, not as that. You can use IPC-mechanisums such as XMLRPC, CORBA or Pyro. But software such as VMWare or VirtualBox tries hard to *not* let guest and host os influence each other. Diez This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From atrooja1998 at gmail.com Fri Aug 29 02:45:24 2008 From: atrooja1998 at gmail.com (atrooja1998 at gmail.com) Date: Thu, 28 Aug 2008 23:45:24 -0700 (PDT) Subject: computer support Message-ID: <01e84436-c94a-42e4-b5db-2ce0f5908498@k30g2000hse.googlegroups.com> hello every body in the group From med.swl at gmail.com Fri Aug 22 17:14:08 2008 From: med.swl at gmail.com (Medardo Rodriguez (Merchise Group)) Date: Fri, 22 Aug 2008 17:14:08 -0400 Subject: Regex on a huge text In-Reply-To: References: <4891add70808221319o1dba87e2gb0d5793737e6227a@mail.gmail.com> Message-ID: <4891add70808221414o248e4c16x5e0fa871e9c3bd48@mail.gmail.com> On Fri, Aug 22, 2008 at 4:48 PM, Terry Reedy wrote: > Does not grep only work a line at a time? Just like the code below? My understanding was that if the regex contains "^" and "$", it will matches in the full file. I wasn't never test it. I tested just before, and didn't work :( If you have a notion of the maximum amount of lines, there is an easy solution. Regards From hniksic at xemacs.org Mon Aug 25 10:22:55 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 25 Aug 2008 16:22:55 +0200 Subject: Equivalents of Ruby's "!" methods? References: <87d4jxutrd.fsf@benfinney.id.au> Message-ID: <874p59uqbk.fsf@mulj.homelinux.net> "Simon Mullis" writes: > There is no equivalent in Python (as far as I know, and I'm only in > my second week of Python so I'm more than likely incorrect!). Python uses strings for that purpose, which works well due to their immutability. Python automatically interns strings used in source code that look like identifiers, so memory is saved. An even closer equivalent of symbols are interned strings (see the "intern" built-in), but they are not as nice to work with as "real" symbols. From roopesh.raj at gmail.com Wed Aug 20 23:10:59 2008 From: roopesh.raj at gmail.com (Roopesh) Date: Wed, 20 Aug 2008 20:10:59 -0700 (PDT) Subject: How to make xss safe strings Message-ID: <919a78ae-8ed8-41ab-a283-6c642462b712@m45g2000hsb.googlegroups.com> Hi, How can I make a string XSS safe? Will simply .replace('<','<').replace('>','>').... do the work? Or are there some other issues to take into account?. Is there already a function in python which will do this for me. Regards Roopesh From __peter__ at web.de Fri Aug 29 14:58:18 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 29 Aug 2008 20:58:18 +0200 Subject: Memory Leek, critique me. Thanks!!! References: Message-ID: Kevin McKinley wrote: > # I posted a few days ago about a memory leak that I think i'm having > # with my first Tkinter program. I've had trouble pinpointing what is > # wrong so i thought i would submit the code and see if anyone would like > # to critique it. Don't create new widgets every time you switch the tab. Instead hide/show the relevant page. You may be able to reuse the idlelib.tabpage.TabPageSet class for that. > # I have one more problem that i can't figure out either. There are a > # bunch of Entry widgets that require number values. > # My problem is if someone inputs a letter or space the program will > # have error that makes part of the Program nonfunctional. You can wrap access to the DoubleVars with try...except, e. g.: try: value = self.COG1.get() except ValueError: # show an error message else: # continue calculation Peter From bockman at virgilio.it Fri Aug 8 06:42:48 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Fri, 8 Aug 2008 03:42:48 -0700 (PDT) Subject: kill thread References: <704879e6-1b21-4c91-99ce-f10e3866c8da@a8g2000prf.googlegroups.com> Message-ID: <28037f13-ac3a-424b-8860-2d65666338f5@t54g2000hsg.googlegroups.com> On 8 Ago, 10:03, "Mathieu Prevot" wrote: > 2008/8/8 Miki : > > > Hello, > > >> I have a threading.Thread class with a "for i in range(1,50)" loop > >> within. When it runs and I do ^C, I have the error [1] as many as > >> loops. I would like to catch this exception (and if possible do some > >> cleanup like in C pthreads) so the program finishes cleanly. Where and > >> how can I do this ? in __run__ ? __init__ ? a try/except stuff ? > > You can have a try/except KeyboardException around the thread code. > > > HTH, > > -- > > Miki > > Of course, but I don't know where. I placed this inside loop, within > called functions from the loop, I still have the problem. > > Mathieu Try this: loop_completed = True for i in range(1,50): try: # your code here except KeyboardException: loop_completed = False break # this breaks the loop # end loop if loop_completed: # code to be executed in case of normal completion else: # code to be executed in case of interruption # code to be executed in both cases From circularfunc at yahoo.se Mon Aug 25 20:50:19 2008 From: circularfunc at yahoo.se (cnb) Date: Mon, 25 Aug 2008 17:50:19 -0700 (PDT) Subject: Return a string result with out breaking loop References: Message-ID: def somefunc(): for action, files in results: full_filename = os.path.join(path_to_watch, files) theact = ACTIONS.get(action, "Unknown") yield str(full_filename) + " " + str(theact) ? Here is an example if that doesn't work, using yield, to show how to use yield: def yi(x): while x > 0: yield str(x) x -= 1 >>> yi(4) >>> a=yi(4) >>> a.next() '4' >>> a.next() '3' >>> a.next() '2' >>> a.next() '1' >>> a.next() Traceback (most recent call last): File "", line 1, in a.next() StopIteration >>> From paul at boddie.org.uk Fri Aug 15 07:30:23 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 15 Aug 2008 04:30:23 -0700 (PDT) Subject: a podcast for music algo-comped with python References: <4600e196-16eb-44da-80ad-42e3589ab31f@f36g2000hsa.googlegroups.com> <7b604f15-945b-4e8a-8ee9-9e0a86746279@r66g2000hsg.googlegroups.com> Message-ID: <2894fe35-1dbf-46aa-aaf6-c59ee7b2331b@l42g2000hsc.googlegroups.com> On 15 Aug, 05:50, castironpi wrote: > On Aug 14, 4:01?pm, Paul Boddie wrote: > > > I'm not sure if I follow the question. I don't have much experience > > with making sound effects, preferring to compose and "pre-render" my > > music, but I imagine there are some tricks that are possible with > > waveform generation and real-time sequencing/playback. > > Oh really, sounds interesting. ?What tricks? Getting it to work, mostly. ;-) I've seen some code reminiscent of the microcomputer era, if I remember correctly, where one is able to specify envelopes and things like that, but I'll have to dig around to see where that was posted. Paul From lists at cheimes.de Fri Aug 22 14:41:27 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 22 Aug 2008 20:41:27 +0200 Subject: Should Python raise a warning for mutable default arguments? In-Reply-To: <3b854a73-21ce-4556-8d0f-5c2ec6fcd6b6@x41g2000hsb.googlegroups.com> References: <00becb2d$0$20312$c3e8da3@news.astraweb.com> <3b854a73-21ce-4556-8d0f-5c2ec6fcd6b6@x41g2000hsb.googlegroups.com> Message-ID: MRAB wrote: > Could there be a new special method __mutable__? Why should we add a new method? Seriously, why should Python be cluttered and slowed down to warn about mutable arguments. It's neither a design flaw nor a surprising feature *ONCE* you have understood how functions work. I agree that the behavior may be surprising for a newbie but it's logical once you got the big picture. Christian From manfredpssnd6 at googlemail.com Sun Aug 24 12:01:34 2008 From: manfredpssnd6 at googlemail.com (manfredpssnd6 at googlemail.com) Date: Sun, 24 Aug 2008 09:01:34 -0700 (PDT) Subject: =?ISO-8859-1?Q?www_single_treff_dresden_in_G=FCnzburg_www_erotik_kon?= =?ISO-8859-1?Q?taktanzeigen_net_erotik_kontaktanzeigen_schwerin_sex_kontakt?= =?ISO-8859-1?Q?anzeigen_berlin_fremdgehen_zu?= Message-ID: <4fbda310-7d6f-47a9-9701-b612b2ea4262@s50g2000hsb.googlegroups.com> www single treff dresden in G?nzburg www erotik kontaktanzeigen net erotik kontaktanzeigen schwerin sex kontaktanzeigen berlin fremdgehen zu + + EROTIK KONTAKTE - EROTISCHE KONTAKTANZEIGEN http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ + + + + + + + + + + + kontaktanzeigen heilbronn in Grevenbroich kontaktanzeigen fotos in Ludwigshafen kontaktanzeigen beep de in Rhoen sex kontaktanzeigen luebeck in Bernkastel die boerse kontaktanzeigen in Bad Kissingen lustige kontaktanzeigen in Homberg / Efze fremdgehen vertrauen in Delitzsch fremdgehen folgen in Barnim http://www.speedreading.com/phpBB2/ftopic147687.html - serioese erotische kontaktanzeigen in Freyung http://www.meinews.net/cialis-t244331.html - erotik kontaktanzeigen berlins in Bad http://www.bloglines.com/forums/read.php?10,71584 - kontaktanzeigen duisburg in Neuruppin http://draconian.com/dragon-forum/showthread.php?t=17661 - single treff mainz in Peine http://www.bloglines.com/forums/read.php?10,98522 - www internet erotik kontaktanzeigen com in Viersen http://www.meinews.net/comprar-t244436.html - kontaktanzeigen berlins in Emmendingen http://draconian.com/dragon-forum/showthread.php?t=20445 - schwule kontaktanzeigen de in Barnim http://forum.tag-board.com/showthread.php?t=23725 - www erotische kontaktanzeigen in Dillingen http://www.bebin.tv/forum/showthread.php?t=31389 - kontaktanzeigen mit bild in Neustadt http://www.meinews.net/yolur-t244563.html - erotik kontaktanzeigen ukraine in Landau http://www.bloglines.com/forums/read.php?10,71539 - nrw kontaktanzeigen in Cloppenburg http://www.gamesforum.ca/showthread.php?t=318761 - singletreff schweiz in Offenbach http://www.dvd.tv/forums/showthread.php?t=8960 - kontaktanzeigen in leipzig in Wittenberg From dudeja.rajat at gmail.com Thu Aug 21 03:04:17 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Thu, 21 Aug 2008 03:04:17 -0400 Subject: WindowsXP/ CTypes - How to convert ctypes array to a string? In-Reply-To: References: Message-ID: On Tue, Aug 19, 2008 at 8:14 AM, Fredrik Lundh wrote: > dudeja.rajat at gmail.com wrote: > >> I also add the letter 'v' same as you suggested. However, I'm looking >> to store this into some variable ( that variable could be be a string, >> tuple or anything, Im not sure which is the suited one) > > the expression gives you a string object; you'll store it in a variable in > the same way as you'd store any other expression result in Python. > > version = "v%d.%d.%d.%d" % tuple(version) > > but when you find yourself getting stuck on things like this, it might a > good idea to take a step back and read the tutorial again: > > http://docs.python.org/tut/tut.html > > pay special attention to the parts that discuss how variables work in > Python. > > if you prefer some other entry level tutorial, the following is said to be > really good: > > http://www.ibiblio.org/g2swap/byteofpython/read/ > > > > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks Fredrik for your support. Regrads, Rajat From pavlovevidence at gmail.com Thu Aug 7 15:43:08 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 7 Aug 2008 12:43:08 -0700 (PDT) Subject: .cpp to .pyd References: Message-ID: On Aug 7, 3:25?am, vedrandeko... at yahoo.com wrote: > Hello, > > I want to build my C++ (.cpp) script to (.pyd) like this: > > http://en.wikibooks.org/wiki/Python_Programming/Extending_with_C%2B%2B > > I have installed "Microsoft Visual studio .NET 2003" and "Boost > Python" and then after I run my setup script: > > python setup.py build > > I get this error: > > running build > running build_ext > building 'hello' extension > D:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\cl.exe /c / > nologo /Ox > ?/MD /W3 /GX /DNDEBUG -IC:\Panda3D-1.5.2\python\include -IC: > \Panda3D-1.5.2\pytho > n\PC /Tphellomodule.cpp /Fobuild\temp.win32-2.5\Release > \hellomodule.obj > hellomodule.cpp > hellomodule.cpp(9) : fatal error C1083: Cannot open include file: > 'boost/python/ > module.hpp': No such file or directory > error: command '"D:\Program Files\Microsoft Visual Studio .NET > 2003\Vc7\bin\cl.e > xe"' failed with exit status 2 > > I think that my MS visual studio ?cannot find "boost python", if > that's the problem then can you tell me how can I solve it. > This is very begginer question,but I can't find answer nowhere, and I > don't have any expirience with Microsoft products. > > Sorry for my bad english! > Regards, > Veki First, locate the boost header files. Suppose you find the file module.hpp in this location: C:\boost-whatever-version\include\boost\python\module.hpp The part that comes before boost\python\module.hpp is the required include directory. You can tell setup to use this directory by adding the following argument to the Extension call: include_dirs = ['C:\\boost-whatever-version\\include'] Notice the doubling of backslashes. Remember to add the directory where the boost header files lie on your system; don't add this line exactly. You should end up with a setup call that looks like this: setup(name="blah", ext_modules=[ Extension("hello", ["hellomodule.cpp"], libraries = ["boost_python"], include_dirs = ['C:\\boost-whatever-version\\include']) ]) Carl Banks From timr at probo.com Tue Aug 5 00:18:30 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 05 Aug 2008 04:18:30 GMT Subject: SMTP via GMAIL References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> Message-ID: mmm wrote: > >After reading about and using the smtplib module, I thought code such >as below would ignore the 'Cc: ' body line below when sending messages >and instead simply use the RECEIVERS list Correct. It is required by the SMTP spec to behave that way. >But when using smtp.gmail.com as the server I learned that any >@gmail.com address in the Cc: text block would >receive mail even if I changed the code to have the RECEIVERS list to >ignore the CC addresses or not include the gmail address in the CC >list as below Interesting. If true, that is incorrect behavior. >And does anyone have a general routine that lets one also have Bcc: >addresses usign SMTP? To make a Bcc, all you do is include the address in the RECEIVERS list, but don't mention it in the body at all. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From rajanikanth at gmail.com Sat Aug 23 17:54:09 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Sat, 23 Aug 2008 14:54:09 -0700 Subject: dropwhile question Message-ID: <84bdef3c0808231454v3e6f347eucae1f7abeabe193d@mail.gmail.com> >>> list(itertools.dropwhile(lambda x: x<5,range(10))) [5, 6, 7, 8, 9] Why doesn't this work? >>> list(itertools.dropwhile(lambda x: 2 References: <76fd5acf0808101249p1202684epcd7ca3139322f308@mail.gmail.com> Message-ID: Calvin Spealman wrote: > dont quote me but i do think this check is being removed. No, the check hasn't been removed - technically speaking. In Python 3.0 the behavior of the method descriptor has been changed. aclass.somemethod doesn't give you an instancemethod wrapper any more. It's a plain function object like aclass.somemethod.im_func in the 2.x series. Only instances return a bound instancemethod wrapper in Python 3.0. Christian From xtd8865 at gmail.com Tue Aug 26 17:11:30 2008 From: xtd8865 at gmail.com (fred8865) Date: Tue, 26 Aug 2008 22:11:30 +0100 Subject: floating point arithmetic Message-ID: <6k_sk.92243$6s4.59352@newsfe14.ams2> Hi all, I understand that due to different arithmetic used in floating points they are just approximations. Hence, 180/100=1 in my python interpreter. How can I tackle this problem of inaccurate floating point numbers? thank you regards xtd From healey.rich at gmail.com Sat Aug 9 01:17:52 2008 From: healey.rich at gmail.com (Rich Healey) Date: Sat, 09 Aug 2008 15:17:52 +1000 Subject: sending to an xterm In-Reply-To: References: <20080808205821.GJ23567@dragontoe.org> Message-ID: <489D2880.9090208@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Kent Tenney wrote: > Derek Martin pizzashack.org> writes: > >> On Fri, Aug 08, 2008 at 08:25:19PM +0000, Kent Tenney wrote: >>> Howdy, >>> >>> I want to open an xterm, send it a command and have it execute it. >> You can't do that. xterm doesn't execute shell commands passed on >> stdin... It can, however, execute one passed on the command line. >> >> Instead of just running xterm, you can run "xterm -e 'cmd foo bar'" >> where cmd is the program to run and foo and bar are its arguments. >> The problem is that as soon as the program exits, xterm will exit >> also. >> > > OK, I see that. > > (getting off topic) > > any chance of keeping the xterm open after running the command? > > Thanks, > Kent > xterm -hold -e "whatever" > > > -- > http://mail.python.org/mailman/listinfo/python-list - -- Rich Healey - healey.rich at gmail.com Developer / Systems Admin - OpenPGP: 0x8C8147807 MSN: bitchohealey at hotmail.com AIM: richohealey33 irc.psych0tik.net -> #hbh #admins richohealey irc.freenode.org -> #hbh #debian PythonNinja -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkidKIAACgkQLeTfO4yBSAclUwCg3uuvxxWHgZ/vqenrmaNIV/iE ceQAn3e8oC6t0rTLtVhpeisujnqq8jlh =4s8n -----END PGP SIGNATURE----- From pmaupin at gmail.com Fri Aug 29 14:18:38 2008 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 29 Aug 2008 11:18:38 -0700 (PDT) Subject: subclassing complex References: <3ce33299-e13c-4ce0-8a09-eab6d0359033@a3g2000prm.googlegroups.com> Message-ID: <0b908015-59c2-4dc9-a279-e42ce920fe03@d45g2000hsc.googlegroups.com> On Aug 29, 4:24 am, Peter Otten <__pete... at web.de> wrote: > A minimal example is > > >>> class Complex(complex): > > ... def __radd__(self, other): print "radd" > ...>>> 1j + Complex() > > 1j > > versus > > >>> class Int(int): > > ... def __radd__(self, other): print "radd" > ...>>> 1 + Int() > > radd > > I think the complex subclass should behave like the int subclass. > To get an authoritative answer you should file a bug report. Hmm, good point. I shouldn't look at newsgroups when I'm too tired to see the whole problem. According to the documentation at http://docs.python.org/ref/numeric-types.html: "Note: If the right operand's type is a subclass of the left operand's type and that subclass provides the reflected method for the operation, this method will be called before the left operand's non- reflected method. This behavior allows subclasses to override their ancestors' operations." I think this makes it pretty clear that the OP found a bug in how complex works. (Before I read this note, I would have assumed that the int() handling was broken, but it looks like a supportable design decision. Probably whoever implemented it wasn't even thinking about complex numbers, but for consistency, I would think they should be made to work the same.) Regards, Pat From maric at aristote.info Wed Aug 13 20:00:36 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 14 Aug 2008 02:00:36 +0200 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: <1d473f6a-ba34-46b8-a8e4-c7c55b85630d@j33g2000pri.googlegroups.com> References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> <1d473f6a-ba34-46b8-a8e4-c7c55b85630d@j33g2000pri.googlegroups.com> Message-ID: <200808140200.36702.maric@aristote.info> Le Wednesday 13 August 2008 21:04:30 Rhamphoryncus, vous avez ?crit?: > class X(object): > ? ? foo = 42 > > ? ? def bar(self): > ? ? ? ? print foo > ? ? ? ? print self.foo > X.foo = 7 Yes this is a problem, function could not bind their free vars to the class namespace without introducing a subtle incompatibility with actual code. This is exactly this case which would be a problem (your example raise an error and is not exactly a "running code"): G = 1 class A(object) : G = 0 def f(self) : return G -- _____________ Maric Michaud From larry.bates at vitalEsafe.com Sat Aug 30 08:48:58 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Sat, 30 Aug 2008 07:48:58 -0500 Subject: Ensure only single application instance. In-Reply-To: References: Message-ID: Cameron Laird wrote: > In article , > Uberman wrote: >> On Fri, Aug 29, 2008 at 6:51 AM, Heston James wrote: >>> Good afternoon all. >>> >>> I have an application/script which is launched by crontab on a regular >>> basis. I need an effective and accurate way to ensure that only one instance >>> of the script is running at any one time. >> You could create a named pipe in /tmp with a unique (static) name and >> permissions that disallow any kind of read/write access. Then simply have >> your script check for its existence when it starts. If it exists, then >> another instance of your script is running, and just terminate. Make sure >> your original instance removes the pipe when it exits. > > I'll write an article on this subject this fall. The > essentials are: > A. There's no canonical answer; every apparent solution > has problems; > B. The suggestions offered you are certainly among the > popular ones; > C. My personal favorite is to open a (network) socket > server. For reasons I'll eventually explain, this > has particularly apt semantics under Unix. Cameron, I found this recipe (http://code.activestate.com/recipes/474070/) on ActiveState's site that had a working version of a single instance class for Windows that I've used quite successfully. Since I also work a lot Linux, I wrote and donated this version (http://code.activestate.com/recipes/546512/) for Linux that also seems to work well for me. -Larry From frankrentef at yahoo.com Tue Aug 26 12:46:00 2008 From: frankrentef at yahoo.com (frankrentef) Date: Tue, 26 Aug 2008 09:46:00 -0700 (PDT) Subject: Newbie needs help Message-ID: <077ddd87-e944-44e0-935f-2d5cf1368e14@w39g2000prb.googlegroups.com> Greetings all, I'm wanting to maintain what values in one file and call them in another. The purpose being to keep a single location where url's, login's and passwords can be maintained, then called as needed from another file. In file #1 I have... import time import os import sys url = 'http://zoo/' adminlogin = 'Zebra' adminpassword = 'Zebra12$' --------------------------------------------- In file #2 I have the following... from cPAMIE import PAMIE #Imports - used to setup / control finding files import time import os import sys import loginout #name of the file retaining all url/login info from log import log #Create New Pamie Object ie=PAMIE() ie=Visible =1 t=time adminlogin (ie,url) if ie.findText ('Site Status: Active'): log ('PASSED -- ADMIN Module - ADMIN Login & Admin Tab Navigation Successful') else: log ('WARNING -- ADMIN Module Login & Admin Tab Navigation FAILED') time.sleep(2) What am I doing incorrectly to not have file two log in when executed. All files are in the same directory. Keep it simple... I'm new at this. THNX From your.master at gmail.com Mon Aug 11 03:27:46 2008 From: your.master at gmail.com (Brandon) Date: Mon, 11 Aug 2008 00:27:46 -0700 (PDT) Subject: updating dictionaries from/to dictionaries Message-ID: Hi all, I am not altogether experienced in Python, but I haven't been able to find a good example of the syntax that I'm looking for in any tutorial that I've seen. Hope somebody can point me in the right direction. This should be pretty simple: I have two dictionaries, foo and bar. I am certain that all keys in bar belong to foo as well, but I also know that not all keys in foo exist in bar. All the keys in both foo and bar are tuples (in the bigram form ('word1', 'word2)). I have to prime foo so that each key has a value of 1. The values for the keys in bar are variable integers. All I want to do is run a loop through foo, match any of its keys that also exist in bar, and add those key's values in bar to the preexisting value of 1 for the corresponding key in foo. So in the end the key,value pairs in foo won't necessarily be, for example, 'tuple1: 1', but also 'tuple2: 31' if tuple2 had a value of 30 in bar. I *think* the get method might work, but I'm not sure that it can work on two dictionaries the way that I'm getting at. I thought that converting the dictionaries to lists might work, but I can't see a way yet to match the tuple key as x[0][0] in one list for all y in the other list. There's just got to be a better way! Thanks for any help, Brandon (trying hard to be Pythonic but isn't there yet) From a.harrowell at gmail.com Wed Aug 27 09:37:56 2008 From: a.harrowell at gmail.com (TYR) Date: Wed, 27 Aug 2008 06:37:56 -0700 (PDT) Subject: JSON from Python mysqldb References: <998cfbb4-3a72-4e51-9274-518caadd9ed7@m44g2000hsc.googlegroups.com> Message-ID: <09fd0a05-ea98-4765-ad0d-00ad89a9bc21@79g2000hsk.googlegroups.com> There's always the naive option. query = ('species', 'lifestyle', 'coolness', 'tentacles=>8') db.execute('SELECT %s, %s, %s % FROM creatures WHERE %s;' % query) record = dict(zip((query), (db.fetchall())) array = '''{ ''' for k,v in record: array.append('"(k)":"(v)"') array.append(''' }''') From timothy.grant at gmail.com Sun Aug 3 13:51:22 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Sun, 3 Aug 2008 10:51:22 -0700 Subject: Teething troubles with Python on a Mac In-Reply-To: References: <6651edd6-d47f-4e10-bf0b-0875190b9bc2@a1g2000hsb.googlegroups.com> <489546F1.9050102@cosc.canterbury.ac.nz> <3dcf39de-3c3c-4e47-abb4-508d1601a9e2@z11g2000prl.googlegroups.com> Message-ID: On Sun, Aug 3, 2008 at 10:44 AM, Avinash Vora wrote: >> You will likely cause more problems updating the system python than >> managing the two separate installations. > > That's sadly worrying. > >> OSX relies on the version of python they ship. > > I think that helps my point--there *are* bug fixes between major versions > despite the new language changes, and that can really only be a good thing. > >> While there are likely cases where it could be >> replaced completely safely the risks of having to re-install your OS >> at some point because it has the wrong version of python are not worth >> it. > > > I haven't been a Mac user long enough to see a major version change (I was > on Linux/XP/Vista for most of 2.4 and switched distributions right after 2.5 > came out, and then XP before that), so I've never seen a version change, but > is this the sort of thing that will be upgraded in Software Update? > > - Avinash I haven't paid enough attention to the system python in my four years as an Apple user to know. I simply installed the python I wanted and went from there. I honestly don't think it is a cause for concern though. The situation is very similar to on Linux (Red Hat has their version of python) you simply install what you want and use it. -- Stand Fast, tjg. [Timothy Grant] From PaulAlexWilson at gmail.com Mon Aug 4 11:08:26 2008 From: PaulAlexWilson at gmail.com (Wilson) Date: Mon, 4 Aug 2008 08:08:26 -0700 (PDT) Subject: Limits of Metaprogramming References: <0c56829a-7ad2-4ff2-b225-7981538e7c7a@j22g2000hsf.googlegroups.com> Message-ID: <64c69a68-aa00-4f59-a84e-52f5cfa14913@z66g2000hsc.googlegroups.com> On 4 Aug, 14:47, Tomasz Rola wrote: > On Mon, 4 Aug 2008, Wilson wrote: > > Hi all, > > Howdy, > > I am not sure if my remarks will be of any use for you, but here it goes. > > > I have an interesting problem that I'm hoping can be solved with > > metaprogramming, but I don't know how far Python supports code > > generation (and I don't know if I'm taking the correct approach > > either... hence why I'm asking on this group): > > > I'd like to write a program that writes/manipulates a statemachine. My > > idea was that I would define states in a .py file along with their > > transitions and other metadata. I could then write a suite of programs > > that would manipulate these states in interesting ways, such as > > generate diagrams and documentation, test suites, do verifications and > > also edit them. These programs would import the .py file and use > > introspection upon the module's classes (states would be modelled as > > classes). For example, a documentation tool could use graphviz to draw > > the statediagram with the transition table and docstring... > > Maybe you have actually two problems. > > One problem is processing source code into something useful, but > not executable. So it does not necessarily need metaprogramming to be > solved, just some "code comprehension" (like get a python grammar, > lex/yacc and read a lot of docs how to use them). I do want my resultant code to be executable; I want to be able to use "import" to get programmatical access to the classes and structures it contains, such that they can be manipulated, added to, exercised and drawn (using graphviz) via introspection... After any manipulation, i'd like to be able to flatten them back into a .py file (as source such that they are readable as Python code). > > My problem is that I don't know if it's possible to edit these states > > and then write them back to .py. Firstly, if my editing tool was to > > create a new state, I would want to create the class (using type) and > > attach it to the imported state module somehow. I can't find > > information on whether this is possible. Secondly, I'd like to > > manipulate the class and then use the inspect module to get the source > > and write it back to file. Now I'm pretty sure the inspect module will > > only write the source code as found in the original .py file. Is there > > a way to generate the code for a class or other python objects in a > > generic way? Or will I have to bite the bullet and write to custom > > file and generate code from that (like glade with XML)? Or is there > > another solution with templates that I'm over looking? > > Well, "everything" is doable in a Turing-complete language :-). However, > this one problem - code generation and using it on the fly - may be better > solved with some other language, perhaps? > > Not that I want to dissuade you (or anyone else) from using Python, but > last time I checked the state of things (was a good couple of years ago, I > wanted to solve some math-related problem with metaprogramming in Python) > I decided I would do better if I learned Scheme. At least in Scheme, > program structure is so simple, it is just a list (or a sequence of them), > so manipulating code is IMHO much easier. > > I mean, even if in theory every language in Turing-complete class is equal > to each other (one can do the same kind of stuff in one as in the other), > in practice they are not equal at all. So doing everything in one ultimate > language of choice is not very wise from my point of view. > > It does not mean you should immediately go to > > http://en.wikipedia.org/wiki/Scheme_(programming_language) > > but you may do so, and then make an informed choice by yourself. To be > better informed, you may also google for more material - introductions, > opinions, comparisons and some first-hand experience. > > On the other hand, writing "metafiles" and interpreters for them - ugh... > :-). I have read somewhere, that some programmers resist using Scheme > (or some other Lisp) for solving their problem and end up with writing > their own Lisp-like (language|file format) and interpreter(s) for it. So > you better watch yourself. If this effort is going to be something more > permament than "done and go", then you will probably find yourself in the > situation of reinventing the wheel, as your project goes more and more > complex. If this is going to happen, you might use existing wheels and > save some time for thinking on something better. I appreciate these comments, and I know the quote that you are refering to although I can't find it now... Something like: " Every sufficiently large application has a poor/incomplete implementation of LISP embedded within it ". I've looked at LISP before and do appreciate its elegance, but Python has a beauty of its own in its pragmatism, standard libraries and community. So I'll choose to stick with it. > > Having the classes in memory, editing their attributes, adding methods > > and then serialising them to code has an elegance to it in my mind and > > would hopefully simplify things. The result would be directly > > executable by the interpreter itself and editable by python > > developers. But I fear that I may need an intermediary notation/format > > for storage. Any advice/hints would be very useful. > > Yes, there is something elegant in this way of thinking, at least for me. > > As I (indirectly) said above, I am not up to date with recent Python > abilities (I still use Python for a lot of things, I just do not overuse > it for things, that it seems to be not so good at). I hope someone knows > better and steps in to prove me wrong - it is always good to learn > something new. Also, if you have just one problem, then learning a new > language because of it is a bit too much (or maybe not, if you enjoy it > :-) ). But if you plan doing similar or more difficult things in the > future, then knowing Scheme may be good for you. Even if you choose to not > use it, you will be aware of what can be done with it so this knowledge > can provide some ready to use templates. I've been through quite a few of the SICP lectures and again, do appreciate its elegance and they have changed the way I program. > And yes, there are also some other languages in Lisp family, but I think > Scheme is best choice if you don't know any of them already. It is quite > small, it is well defined (I mean, it has some real specification, > instead of being "specified by its implementation") and there is a lot of > info about it on the net that could be easily understood. And, last but > not least, it has metaprogramming included with nice bunch of additional > stuff. For a start, PLT's DrScheme looks nice (IMHO - yes, there are > other nice looking Scheme implementations but this one is probably best > fitted for a beginner): > http://www.plt-scheme.org/ > > Regards, > Tomasz Rola Thanks for your comments. But I believe my solution may lie in using a template language such as cheetah. Too much is already invested in Python! Best Regards, Paul From giles.thomas at gmail.com Tue Aug 19 08:40:02 2008 From: giles.thomas at gmail.com (giles.thomas at gmail.com) Date: Tue, 19 Aug 2008 05:40:02 -0700 (PDT) Subject: ANN: Resolver One 1.2 released Message-ID: <59f2f4c8-5713-4779-8bcf-e1683645bd64@a70g2000hsh.googlegroups.com> We are proud to announce the release of Resolver One, version 1.2 - the largest IronPython application in the world, we think, at 38,000 lines of production code backed up by 150,000 lines of unit and functional tests. Resolver One is a Rapid Application Development tool for analysing and presenting business data, using a familiar spreadsheet interface combined with a powerful IronPython-based scripting capability that allows you to insert your own code directly into the recalculation loop. For version 1.2, we have on big headline feature; a new function called RunWorkbook that allows you to "call" one spreadsheet from another, passing in parameters and pulling out results - just like functions, but without having to code the function by hand. This allows you to mix spreadsheet-based and code-based logic, using the best paradigm for the job in hand. We've also added a whole bunch of usability enhancements - the full (long!) changelist is up on our website, or you can see a screencast: It's free for non-commercial use, so if you would like to take a look, you can download it from our website: (registration no longer required). Best regards, Giles -- Giles Thomas MD & CTO, Resolver Systems Ltd. giles.tho... at resolversystems.com +44 (0) 20 7253 6372 Try out Resolver One! 17a Clerkenwell Road, London EC1M 5RD, UK VAT No.: GB 893 5643 79 Registered in England and Wales as company number 5467329. Registered address: 843 Finchley Road, London NW11 8NA, UK From ggpolo at gmail.com Thu Aug 28 10:54:44 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 28 Aug 2008 11:54:44 -0300 Subject: Tkinter tkMessageBox problem - message box is displayed with an additional window In-Reply-To: References: Message-ID: On Thu, Aug 28, 2008 at 10:29 AM, wrote: > Hi, > I'm working on Windows Platform > > I'm facing some problem with the tkMessageBox. My code is as below: > > import tkMessageBox > import Tix > from Tkinter import * > > if len(installedLibPath) != len(listOfLibraries): > if tkMessageBox.askyesno("Question", \ > type='yesno', icon='warning', \ > message="Some of the libraries are > not installed. Do you wish to continue with the remaining?"): > myRoot = Tix.Tk() > myAppGUIObject = myAppGUI(myRoot) #Class for my GUI > myRoot.mainloop() > else: > sys.exit(0) > It is good to post a short code sample that demonstrates the problem, but it has to run by itself at least. > > The Message Box is called before the Tix.Tk mainloop(). The problems > are as under : > > 1. Since the message box is displayed before the mainloop() is > started, the message box is displayed with another window that is > blank. This should not be displayed. > > 2. As a results of this messagebox (called before the mainloop) the > original Gui started by mainloop doesnot work as desired. Some of the > checkbuttons are displayed as unset (i.e un-ticked). These > checkbuttons used to be set at initialization before I stared using > this messagebox. tkMessageBox blocks till you finish it, maybe that is what is causing your problem but it is hard to tell what you are doing wrong in that myAppGui without seeing it (preferably reduced code demonstrating the problem). Now.. an attempt to solve your problem. Tk always has a root window going on, so that "another window" is inevitable, but you can hide and show it again when needed. You could do something like this: import tkMessageBox import Tkinter class App(object): def __init__(self, master): self.master = master print "tkMessageBox is gone now" root = Tkinter.Tk() root.withdraw() tkMessageBox.askyesno("Question", message="Do you use Python?", type='yesno', icon='warning', master=root) root.deiconify() app = App(root) root.mainloop() > > > Please help. > > Thanks and regards, > Rajat > -- > Regrads, > Rajat > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From bdesth.quelquechose at free.quelquepart.fr Tue Aug 12 11:52:59 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 12 Aug 2008 17:52:59 +0200 Subject: __getattr__, __setattr__ and pickle In-Reply-To: References: Message-ID: <48a1cdce$0$14748$426a74cc@news.free.fr> mwojc a ?crit : > Hi! > My class with implemented __getattr__ and __setattr__ methods cannot be > pickled because of the Error: > > ====================================================================== > ERROR: testPickle (__main__.TestDeffnet2WithBiases) > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "deffnet.py", line 246, in testPickle > cPickle.dump(self.denet, file) > TypeError: 'NoneType' object is not callable > > ---------------------------------------------------------------------- > > Is there an obvious reason i don't know, which prevents pickling with those > methods (if i comment them out the pickling test passes)? > > I'm using Python 2.4.4 on Gentoo Linux. The mentioned methods goes as > follows: > > def __setattr__(self, name, value): > if name == 'weights': > j = 0 > for net in self.nets: > w1 = self.wmarks[j] > w2 = self.wmarks[j+1] > net.weights = value[w1:w2] > j += 1 > else: > self.__dict__[name] = value > > def __getattr__(self, name): > if name == 'weights': > j = 0 > for net in self.nets: > w1 = self.wmarks[j] > w2 = self.wmarks[j+1] > self._weights[w1:w2] = net.weights > j += 1 > return self._weights __getattr__ should raise an AttributeError when name != 'weight' instead of (implicitely) returning None. pickle looks for a couple special method in your object[1], and it looks like it doesn't bother to check if what it found was really callable. [1] cf http://docs.python.org/lib/pickle-inst.html FWIW, you'd be better using a property instead of __getattr__ / __setattr__ if possible. And while we're at it, you dont need to manually take care of your index in the for loop - you can use enumerate(iterable) instead: for j, net in enumerate(self.nets): w1 = self.wmarks[j] w2 = self.wmarks[j+1] self._weights[w1:w2] = net.weights return self._weights HTH > Greetings, From deets at nospam.web.de Mon Aug 18 04:37:11 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 18 Aug 2008 10:37:11 +0200 Subject: if in expression In-Reply-To: <87k5eeafw3.fsf@mulj.homelinux.net> References: <6gsnsqFhdofgU1@mid.uni-berlin.de> <87k5eeafw3.fsf@mulj.homelinux.net> Message-ID: <6gsqlnFhgre0U1@mid.uni-berlin.de> Hrvoje Niksic schrieb: > "Diez B. Roggisch" writes: > >> Since python 2.5, it is >> >> if else >> >> If you want lazy evaluation, you can use lambdas: >> >> iif(cond, lambda: then, lambda: else_)() > > Your code uses "iif" and attempts to evaluate a tuple; could you post > an example that works? > I ask because it's not clear what you mean by lazy evaluation in this > context. The ternary "if" expression introduced in Python 2.5 only > evaluates then_value or else_value depending on the outcome of cond. > How is that different than using a lambda? If iif is defined as this: def iif(cond, then, else_): if cond: return then else: return else_ you have the problem that "then" and "else_" get evaluated *before* they get passed. So for example this factorial function will fail with too deep recursion error: def f(n): return iif(n> 1, n * f(n-1), 1) But if you do it like this, the then and else_ will be functions that get returned and then they need to be called to be acutally evaluated: def f(n): return iif(n> 1, lambda: n * f(n-1), lambda: 1)() Diez From avinashvora at gmail.com Mon Aug 4 04:51:33 2008 From: avinashvora at gmail.com (Avinash Vora) Date: Mon, 4 Aug 2008 14:21:33 +0530 Subject: Peer-to-Peer Chat Program In-Reply-To: <98ad656a0808032214w23b51020j29d97fac1249d14a@mail.gmail.com> References: <98ad656a0808032214w23b51020j29d97fac1249d14a@mail.gmail.com> Message-ID: <007EC863-1A30-499B-A85B-AC1254800C7D@gmail.com> On Aug 4, 2008, at 10:44 AM, Trevor Slocum wrote: > Python seemed like the right choice for writing a peer-to-peer > application, as the support for sockets is adequate and the cross- > platform ability is nominal. That's why I searched around for P2P > frameworks in Python, and didn't have much luck. I've had this problem too. > Like I said, I didn't know anything about P2P before this, and I'm > sure much of what I've done so far can be improved upon. That's why > I'm posting here. I'd like to make an open request to anyone who > would like to assist me in the application development to reduce the > resource usage and improve the overall network efficiency. Even > simple "Ah, I saw you were doing this in your code, I recommend you > do this..." would be of great help. Well, I have about the same level of experience that you do, but I'll take a look at the code and see if I can offer assistance. > If you are interested, you may view the Google Code page at http://code.google.com/p/kaishi/ > or checkout the SVN repository directly using http://kaishi.googlecode.com/svn/trunk/ I haven't read the code itself yet, but I'm extremely interested in the project. I'm a fairly experienced Pythonista, yet I've never really worked on networked projects in any programming language before. Not only does it interest me, but it's a good way to expand my knowledge base. > I have proper hosting and can set up a specific website for > collaboration on project ideas and such if support is carried after > this message. I thank anyone who has taken their time to read this. I would be interested in collaborating in a project like this, I think. Feel free to email me privately to talk further if you wish. -- Avi From george.sakkis at gmail.com Fri Aug 22 14:06:03 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 22 Aug 2008 11:06:03 -0700 (PDT) Subject: property() usage - is this as good as it gets? References: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> Message-ID: On Aug 22, 12:18 pm, David Moss wrote: > Hi, > > I want to manage and control access to several important attributes in > a class and override the behaviour of some of them in various > subclasses. > > Below is a stripped version of how I've implemented this in my current > bit of work. > > It works well enough, but I can't help feeling there a cleaner more > readable way of doing this (with less duplication, etc). > > Is this as good as it gets or can this be refined and improved > especially if I was to add in a couple more attributes some fairly > complex over-ride logic? A small improvement as far as overriding goes is the OProperty recipe: http://infinitesque.net/articles/2005/enhancing%20Python's%20property.xhtml George From steve at REMOVE-THIS-cybersource.com.au Thu Aug 14 18:35:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2008 22:35:53 GMT Subject: for y in range (0,iNumItems)--> not in order? References: <8514d915-95bf-4e57-a16a-68866e0ad789@l42g2000hsc.googlegroups.com> <48a45818$0$1135$426a34cc@news.free.fr> Message-ID: <00b4ae4d$0$14351$c3e8da3@news.astraweb.com> On Thu, 14 Aug 2008 10:54:25 -0700, korean_dave wrote: > Well, here is the whole problem. > > It works perfectly. I can see why that might be a problem. To solve it, open the source code in a text editor and make random changes to the code. -- Steven From vlastimil.brom at gmail.com Sun Aug 17 16:05:52 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sun, 17 Aug 2008 22:05:52 +0200 Subject: like a "for loop" for a string In-Reply-To: <19022694.post@talk.nabble.com> References: <19022098.post@talk.nabble.com> <19022155.post@talk.nabble.com> <19022694.post@talk.nabble.com> Message-ID: <9fdb569a0808171305x6345ec17ife5afd87c2a0c3b7@mail.gmail.com> 2008/8/17 Alexnb > > Basically I want the code to be able to pick out how many strings there are > and then do something with each, or the number. When I say string I mean > how > many "strings" are in the string "string string string non-string string" > > Does that help? > > Not quite sure, if i underestand the task you want to achieve correctly, but do you maybe mean something like the following? (here under "string" the exact wording "string" is meant; obviously any section of the input string will be a string too) >>> fun_string = "string string string non-string non-string string" >>> fun_words = fun_string.split() >>> fun_words ['string', 'string', 'string', 'non-string', 'non-string', 'string'] >>> strings_from_fun_words = [word for word in fun_words if word == "string"] >>> strings_from_fun_words ['string', 'string', 'string', 'string'] >>> len(fun_words) 6 >>> len(strings_from_fun_words) 4 >>> HTH Vlasta -------------- next part -------------- An HTML attachment was scrubbed... URL: From rex.eastbourne at gmail.com Fri Aug 15 20:21:56 2008 From: rex.eastbourne at gmail.com (Rex) Date: Fri, 15 Aug 2008 17:21:56 -0700 (PDT) Subject: Confused: looking for a simple XML parser Message-ID: <04f57893-3f08-41a6-b2a7-defb069c4978@x16g2000prn.googlegroups.com> Hello, I am a Python programmer facing my first small XML project. I am looking to find a simple tool to take an XSD file and convert the XSD tree structure to another text format (e.g. an adjacency matrix for the tree's graph), or convert one xml file format definition into another, non-xml one. I don't need to validate XML documents created by this schema or do anything else fancy. I just need to be able to traverse this tree programmatically and find which child attributes belong to which parent attributes, etc. There seem to be so many Python libraries and programs out there that I don't know what to use. What tool should I use? Thanks, Rex From aassime1 at hotmail.fr Thu Aug 21 08:18:41 2008 From: aassime1 at hotmail.fr (aassime abdellatif) Date: Thu, 21 Aug 2008 05:18:41 -0700 (PDT) Subject: ISLAM and the AIM of LIFE Message-ID: ISLAM and the AIM of LIFE What is your purpose in life? What is the rationale behind our life? Why do we live in this life? These questions frequently intrigue people who try to find accurate answers. People provide different answers to these questions. Some people believe the purpose of life is to accumulate wealth. But one may wonder: What is the purpose of life after one has collected colossal amounts of money? What then? What will the purpose be once money is gathered? If the purpose of life is to gain money, there will be no purpose after becoming wealthy. And in fact, here lies the problem of some disbelievers or misbelievers at some stage of their life, when collecting money is the target of their life. When they have collected the money they dreamt of, their life loses its purpose. They suffer from the panic of nothingness and they live in tension and restlessness. Can Wealth Be an Aim? We often hear of a millionaire committing suicide, sometimes, not the millionaire himself but his wife, son, or daughter. The question that poses itself is: Can wealth bring happiness to one?s life? In most cases the answer is NO. Is the purpose of collecting wealth a standing purpose? As we know, the five-year old child does not look for wealth: a toy for him is equal to a million dollars. The eighteen-year old adolescent does not dream of wealth because he is busy with more important things. The ninety-year old man does not care about money; he is worried more about his health. This proves that wealth cannot be a standing purpose in all the stages of the individual's life. Wealth can do little to bring happiness to a disbeliever, because he/ she is not sure about his fate. A disbeliever does not know the purpose of life. And if he has a purpose, this purpose is doomed to be temporary or self destructive. What is the use of wealth to a disbeliever if he feels scared of the end and skeptical of everything. A disbeliever may gain a lot of money, but will surely lose himself. Worshipping Allah as an Aim On the contrary, faith in Allah gives the believer the purpose of life that he needs. In Islam, the purpose of life is to worship Allah. The term "Worship" covers all acts of obedience to Allah. The Islamic purpose of life is a standing purpose. The true Muslim sticks to this purpose throughout all the stages of his life, whether he is a child, adolescent, adult, or an old man. Worshipping Allah makes life purposeful and meaningful, especially within the framework of Islam. According to Islam this worldly life is just a short stage of our life. Then there is the other life. The boundary between the first and second life is the death stage, which is a transitory stage to the second life. The type of life in the second stage a person deserves depends on his deeds in the first life. At the end of the death stage comes the day of judgment. On this day, Allah rewards or punishes people according to their deeds in the first life. The First Life as an Examination So, Islam looks at the first life as an examination of man. The death stage is similar to a rest period after the test, i. e. after the first life. The Day of Judgment is similar to the day of announcing the results of the examinees. The second life is the time when each examinee enjoys or suffers from the outcome of his behavior during the test period. In Islam, the line of life is clear, simple, and logical: the first life, death, the Day of Judgment, and then the second life. With this clear line of life, the Muslim has a clear purpose in life. The Muslim knows he is created by Allah. Muslims know they are going to spend some years in this first life, during which they have to obey God, because God will question them and hold them responsible for their public or private deeds, because Allah knows about all the deeds of all people. The Muslim knows that his deeds in the first life will determine the type of second life they will live in. The Muslim knows that this first life is a very short one, one hundred years, more or less, whereas the second life is an eternal one. The Eternity of the Second Life The concept of the eternity of the second life has a tremendous effect on a Muslims during their first life, because Muslims believe that their first life determines the shape of their second life. In addition, this determines the shape of their second life and this determination will be through the Judgment of Allah, the All just and Almighty. With this belief in the second life and the Day of Judgment, the Muslim's life becomes purposeful and meaningful. Moreover, the Muslim's standing purpose is to go to Paradise in the second life. In other words, the Muslim's permanent purpose is to obey Allah, to submit to Allah, to carry out His orders, and to keep in continues contact with Him through prayers (five times a day), through fasting (one month a year), through charity (as often as possible), and through pilgrimage (once in one's life). The Need for a Permanent Purpose Disbelievers have purposes in their lives such as collecting money and property, indulging in sex, eating, and dancing. But all these purposes are transient and passing ones. All these purposes come and go, go up and down. Money comes and goes. Health comes and goes. Sexual activities cannot continue forever. All these lusts for money, food and sex cannot answer the individual's questions: so what? Then What? However, Islam saves Muslims from the trouble of asking the question, because Islam makes it clear, from the very beginning, that the permanent purpose of the Muslim in this life is to obey Allah in order to go to Paradise in the second life. We should know that the only way for our salvation in this life and in the hereafter is to know our Lord who created us, believe in Him, and worship Him alone. We should also know our Prophet whom Allah had sent to all mankind, believe in Him and follow Him. We should, know the religion of truth which our Lord has commanded us to believe in, and practice it ? Those in search of truth Who have an open mind and heart, Islamic Education Foundation Welcome You. Objectives: - To Convey the message of Islam To Educate Muslims about Islam To keep in close contact with new Muslims. Activities: Offering Courses and presenting lectures about Islam in several languages. Teaching Islam and Arabic. Teaching new Muslims to receive the Holy Quran. Helping Non- Muslims embrace Islam and complete the required procedures From rtw at freenet.co.uk Sat Aug 2 17:14:11 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 02 Aug 2008 16:14:11 -0500 Subject: Profiling weirdness: Timer.timeit(), fibonacci and memoization References: <59994541-2fb7-450c-ac14-9922d87b6aa1@m45g2000hsb.googlegroups.com> <2m3lk.118118$9I1.20910@newsfe16.ams2> Message-ID: Stefaan Himpe wrote in news:2m3lk.118118$9I1.20910 at newsfe16.ams2 in comp.lang.python: > Nothing weird about this ... > The difference will become larger as your input value becomes larger. > > You can easily understand why if you try to calculate fib(10) by hand, > i.e. work through the algorithm with pencil and paper, > then compare the work you have to do to the memoized version which just > takes fib(9) and fib(8) from memory and adds them together. > I think you missed the point. The problem is that the un-decorated, loop only version takes 35 seconds when called by timeit.Timer. However if you apply the decorator it takes less that a second. In *both* cases the function (fib) only gets called once. Note, I timed the call fib(100) with time.clock() and got a value of less than 1 ms, the memozed version takes about 10 times longer. So the question is: whats going on with timeit.Timer ? Rob. -- http://www.victim-prime.dsl.pipex.com/ From mattheww at chiark.greenend.org.uk Tue Aug 5 13:53:08 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 05 Aug 2008 18:53:08 +0100 (BST) Subject: URLs and ampersands References: <00a78f7e$0$20302$c3e8da3@news.astraweb.com> Message-ID: Gabriel Genellina wrote: > Steven D'Aprano wrote: >> I have searched for, but been unable to find, standard library >> functions that escapes or unescapes URLs. Are there any such >> functions? > Yes: cgi.escape/unescape, and xml.sax.saxutils.escape/unescape. I don't see a cgi.unescape in the standard library. I don't think xml.sax.saxutils.unescape will be suitable for Steven's purpose, because it doesn't process numeric character references (which are both legal and seen in the wild in /href/ attributes). -M- From deets at nospam.web.de Mon Aug 11 03:05:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 11 Aug 2008 09:05:39 +0200 Subject: Wildcards for regexps? In-Reply-To: <7de4bd2e-bb0e-44b8-b7ed-24ca7f46ab2b@25g2000hsx.googlegroups.com> References: <7de4bd2e-bb0e-44b8-b7ed-24ca7f46ab2b@25g2000hsx.googlegroups.com> Message-ID: <6ga6m3Fetd0fU1@mid.uni-berlin.de> ssecorp schrieb: > If I have an expression like "bob marley" and I want to match > everything with one letter wrong, how would I do? > so "bob narely" and "vob marley" should match etc. Fuzzy matching is better done using Levensthein-distance [1] or n-gram-matching [2]. Diez [1] http://en.wikipedia.org/wiki/Levenshtein_distance [2] http://en.wikipedia.org/wiki/Ngram#n-grams_for_approximate_matching From george.trojan at noaa.gov Mon Aug 25 12:13:23 2008 From: george.trojan at noaa.gov (George Trojan) Date: Mon, 25 Aug 2008 16:13:23 +0000 Subject: tkinter: Round Button - Any idea? In-Reply-To: References: Message-ID: akineko wrote: > Hello everyone, > > I'm trying to implement a virtual instrument, which has buttons and > displays, using Tkinter+Pmw. > One of items on the virtual instrument is a round button. > This is imitating a tact switch. > > Tkinter has a Button class, which I can assign a button image. > However, when the button is depressed, the rectangle is sunken (rather > than the round button). > > Probably I need to prepare two images, normal one and depressed one, > and implement all button behaviours by myself. > But before reinventing everything by myself, I'm wondering if there is > an easy way to implement or there is existing widget example of such > button. > So far, I couldn't find any good examples. > > Any suggestions are highly appreciated. > > Best regards, > Aki Niimura Try http://search.cpan.org/~darnold/Tk-StyledButton-0.10/lib/Tk/StyledButton.pod. This is Perl, but it might be worthwhile to take a look at implementation. George From deets at nospam.web.de Wed Aug 20 10:43:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 20 Aug 2008 16:43:50 +0200 Subject: simple Question about using BeautifulSoup References: Message-ID: <6h2outFidk8kU1@mid.uni-berlin.de> Alexnb wrote: > > Okay, I have used BeautifulSoup a lot lately, but I am wondering, how do > you open a local html file? > > Usually I do something like this for a url > > soup = BeautifulSoup(urllib.urlopen('http://www.website.com') > > but the file extension doesn't work. So how do I open one? The docs for urllib.urlopen clearly state that it returns a file-like object. Which BS seems to grok. So... how about passing another file-like object, like... *drumroll* - a file? soup = BeautifulSoup(open("myfile.html")) Apart from the documented possibility to pass the html as string, which means soup = BeautifulSoup(open("myfile.html").read()) will work as well. Diez From deets at nospam.web.de Wed Aug 6 08:16:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 06 Aug 2008 14:16:09 +0200 Subject: enhancing decorator signatures Message-ID: <6ftj2fFd70cgU1@mid.uni-berlin.de> Hi, I'm using Michele S's decorator-module to create decorators with matching signatures, for better error-catching. However, I now want to enrich the signature of a generic wrapper so that the new function will accept more parameters (keyword only). These additional parameters are consumed by the wrapper and not passed to the decorated function. So something like this would be cool: @enriched_decorator("bar") def some_decorator(f, **args, **kwargs): bar = kwargs.pop("bar") return f(**args, **kwargs) Anybody has done something like this? Diez From bill.pursell at gmail.com Wed Aug 6 01:34:59 2008 From: bill.pursell at gmail.com (William Pursell) Date: Tue, 5 Aug 2008 22:34:59 -0700 (PDT) Subject: What Python looks like References: Message-ID: <5fbe65a5-c2ea-465c-ab3c-c2fe1daa8931@m36g2000hse.googlegroups.com> On 5 Aug, 16:08, Brett Ritter wrote: > On Aug 4, 3:43?pm, Gary Herron wrote: > > > A page of Python code looks *clean*, ?with not a lot of > > punctuation/special symbols and (in particular) no useless lines > My first impression of Python was that it was visually hard to parse. > > Put another way, imagine math went from: > 2 + 2 = 4 > to: > two plus two equals four > and then someone decided to abbreviate: > two pl two eq four That looks more like tcl than python to me. My first reaction to python was a strong dislike of indentation as a block delimeter and the convention of using '__*__' names. I got over my issue with indentation fairly quickly, but still don't care for the excessive underscores. However, overall I thought it was extremely clean and easy to write. By the time I saw Python, I had already essentially given up on Perl, but it only took 20 minutes going through the tutorial to completely nail down the lid on the coffin of my Perl self. To summarize the first impression: clean, simple, powerful, and a lot of potential. From jura.grozni at gmail.com Mon Aug 11 11:49:44 2008 From: jura.grozni at gmail.com (azrael) Date: Mon, 11 Aug 2008 08:49:44 -0700 (PDT) Subject: Eclipse, Python, wxPython and code completion References: <94acefa8-f3ec-4d5a-a7cb-a3bf769d35e9@79g2000hsk.googlegroups.com> <9d29ac73-dbe0-44fc-b3a9-b9f74a6aa38c@34g2000hsh.googlegroups.com> Message-ID: <2518f2ba-f2f9-4bee-a388-764d443f52fd@z72g2000hsb.googlegroups.com> if you need a good python ide with great code completition, then why don't you try WingIde. On 11 kol, 10:49, leon.domi... at gmail.com wrote: > On 11 ago, 04:34, "SPE - Stani's Python Editor" > > > > > > wrote: > > On 10 aug, 20:42, leon.domi... at gmail.com wrote: > > > > Hello, > > > > I've installed Eclipse, Python 2.5 and wxPython on Ubuntu 8.04. The > > > problem is that I can't get code completion for wx module. I don't > > > know if it occurs the same with other libraries outside the python > > > "core". > > > > If I compile/run my code containing the wx library, I get an > > > application running correctly, so it looks that definition works fine. > > > Obviously, the obstacle is that I don't know (I don't want to either) > > > the name of every method of every wxPython class so it's difficult to > > > develop anything within this environment. > > > > Thanks a lot > > > > Note: I'm a newbie-coming-from-"Billy's"-WindowsXP > > > You can try SPE which is written in wxPython itself and has very good > > code completion for wxPython. It also includes some wxPython GUI > > builders such as wxGlade and XRCed. I improved it a lot for Hardy, > > which I use myself: > > sudo apt-get install spe > > > Stani > > Thanks, Stani > > I will check this out From kyosohma at gmail.com Wed Aug 6 16:02:33 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 6 Aug 2008 13:02:33 -0700 (PDT) Subject: Parsing of a file References: Message-ID: <760c7cd4-5a23-4e8e-801d-31670afd050b@l42g2000hsc.googlegroups.com> On Aug 6, 1:55?pm, Tommy Grav wrote: > I have a file with the format > > Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames ? > 5 Set 1 > Field f31448: Ra=20:24:58.13 Dec=+79:39:43.9 MJD=53370.06811620 Frames ? > 5 Set 2 > Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames ? > 5 Set 3 > Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames ? > 5 Set 4 > Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames ? > 5 Set 5 > Field f30560: Ra=20:27:01.82 Dec=+74:47:50.3 MJD=53370.06860400 Frames ? > 5 Set 6 > Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames ? > 5 Set 7 > Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames ? > 5 Set 8 > Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames ? > 5 Set 9 > Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames ? > 5 Set 10 > > I would like to parse this file by extracting the field id, ra, dec ? > and mjd for each line. It is > not, however, certain that the width of each value of the field id, ? > ra, dec or mjd is the same > in each line. Is there a way to do this such that even if there was a ? > line where Ra=****** and > MJD=******** was swapped it would be parsed correctly? > > Cheers > ? ?Tommy I'm sure Python can handle this. Try the PyParsing module or learn Python regular expression syntax. http://pyparsing.wikispaces.com/ You could probably do it very crudely by just iterating over each line and then using the string's find() method. Mike From spe.stani.be at gmail.com Sun Aug 10 22:34:44 2008 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: Sun, 10 Aug 2008 19:34:44 -0700 (PDT) Subject: Eclipse, Python, wxPython and code completion References: <94acefa8-f3ec-4d5a-a7cb-a3bf769d35e9@79g2000hsk.googlegroups.com> Message-ID: On 10 aug, 20:42, leon.domi... at gmail.com wrote: > Hello, > > I've installed Eclipse, Python 2.5 and wxPython on Ubuntu 8.04. The > problem is that I can't get code completion for wx module. I don't > know if it occurs the same with other libraries outside the python > "core". > > If I compile/run my code containing the wx library, I get an > application running correctly, so it looks that definition works fine. > Obviously, the obstacle is that I don't know (I don't want to either) > the name of every method of every wxPython class so it's difficult to > develop anything within this environment. > > Thanks a lot > > Note: I'm a newbie-coming-from-"Billy's"-WindowsXP You can try SPE which is written in wxPython itself and has very good code completion for wxPython. It also includes some wxPython GUI builders such as wxGlade and XRCed. I improved it a lot for Hardy, which I use myself: sudo apt-get install spe Stani From gopsychonauts at gmail.com Sun Aug 24 04:18:31 2008 From: gopsychonauts at gmail.com (MeTheGameMakingGuy) Date: Sun, 24 Aug 2008 01:18:31 -0700 (PDT) Subject: No method overloading References: <569491c4-f7e2-4575-8f10-451f8ddb1916@k7g2000hsd.googlegroups.com> Message-ID: On Aug 24, 6:15?pm, Hussein B wrote: > Hey, > Please correct me if I'm wrong but Python doesn't support method > overload, right? > -- > def method(self): > ?#code > def method(self, data): > ?#code > -- > The last declaration of method() erase the previous one (like > JavaScript). > Thanks. Correct. The second declaration overwrites the first. Give data a default argument instead: def method(self, data=None): if data is None: # Normal code else: # data included code Not sure how Pythonic that is, but it should work the way you're requesting... I think. From gminick at nie.ma.takiego.adresu.w.sieci.pl Tue Aug 12 05:05:33 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Tue, 12 Aug 2008 09:05:33 +0000 (UTC) Subject: very rare python expression References: Message-ID: Dnia Tue, 12 Aug 2008 16:39:27 +0800, =?GB2312?B?zPC5zw==?= napisa?(a): > Howdy everyone, > > I saw a strange python code in pygame project. What does "while > not(x&528or x in l):" mean? Below code works in python2.5, so "x&528" > is not HTML strings. It looks like a check if 528 flag is set. In this way you can set more than one flag in signle variable: >>> flag1 = 1 >>> flag2 = 2 >>> flag3 = 4 >>> flag4 = 8 >>> flag5 = 10 >>> flags_set = flag2 | flag4 >>> flags_set & flag1 0 >>> flags_set & flag2 2 >>> flags_set & flag3 0 >>> flags_set & flag4 8 >>> flags_set & flag5 0 -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From rajanikanth at gmail.com Wed Aug 20 17:44:35 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Wed, 20 Aug 2008 14:44:35 -0700 Subject: Detect a sequence of keystrokes in an os independent way In-Reply-To: <84bdef3c0808201421tf88ef1dg5e828c00091c4ade@mail.gmail.com> References: <84bdef3c0808201421tf88ef1dg5e828c00091c4ade@mail.gmail.com> Message-ID: <84bdef3c0808201444t193f8045n18bf96990e270e6f@mail.gmail.com> Hi! I was able to do this in the following way: import os fKey= raw_input('') if fKey=='ab': print(os.listdir(os.getcwd())) Is there a better way to do this? Thanks, Raj On Wed, Aug 20, 2008 at 2:21 PM, Rajanikanth Jammalamadaka wrote: > Hi! > > Can somebody tell me if there is an os independent way to detect a > sequence of key strokes. For example, I want to start some other > program once the user presses a couple of keys: ex: key a and then key > b > > Thanks, > > Raj > > -- > "For him who has conquered the mind, the mind is the best of friends; > but for one who has failed to do so, his very mind will be the > greatest enemy." > > Rajanikanth > -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From tjreedy at udel.edu Mon Aug 18 18:21:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 18 Aug 2008 18:21:48 -0400 Subject: Programming Languages Decisions In-Reply-To: References: Message-ID: > This report is intended for any computer programming experts who > would like to propose that their favorite programming language is the one > that should be used for the potentially important application that is being > discussed here. I believe more scientists are happy programming in Python than Perl. Python reads like 'executable pseudocode'. It is, I believe, easier for most people to read and understand than Perl. Rather than explain further, I suggest that you visit python.org and read some of the tutorial to see what *you* think. http://docs.python.org/tut/tut.html tjr From andrew at ilium.invalid Fri Aug 29 02:55:16 2008 From: andrew at ilium.invalid (andrew) Date: Fri, 29 Aug 2008 16:55:16 +1000 Subject: computer support References: <01e84436-c94a-42e4-b5db-2ce0f5908498@k30g2000hse.googlegroups.com> Message-ID: <20080829165448.574@ilium.andrews-corner.org> On 2008-08-29, atrooja1998 at gmail.com wrote: > hello every body in the group Hello Dr Nick :-) -- http://www.andrews-corner.org From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 5 05:28:33 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 05 Aug 2008 11:28:33 +0200 Subject: Python-URL! - weekly Python news and links (Jul 28) In-Reply-To: References: Message-ID: <48981d41$0$17009$426a74cc@news.free.fr> Gabriel Genellina a ?crit : > QOTW: "Python's goals are to maximize opportunities for good > programming, which is quite different." - Bruno Desthuilliers, contrasting > Python with Java > I'm afraid I mostly (and approximatly) quoted somebody else here (just don't ask me for a link to the original...). From sjmachin at lexicon.net Sun Aug 31 20:26:43 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 31 Aug 2008 17:26:43 -0700 (PDT) Subject: Is this a closure? References: <762bc148-281d-4076-8225-280e42d081bd@d45g2000hsc.googlegroups.com> Message-ID: <2e688db6-9fa5-4595-9bcd-91961bf79a05@b30g2000prf.googlegroups.com> On Sep 1, 9:53 am, ssecorp wrote: > A method on a class: > > def printSelf(self): > def printReviews(): > for review in self.reviews: > review.printSelf() > print "Idnbr: ", self.idnumber, "Reviews: ", printReviews() > The above appears to be more or less identical in effect to: def printSelf(self): print "Idnbr: ", self.idnumber, "Reviews: " for review in self.reviews: review.printSelf() except for spacing and more importantly the second version won't print the gratuitous None value returned by printReviews(). What are you aiming for? If your purpose is to explore/understand lexical scopes, I suggest that you get it right in your head in the context of a simple non-recursive function, then /if necessary/ try to do it in a recursive class method. HTH, John From nospam at invalid.com Thu Aug 7 03:01:53 2008 From: nospam at invalid.com (jlist) Date: Thu, 7 Aug 2008 00:01:53 -0700 Subject: benchmark References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> Message-ID: I think what makes more sense is to compare the code one most typically writes. In my case, I always use range() and never use psyco. But I guess for most of my work with Python performance hasn't been a issue. I haven't got to write any large systems with Python yet, where performance starts to matter. > That Python code is bad, it contains range() instead of xrange, the > big loop is in the main code instead of inside a function, uses == > None, etc. That person can try this (with Psyco), I have changed very > little, the code is essentially the same: From python-url at phaseit.net Tue Aug 5 09:51:13 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 5 Aug 2008 13:51:13 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Aug 5) Message-ID: QOTW: "As a project manager, I have never had trouble finding people with crazy ideas. I have trouble finding people who can execute. IOW, 'innovation' is way oversold. And it sure as hell shouldn't be applied to products like MS Word or Open office." - Linus http://www.simple-talk.com/opinion/geek-of-the-week/linus-torvalds,-geek-of-the-week/ A very long thread: now arguing against "self", and whether "if x:" enhances polymorphism or not: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a5fa8ff0ffadd6ee/ Floating point representation errors explained (0.2==0.20000000000000001): http://groups.google.com/group/comp.lang.python/browse_thread/thread/9e4f8dce08743c22/ Difference between "type" and "class": http://groups.google.com/group/comp.lang.python/browse_thread/thread/5ae03a438383ba65/ Recursive inner functions aren't destroyed as soon as the outer function exits: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4dbf149b6ded7b84/ "Interpreted" vs "Compiled" programs and languages: http://groups.google.com/group/comp.lang.python/browse_thread/thread/d36bc1db8e64e18c/ Iterating over a sequence by two elements at a time: http://groups.google.com/group/comp.lang.python/browse_thread/thread/85e416759ce1b314/ Coming from Java, "module" and "import" can be confusing terms: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c0a78d37bc010e4e/ __getattr__ with multiple inheritance requires cooperative base classes: http://groups.google.com/group/comp.lang.python/browse_thread/thread/8d05f8 b6c7575c6f/ The different 64-bit architectures and their names are rather confusing: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b8bcb70ad78030dd/ How to define "static variables" in Python: http://groups.google.com/group/comp.lang.python/browse_thread/thread/86db8568d09b5344/ ======================================================================== 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. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org 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 Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html 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 Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. 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://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. 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://www.python.org/dev/peps/pep-0042/ 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!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From gstaniak at wp.pl Mon Aug 25 13:04:07 2008 From: gstaniak at wp.pl (Grzegorz Staniak) Date: Mon, 25 Aug 2008 17:04:07 +0000 (UTC) Subject: Equivalents of Ruby's "!" methods? References: <74d712c2-9a6c-41ab-8d24-4a8084b8e56b@d45g2000hsc.googlegroups.com> Message-ID: On 25.08.2008, Terry Reedy wroted: > The newish sorted() and reversed() built-ins were meant to complement > list.sort and list.reverse, not replace them. BTW, is there a reason why sorted() on a list returns a list, while reversed() on the same list returns an iterator? GS -- Grzegorz Staniak From vedrandekovic at yahoo.com Fri Aug 8 13:11:28 2008 From: vedrandekovic at yahoo.com (vedrandekovic at yahoo.com) Date: Fri, 8 Aug 2008 10:11:28 -0700 (PDT) Subject: .cpp to .pyd References: Message-ID: <8a2eea23-1d72-4653-8a8f-c2bb56bc47f6@l64g2000hse.googlegroups.com> On 7 kol, 21:43, Carl Banks wrote: > On Aug 7, 3:25?am, vedrandeko... at yahoo.com wrote: > > > > > Hello, > > > I want to build my C++ (.cpp) script to (.pyd) like this: > > >http://en.wikibooks.org/wiki/Python_Programming/Extending_with_C%2B%2B > > > I have installed "Microsoft Visual studio .NET 2003" and "Boost > > Python" and then after I run my setup script: > > > python setup.py build > > > I get this error: > > > running build > > running build_ext > > building 'hello' extension > > D:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\cl.exe /c / > > nologo /Ox > > ?/MD /W3 /GX /DNDEBUG -IC:\Panda3D-1.5.2\python\include -IC: > > \Panda3D-1.5.2\pytho > > n\PC /Tphellomodule.cpp /Fobuild\temp.win32-2.5\Release > > \hellomodule.obj > > hellomodule.cpp > > hellomodule.cpp(9) : fatal error C1083: Cannot open include file: > > 'boost/python/ > > module.hpp': No such file or directory > > error: command '"D:\Program Files\Microsoft Visual Studio .NET > > 2003\Vc7\bin\cl.e > > xe"' failed with exit status 2 > > > I think that my MS visual studio ?cannot find "boost python", if > > that's the problem then can you tell me how can I solve it. > > This is very begginer question,but I can't find answer nowhere, and I > > don't have any expirience with Microsoft products. > > > Sorry for my bad english! > > Regards, > > Veki > > First, locate the boost header files. ?Suppose you find the file > module.hpp in this location: > > C:\boost-whatever-version\include\boost\python\module.hpp > > The part that comes before boost\python\module.hpp is the required > include directory. ?You can tell setup to use this directory by adding > the following argument to the Extension call: > > include_dirs = ['C:\\boost-whatever-version\\include'] > > Notice the doubling of backslashes. ?Remember to add the directory > where the boost header files lie on your system; don't add this line > exactly. > > You should end up with a setup call that looks like this: > > setup(name="blah", > ? ? ext_modules=[ > ? ? ? ? Extension("hello", ["hellomodule.cpp"], > ? ? ? ? ? ? libraries = ["boost_python"], > ? ? ? ? ? ? include_dirs = ['C:\\boost-whatever-version\\include']) > ? ? ]) > > Carl Banks Hi, Thanks for quick reply.Maybe I'm crazy but I did what you said and I stll get the same error :( :( :( :(.I have boost version 1.34.1 and I'm running it on Windows XP SP2. Regards, Veki From tjreedy at udel.edu Thu Aug 7 15:19:26 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 07 Aug 2008 15:19:26 -0400 Subject: Best practise implementation for equal by value objects In-Reply-To: <573362d6-5356-4029-8ee4-f43248263976@p25g2000hsf.googlegroups.com> References: <135eb396-6daa-4ff4-a722-253ba149889c@27g2000hsf.googlegroups.com> <573362d6-5356-4029-8ee4-f43248263976@p25g2000hsf.googlegroups.com> Message-ID: Slaunger wrote: > On 6 Aug., 21:36, Terry Reedy wrote: > OK, the situation is more complicated than that then. In the case here > though, > the attributes would always be sinmple bulit-in types, where > eval(repr(x))==x > or, where the attribute is a user-defined equal-by-value class, that I > have > control over. I think most would agree that a more accurate and informative representation is better than a general representation like Pythons default. For instance, >>> a=range(2,10,2) # 3.0 >>> a range(2, 10, 2) is nicer than . So when the initializers for instances are all 'nice' (as for range), go for it (as in 'Age(10)'). And test it as you are by eval'ing the rep. Just accept that the eval will only work in contexts with the class name bound to the class. For built-in like range, it always is, by default -- unless masked by another assignment! Terry Jan Reedy From python6+4 at ulfbaur.de Tue Aug 19 15:55:12 2008 From: python6+4 at ulfbaur.de (mounty) Date: Tue, 19 Aug 2008 21:55:12 +0200 Subject: Idle is not accepting backslashes on some Mac OSX keyboards Message-ID: <48AB2520.7060503@ulfbaur.de> Hi list, I am using a German keyboard on Mac OS X 10.4.11. Idle 1.2.2 is constantly blocking entering the backslash character '\' which is for instance perfectly accepted by my mail application, as you can see for yourself. If I switch to an US, Australian or English keyboard layout the backslash can be entered. Unfortunately this key position is the pound- sign '#' on a German keyboard. The same applies to (German) Switzerland and Austrian keyboards as well. google lists several inquiries like this one: http://bugs.python.org/issue3493 It seems to me that the backslash is hard coded to the physical key in Idle. However this key position is occupied by the '#' pound-sign in the lower-case position of the German keyboard layout. The upper case letter for this physical key is a single quote "'". If I copy the backslash character from a different application into idle, the character will be processed. And as there is no input problem with the terminal program which is shipped with OS X, the problem should be somewhere in Idle. IMHO of course. Here is a photo of the German keyboard layout: http://de.wikipedia.org/wiki/Bild:2007_09_30_de_Apple-Tastatur.jpg If anybody is curious about how we have to enter a backslash, it's "Alt-Shift-7" no matter if you are using OS X, Windows or Linux. Can anyone advise how to proceed. Many thanks Ulf From sjmachin at lexicon.net Fri Aug 29 19:28:20 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 29 Aug 2008 16:28:20 -0700 (PDT) Subject: Date Comparison and Manipulation Functions? References: <6cdf0c14-80b6-42c4-8047-8c01fda8b87c@r15g2000prh.googlegroups.com> <9U8tk.19080$cW3.13729@nlpi064.nbdc.sbc.com> <8AVtk.8079$np7.5970@flpi149.ffdc.sbc.com> Message-ID: <4ad1c85c-479c-44e5-ac1b-ca0509d40c42@s20g2000prd.googlegroups.com> On Aug 30, 2:32 am, "W. eWatson" wrote: > I just tried the following code, and got an unexpected result. > > from pyfdate import * > t = Time() > > ts = Time(2008, 8, 29,15,20,7) > tnew = ts.plus(months=6) > print "new date: ", tnew > > Result: > new date: 2009-02-28 15:20:07 > > I believe that should be April 1, 2009. Presuming that we are talking about the Gregorian calendar, and not one of your own invention, you are (one trusts) alone in that belief. There are SEVEN whole months and a bit between August 29, 2008 and April 1, 2009. Count the months: Sep, Oct, Nov, Dec, Jan, Feb, Mar. > If I use months = 1 and day =31, I > get Sept. 30, 2008 and not Oct. 1, 2008. Is there a way to get around this? Because the number of days in a month is not constant, adding a number of months to a date is capable of more than one interpretation. Most folk are happy with adding the months on and then ensuring that the day is not later than the last day of the resultant (year, month) combination -- this is what the pyfdate routine appears to be doing. However there are some interesting ideas floating around e.g. IIRC an eminent personage once asserted in this newsgroup that adding 1 month to 31 Jan in a non-leap year should produce 3 Mar. There is also the general question with date intervals of whether the first day is included in the calculation or not. E.g. work on Monday, Tuesday, Wednesday: that's 3 days service. Put money into the bank on Monday, withdraw it on Wednesday: that's likely to attract 2 days interest. One needs to understand exactly what calculation is required, and exactly what calculation is provided by the software that is proposed to be used. HTH, John From sriramrajan at acm.org Mon Aug 4 19:54:19 2008 From: sriramrajan at acm.org (Sriram Rajan) Date: Mon, 4 Aug 2008 16:54:19 -0700 Subject: Module re, extract on string match Message-ID: I am wondering if I can use re.search to extract from a particular location in a string. Example: string1='/Users/sriram/folder1/folder2/folder3/folder4/folder5/file' re.search ('folder3,string1) Thanks, Sriram From sjmachin at lexicon.net Thu Aug 21 18:41:24 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 21 Aug 2008 15:41:24 -0700 (PDT) Subject: Could anyone point me to a good site for pearl compiler download References: <437b50e2-d1dc-42e6-ba52-d369312ab5d8@j1g2000prb.googlegroups.com> Message-ID: <8ec528e9-b21a-4a38-99da-7b11db2a91e9@r15g2000prh.googlegroups.com> On Aug 22, 5:01 am, thejm... at gmail.com wrote: > I think he wants to know where he can find good abalone. Which he may have confused with baloney. From circularfunc at gmail.com Tue Aug 12 13:14:05 2008 From: circularfunc at gmail.com (ssecorp) Date: Tue, 12 Aug 2008 10:14:05 -0700 (PDT) Subject: super, object and type? Message-ID: <6632d5a3-78b1-44f8-badb-626605971303@k37g2000hsf.googlegroups.com> >>> super(object, type) , > >>> super(type, object) , > >>> how can both work? they can't both be the superclass of each other right? or is it some sort of mutually recursive definition? >>> help(object) Help on class object in module __builtin__: class object | The most base type >>> help(type) Help on class type in module __builtin__: class type(object) | type(object) -> the object's type | type(name, bases, dict) -> a new type From mu at problemlos.ch Tue Aug 19 07:50:25 2008 From: mu at problemlos.ch (Kurt Mueller) Date: Tue, 19 Aug 2008 13:50:25 +0200 Subject: Getting pid of a remote process In-Reply-To: <197551.74424.qm@web7904.mail.in.yahoo.com> References: <197551.74424.qm@web7904.mail.in.yahoo.com> Message-ID: <48AAB381.1060200@problemlos.ch> srinivasan srinivas schrieb: > Thanks a lot. > But i am wondeing will it return correct pid if more than one instance of run on the remote machine?? > Thanks, > Srini On UNIX-like OS: If you start the process in the background, you can get the PID with: :~> ssh 'ls -l & echo PID=$!' | grep PID PID=30596 :~> see: man bash -> Special Parameters Gr?essli -- Kurt M?ller, mu at problemlos.ch From mh at pixar.com Tue Aug 26 12:42:30 2008 From: mh at pixar.com (mh at pixar.com) Date: Tue, 26 Aug 2008 16:42:30 GMT Subject: Best idiom for looping over input? Message-ID: What's the best Python idiom for this C construct? while ((x = next()) != END) { .... } Now I'm doing x = next() while x != END: .... x = next() There's not an iterator for this function, or I would just use for x in ... Many TIA! Mark -- Mark Harrison Pixar Animation Studios From tjreedy at udel.edu Fri Aug 8 00:04:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 08 Aug 2008 00:04:48 -0400 Subject: how to find out if an object is a class? In-Reply-To: <2de677cb-7dc8-43db-b249-cef11ea62f03@m36g2000hse.googlegroups.com> References: <2de677cb-7dc8-43db-b249-cef11ea62f03@m36g2000hse.googlegroups.com> Message-ID: Carl Banks wrote: > On Aug 7, 8:56 pm, Terry Reedy wrote: >> That is only true and only works for 2.x old-style classes and not for >> 2.x new-style classes and all 3.0 classes, for which isinstance(Q,type) >> is True. > > isinstance(Q,type) is also true for built in types and C extension > types That is rather the point of new and improved classes -- that the implementation language of a class be pretty much irrelevant from the user api viewpoint ;-) From mmanns at gmx.net Sun Aug 24 18:52:56 2008 From: mmanns at gmx.net (Martin Manns) Date: Mon, 25 Aug 2008 00:52:56 +0200 Subject: ANN: pyspread 0.0.9 Message-ID: pyspread 0.0.9 has been released. About: pyspread is a spreadsheet that accepts a pure python expression in each cell. New features: + Find & Replace + Undo & Redo + New context menu in grid + Improved speed especially for large grids + Relative addressing revamped + CSV import improved + Icons changed to Tango iconset + Docstrings improved + Bug fixes in print framework Highlights: + Numpy high performance arrays for spreadsheet calculation + Full access to python batteries from each cell + No non-python syntax add-ons + 3D grid + Cell access via slicing of numpy array S + X, Y, and Z yield current cell location for relative reference Notes: Please use distutils for installation. Make sure that the old files are deleted: $ su $ rm -Rf [MyPythonPath]/site-packages/pyspread* $ python setup.py install $ exit $ pyspread.py Requires: Python >=2.4, Numpy >=1.1.0, and wxPython >=2.8.7.1. License: GPL Project page: http://pyspread.sourceforge.net Enjoy Martin From deets at nospam.web.de Tue Aug 19 02:54:34 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 19 Aug 2008 08:54:34 +0200 Subject: Python Substitute for PHP GD, Resizing an image on the client side In-Reply-To: <02f733bb-e734-46a9-b42f-5b664cdddd3f@v26g2000prm.googlegroups.com> References: <02f733bb-e734-46a9-b42f-5b664cdddd3f@v26g2000prm.googlegroups.com> Message-ID: <6gv91bFhm5u5U1@mid.uni-berlin.de> brahmaforces schrieb: > Hi Folks, > > I am using cherrypy and python. I am trying to get a user profile > image to resize on the client side before uploading to the server. PHP > has a gd library that does it it seems. Has anyone done this in a > python environment without uploading to the server? Everything PHP is server-side. And displaying images is *always* done through uploading and then displaying it. The resizing is done using JavaScript, and then communicating back the selected rectangle to the server - *then* GD or whatnot (PIL, ImageMagick) are used to resize the image. Diez From tjreedy at udel.edu Tue Aug 26 22:34:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 26 Aug 2008 22:34:51 -0400 Subject: sum up numbers in a list In-Reply-To: References: Message-ID: sharon kim wrote: > is there a way to sum up all the numbers in a list? >>> help(sum) sum(...) sum(iterable[, start]) -> value Returns the sum of an iterable of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). When the iterable is empty, returns start. >>> L=[28,39,20,78490,37373,22,2,33,4,5] >>> sum(L) 116016 From timothy.grant at gmail.com Sun Aug 10 01:38:34 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Sat, 9 Aug 2008 22:38:34 -0700 Subject: some kind of trace facility ? In-Reply-To: <489E24F0.6030508@gmail.com> References: <489E24F0.6030508@gmail.com> Message-ID: n Sat, Aug 9, 2008 at 4:14 PM, Stef Mientki wrote: > hello, > > I want to investigate on a regular base the flow of my Python (most of them > using wxPython) programs. > So I want to have some log facilty, that logs things like > - every time a function / method is called > - the time spent in that function / method (or even better start / finish > time) > - in case the function / method has some predefined variables, the values of > these variables > - the caller > > As an extra condition, I'm only interested in my own program modules > (located in a specific subdirectory). > > Is there a module available that can perform such a task ? > Any hints to get started ? > > thanks, > Stef Mientki As is often the case, I have never used this technique, but have read about it: You may want to investigate a logging decorator. Python's Decorator module has a decorator factory that should allow you to log at least the calls. I'm not sure it would help you much with the time the method took, but I could very well be wrong about that. -- Stand Fast, tjg. [Timothy Grant] From timr at probo.com Mon Aug 11 20:58:51 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 11 Aug 2008 17:58:51 -0700 Subject: Broken examples In-Reply-To: <48A0DAF6.4040207@hughes.net> References: <48A0DAF6.4040207@hughes.net> Message-ID: <48A0E04B.1040006@probo.com> norseman wrote: > Tim; > Finally got a chance to test your snippet. Thank you for it! > > I took the liberty of flushing it out a bit. > ================ > #!/--- > # > import os > import win32com.client > > excel = win32com.client.Dispatch( 'Excel.Application' ) > excel.Visible=1 # shows the spreadsheet (can be handy) > xlCSV = 6 > # substitute for list generation > list = ["c:\\temp\\test.xls", "c:\\temp\\test1.xls"] > > for nm in list: > csv = os.path.splitext( nm )[0] + '.csv' > print "Procesing file:", csv > if os.path.exists(csv): # window$ won't auto overwrite > os.unlink(csv) > wb = excel.Workbooks.Open( nm ) > wb.SaveAs( csv, xlCSV ) > print wb.Close() # requires manual verification > # eliminating unattended runs > > #wb.Exit() & wb.Quit() # generate ERROR(s) - no such thing(s) > # leaving Excel open > > excel.Visible=0 # actually closes Excel if no sheet open > # verified via task manager > > print "Check to see if this worked." > > # end of file > ================= > The above does in fact work. > Using the above I have a few questions. > Documentation on xlCSV came from where? > " on .Workbooks.Open(file.xls) came from ??? > " on .SaveAs( filename, xlCSV ) came from ??? > " on .Close() came from ??? MSDN has rather extensive documentation on the Excel object model, although it is somewhat spread out. Search for "Excel object model". I cheated on xlCSV. That's the name of the symbol, and I believe it will even be available as win32com.client.constants.xlCSV after you instantiate the application, but I just searched the web for "xlCSV" and hard-coded the 6. > Tell me about the lack of the .Exit() and/or .Quit(), please. Workbooks don't exit or quit. Workbooks can be closed, but exit is something that applies to the application (excel, in your case). You should also be able to say excel = None to get rid of the app. > I ran out of time today. Is it possible to send something like an > keystroke to a Window () box if it accepts same from > actual keyboard? May not work anyway since .Close() hangs (in > interactive) awaiting it's answer. The Workbook.Close method accepts parameters; you should be able to get it to skip the dialog. I believe that wb.Close( False ) should do this. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From circularfunc at gmail.com Mon Aug 11 00:18:53 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 10 Aug 2008 21:18:53 -0700 (PDT) Subject: for x,y in word1, word2 ? Message-ID: Is there a syntax for looping through 2 iterables at the same time? for x in y: for a in b: is not what I want. I want: for x in y and for a in b: From mail at timgolden.me.uk Tue Aug 19 11:58:54 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 19 Aug 2008 16:58:54 +0100 Subject: How to use win32com to convert a MS WORD doc to HTML ? In-Reply-To: <29de18070808190706mfb6224ya189b63545c05d84@mail.gmail.com> References: <29de18070808190706mfb6224ya189b63545c05d84@mail.gmail.com> Message-ID: <48AAEDBE.6090400@timgolden.me.uk> Lave wrote: > Hi, all ! > > I'm a totally newbie huh:) > > I want to convert MS WORD docs to HTML, I found python windows > extension win32com can make this. But I can't find the method, and I > can't find any document helpful. You have broadly two approaches here, both involving automating Word (ie using the COM object model it exposes, referred to in another post in this thread). 1) Use the COM model to have Word load your doc, and SaveAs it in HTML format. Advantage: it's relatively straightforward. Disadvantage: you're at the mercy of whatever HTML Word emits. 2) Use the COM model to iterate over the paragraphs in your document, emitting your own HTML. Advantage: you get control. Disadvantage: the more complex your doc, the more work you have to do. (What do you do with images, for example? Internal links?) To do the first, just record a macro in Word to do what you want and then reproduce the macro in Python. Something like this: import win32com.client doc = win32com.client.GetObject ("c:/data/temp/songs.doc") doc.SaveAs (FileName="c:/data/temp/songs.html", FileFormat=8) doc.Close () To do the second, you have to roll your own html doc. Crudely, this would do it: import codecs import win32com.client doc = win32com.client.GetObject ("c:/data/temp/songs.doc") with codecs.open ("c:/data/temp/s2.html", "w", encoding="utf8") as f: f.write ("") for para in doc.Paragraphs: text = para.Range.Text style = para.Style.NameLocal f.write ('

%(text)s

\n' % locals ()) doc.Close ()
TJG From saptarshi.guha at gmail.com Sat Aug 16 23:37:45 2008 From: saptarshi.guha at gmail.com (sapsi) Date: Sat, 16 Aug 2008 20:37:45 -0700 (PDT) Subject: QT, ctypes dll and SEG Faults Message-ID: Hello, Below is a small class using ctypes and libspectre to read a postscript file. My program is a PyQT 4.4 application and when the user clicks on a entry in a QTableWidget, i run PostScriptImage( filename_as_contained_in_clicked_tableWidgetItem ) However on i get a segfault while trying document_load. Surprisingly, before i run sys.exit(app.exec_()) (i.e before the app starts) if run PostScriptImage(command_line_specified_ps_file) it works! I know the ctypes so file works with QT since i wrote an application using it, but i hadn't separated the ctypes stuff into separate class (i.e the spectre code was in the widget method). Any ideas why the crash? Regards Saptarshi --Python Code-- class PostScriptImage: def __init__(self,filename): print "Doc New" self.document=libspec.spectre_document_new() print "Load Doc" , filename #############crashed in the following line######################### libspec.spectre_document_load(self.document,filename) print "Done load doc" if libspec.spectre_document_status(self.document): return False self.scale=[1.0,1.0] self.quicksetup() def quicksetup(self): print "RC" rc=libspec.spectre_render_context_new() print "Get 0th Page" page=libspec.spectre_document_get_page (self.document, 0) if libspec.spectre_document_status(self.document): raise Exception("Spectre:Setup Document Error") w= c_int() h= c_int() print "Page Size" libspec.spectre_page_get_size(page, byref(w),byref(h)) self.initialSize=(h.value*1.0,w.value*1.0) self.initialAspect=float(h.value)/float(w.value) self.npages=libspec.spectre_document_get_n_pages(self.document) From sjmachin at lexicon.net Sat Aug 9 07:45:48 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 9 Aug 2008 04:45:48 -0700 (PDT) Subject: How to round a floating point to nearest 10? References: Message-ID: On Aug 9, 9:31 pm, Will Rocisky wrote: > I want my 76.1 to be rounded to decimal 80 and 74.9 to decimal 70. > How can I achieve that? >>> import decimal >>> [decimal.Decimal(int(round(x, -1))) for x in (76.1, 74.9)] [Decimal("80"), Decimal("70")] >>> From brtzsnr at gmail.com Tue Aug 12 10:49:03 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Tue, 12 Aug 2008 07:49:03 -0700 (PDT) Subject: python interpreter Message-ID: <29e59f7a-af87-40b4-9c5e-58abe1a28721@t1g2000pra.googlegroups.com> I'm using python's interpreter's to run various commands (like a normal shell). However if sources are modified changes are not reflected so I have to restart interpreter. Is there any way to avoid restarting this? example: import blah blah.Blah() # ... blah.Blah() changed blah.Blah() # ... new behavior From ryntech at gmail.com Tue Aug 5 09:46:55 2008 From: ryntech at gmail.com (rynt) Date: Tue, 5 Aug 2008 06:46:55 -0700 (PDT) Subject: What Python looks like References: Message-ID: <31075ed4-0780-43a4-9440-45e86dbde87b@q5g2000prf.googlegroups.com> On Aug 4, 12:06?pm, iu2 wrote: > Hi, > > This is a little bit strange post, but I'm curious... > > I learned Python from its tutorial step by step, and practicing > writing small scripts. > I haven't seen a Python program before knowing Python. > > I'm curious, what did Python code look like to those of you who have > seen a bunch of Python code for the first time before knowing Python? > > (I can tell, for example, that seeing perl for the first time looked > like C with many $$$, I could see "if" and "for" and "while" but they > were meaningless. Or Lisp for the first time looked like many words, > no operators, how could that make a program???) > > Thanks I stumbled across Python in 2000 when I ran accross GNUe. I decided to look into Python at that time, and was impressed that the code was readable, and, understandable - even before I looked at the language and library refs. I had been working in a subset of Basic and Delphi at the time. I really don't like Pascal or C/C++ with all of the BEGIN/END and braces. I don't work in Python full time, but do use it for scripting, and "hobby" programming. One heck of a cool language! RCB From news1234 at free.fr Wed Aug 13 17:44:08 2008 From: news1234 at free.fr (nntpman68) Date: Wed, 13 Aug 2008 23:44:08 +0200 Subject: The python not starting under cmd.exe In-Reply-To: References: Message-ID: <48a355a8$0$13081$426a74cc@news.free.fr> durumdara at gmail.com wrote: > Hi! > > My problem is that: > The "test.py" is working in every machine that I use except in my home > machine. > Formerly it worked but now not. I don't know what happened, I searching > for some solution. > > The errormessage is this (after I tried to start test.py under cmd.exe): > > Microsoft Windows XP [verzi?sz?m: 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > c:\>test.py > A rendszer nem tudja v?grehajtani a megadott programot. > > c:\> > Did you try start test.py from the command line? Normally this tries to behave as if you clicked on the file from the explorer? bye N > > Sorry for non english, I try to translate it: > "The system cannot execute the program/application." > > Interesting thing that the starting from Explorer, FreeCommander, or > other tool (Double clicking, Hit enter on it) is working good, so the > "py" linked to the python. > I tried to set path, and pathext too but it have no effect. > > This command is working: > "python test.py". > > I don't know, why not working the "test.py" command, because in other > machines it is working good... :-((((( > > Thanks for any advance in this problem! > > dd > From aspersieman at gmail.com Thu Aug 14 02:52:09 2008 From: aspersieman at gmail.com (Aspersieman) Date: Thu, 14 Aug 2008 08:52:09 +0200 Subject: win32service and Python In-Reply-To: <1agogkuyrv3pv$.gtck933m0pt3.dlg@40tude.net> References: <1agogkuyrv3pv$.gtck933m0pt3.dlg@40tude.net> Message-ID: <48A3D619.6030802@gmail.com> David wrote: > I am collecting informations about win32 services for Python but, except for > few basic examples about Mark Hammond's win32serviceutil, I found nothing > useful. > > Any link is welcome. > > Thank you. > David > > This might also be useful: http://support.microsoft.com/kb/137890 It's doesn't register the service using python - but it's generic enough to work. HTH Nicolaas -- The three things to remember about Llamas: 1) They are harmless 2) They are deadly 3) They are made of lava, and thus nice to cuddle. From norseman at hughes.net Mon Aug 11 20:36:06 2008 From: norseman at hughes.net (norseman) Date: Mon, 11 Aug 2008 17:36:06 -0700 Subject: Broken examples Message-ID: <48A0DAF6.4040207@hughes.net> Tim; Finally got a chance to test your snippet. Thank you for it! I took the liberty of flushing it out a bit. ================ #!/--- # import os import win32com.client excel = win32com.client.Dispatch( 'Excel.Application' ) excel.Visible=1 # shows the spreadsheet (can be handy) xlCSV = 6 # substitute for list generation list = ["c:\\temp\\test.xls", "c:\\temp\\test1.xls"] for nm in list: csv = os.path.splitext( nm )[0] + '.csv' print "Procesing file:", csv if os.path.exists(csv): # window$ won't auto overwrite os.unlink(csv) wb = excel.Workbooks.Open( nm ) wb.SaveAs( csv, xlCSV ) print wb.Close() # requires manual verification # eliminating unattended runs #wb.Exit() & wb.Quit() # generate ERROR(s) - no such thing(s) # leaving Excel open excel.Visible=0 # actually closes Excel if no sheet open # verified via task manager print "Check to see if this worked." # end of file ================= The above does in fact work. Using the above I have a few questions. Documentation on xlCSV came from where? " on .Workbooks.Open(file.xls) came from ??? " on .SaveAs( filename, xlCSV ) came from ??? " on .Close() came from ??? Tell me about the lack of the .Exit() and/or .Quit(), please. I ran out of time today. Is it possible to send something like an keystroke to a Window () box if it accepts same from actual keyboard? May not work anyway since .Close() hangs (in interactive) awaiting it's answer. Tim - thank you again! At least this works well enough that a clerk can press until the thing runs out of material. :) Just press and hold the key until the buffer overflow beeps and go do some filing and when the screen 'stops' do it again... Eliminates typos. Thank you. Steve norseman at hughes.net From mblume at socha.net Sun Aug 24 11:05:25 2008 From: mblume at socha.net (mblume) Date: 24 Aug 2008 15:05:25 GMT Subject: recursively change values in list of lists References: Message-ID: <48b178b5$0$16174$5402220f@news.sunrise.ch> Am Sun, 24 Aug 2008 15:17:46 +0100 schrieb Carson Farmer: > Dear list, > > I'm sure this is a relatively trivial problem, but I have been unable to > find any good examples/explanations on how to do this, so here goes: > > I have multi-polygon object, which is simply a list of polygons, where > each polygon is a list of lines, where each line is a list of points. > What I would like to do, is change the x and y values of each point, all > the while keeping the structure of the lists intact. > > So in the end, the only thing that should be changed is the values, not > the lists themselves... clear as mud? > > Any hints, and/or suggestions are greatly appreciated, > I always do something along the lines of: for (i,obj) in enumerate(list_of_objects): obj = do_something_to_obj(obj) list_of_objects[i] = obj HTH. YMMV. Martin From jasmine956 at gmail.com Fri Aug 1 22:42:22 2008 From: jasmine956 at gmail.com (jasmine956 at gmail.com) Date: Fri, 1 Aug 2008 19:42:22 -0700 (PDT) Subject: HELP DESK SOFTWARE APPLICATION DESIGNED Message-ID: HELP DESK SOFTWARE APPLICATION DESIGNED ___________________________________ http://helpdesksoftwaremanagement.blogspot.com From aassime1 at hotmail.fr Thu Aug 21 08:18:48 2008 From: aassime1 at hotmail.fr (aassime abdellatif) Date: Thu, 21 Aug 2008 05:18:48 -0700 (PDT) Subject: ISLAM and the AIM of LIFE Message-ID: ISLAM and the AIM of LIFE What is your purpose in life? What is the rationale behind our life? Why do we live in this life? These questions frequently intrigue people who try to find accurate answers. People provide different answers to these questions. Some people believe the purpose of life is to accumulate wealth. But one may wonder: What is the purpose of life after one has collected colossal amounts of money? What then? What will the purpose be once money is gathered? If the purpose of life is to gain money, there will be no purpose after becoming wealthy. And in fact, here lies the problem of some disbelievers or misbelievers at some stage of their life, when collecting money is the target of their life. When they have collected the money they dreamt of, their life loses its purpose. They suffer from the panic of nothingness and they live in tension and restlessness. Can Wealth Be an Aim? We often hear of a millionaire committing suicide, sometimes, not the millionaire himself but his wife, son, or daughter. The question that poses itself is: Can wealth bring happiness to one?s life? In most cases the answer is NO. Is the purpose of collecting wealth a standing purpose? As we know, the five-year old child does not look for wealth: a toy for him is equal to a million dollars. The eighteen-year old adolescent does not dream of wealth because he is busy with more important things. The ninety-year old man does not care about money; he is worried more about his health. This proves that wealth cannot be a standing purpose in all the stages of the individual's life. Wealth can do little to bring happiness to a disbeliever, because he/ she is not sure about his fate. A disbeliever does not know the purpose of life. And if he has a purpose, this purpose is doomed to be temporary or self destructive. What is the use of wealth to a disbeliever if he feels scared of the end and skeptical of everything. A disbeliever may gain a lot of money, but will surely lose himself. Worshipping Allah as an Aim On the contrary, faith in Allah gives the believer the purpose of life that he needs. In Islam, the purpose of life is to worship Allah. The term "Worship" covers all acts of obedience to Allah. The Islamic purpose of life is a standing purpose. The true Muslim sticks to this purpose throughout all the stages of his life, whether he is a child, adolescent, adult, or an old man. Worshipping Allah makes life purposeful and meaningful, especially within the framework of Islam. According to Islam this worldly life is just a short stage of our life. Then there is the other life. The boundary between the first and second life is the death stage, which is a transitory stage to the second life. The type of life in the second stage a person deserves depends on his deeds in the first life. At the end of the death stage comes the day of judgment. On this day, Allah rewards or punishes people according to their deeds in the first life. The First Life as an Examination So, Islam looks at the first life as an examination of man. The death stage is similar to a rest period after the test, i. e. after the first life. The Day of Judgment is similar to the day of announcing the results of the examinees. The second life is the time when each examinee enjoys or suffers from the outcome of his behavior during the test period. In Islam, the line of life is clear, simple, and logical: the first life, death, the Day of Judgment, and then the second life. With this clear line of life, the Muslim has a clear purpose in life. The Muslim knows he is created by Allah. Muslims know they are going to spend some years in this first life, during which they have to obey God, because God will question them and hold them responsible for their public or private deeds, because Allah knows about all the deeds of all people. The Muslim knows that his deeds in the first life will determine the type of second life they will live in. The Muslim knows that this first life is a very short one, one hundred years, more or less, whereas the second life is an eternal one. The Eternity of the Second Life The concept of the eternity of the second life has a tremendous effect on a Muslims during their first life, because Muslims believe that their first life determines the shape of their second life. In addition, this determines the shape of their second life and this determination will be through the Judgment of Allah, the All just and Almighty. With this belief in the second life and the Day of Judgment, the Muslim's life becomes purposeful and meaningful. Moreover, the Muslim's standing purpose is to go to Paradise in the second life. In other words, the Muslim's permanent purpose is to obey Allah, to submit to Allah, to carry out His orders, and to keep in continues contact with Him through prayers (five times a day), through fasting (one month a year), through charity (as often as possible), and through pilgrimage (once in one's life). The Need for a Permanent Purpose Disbelievers have purposes in their lives such as collecting money and property, indulging in sex, eating, and dancing. But all these purposes are transient and passing ones. All these purposes come and go, go up and down. Money comes and goes. Health comes and goes. Sexual activities cannot continue forever. All these lusts for money, food and sex cannot answer the individual's questions: so what? Then What? However, Islam saves Muslims from the trouble of asking the question, because Islam makes it clear, from the very beginning, that the permanent purpose of the Muslim in this life is to obey Allah in order to go to Paradise in the second life. We should know that the only way for our salvation in this life and in the hereafter is to know our Lord who created us, believe in Him, and worship Him alone. We should also know our Prophet whom Allah had sent to all mankind, believe in Him and follow Him. We should, know the religion of truth which our Lord has commanded us to believe in, and practice it ? Those in search of truth Who have an open mind and heart, Islamic Education Foundation Welcome You. Objectives: - To Convey the message of Islam To Educate Muslims about Islam To keep in close contact with new Muslims. Activities: Offering Courses and presenting lectures about Islam in several languages. Teaching Islam and Arabic. Teaching new Muslims to receive the Holy Quran. Helping Non- Muslims embrace Islam and complete the required procedures From rafesacks at gmail.com Fri Aug 15 09:35:55 2008 From: rafesacks at gmail.com (Rafe) Date: Fri, 15 Aug 2008 06:35:55 -0700 (PDT) Subject: Passing an object through COM which acts like str but isn't Message-ID: Forgive me if I mangle any terminology here, but please correct me if I do... I have an object which acts exactly like a string as long as I stay in Python land. However, I am using the object in Softimage|XSI a 3D application on Windows. It was created while (briefly) owned by Microsoft, so knowledge of COM with excel or anything else should be applicable I should think. I should also say I am a COM novice and still learning Python (there are few that aren't learning though I suppose). Here is an example: class Name(object): def __init__(self, s): self.__data = s def __repr__(self): return repr(self.__data) def __cmp__(self, string): return cmp(self.__data, string) def __contains__(self, char): return char in self.__data __data = "Test" __doc = "Test" def __Set(self, value): self.__data = value def __Get(self): return self.__data data = property(fget = __Get, fset = __Set, fdel = None, doc = "string-like example") It also uses some new-style class Property From castironpi at gmail.com Sun Aug 24 16:36:22 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 24 Aug 2008 13:36:22 -0700 (PDT) Subject: In-place memory manager, mmap References: <1cf85075-17a1-4a1d-8ea5-bf5104541528@s50g2000hsb.googlegroups.com> Message-ID: On Aug 24, 12:19?pm, Kris Kennaway wrote: > castironpi wrote: > > On Aug 24, 9:52 am, Kris Kennaway wrote: > >> castironpi wrote: > >>> Hi, > >>> I've got an "in-place" memory manager that uses a disk-backed memory- > >>> mapped buffer. ?Among its possibilities are: storing variable-length > >>> strings and structures for persistence and interprocess communication > >>> with mmap. > >>> It allocates segments of a generic buffer by length and returns an > >>> offset to the reserved block, which can then be used with struct to > >>> pack values to store. ?The data structure is adapted from the GNU PAVL > >>> binary tree. > >>> Allocated blocks can be cast to ctypes.Structure instances using some > >>> monkey patching, which is optional. > >>> Want to open-source it. ?Any interest? > >> Just do it. ?That way users can come along later. > > >> Kris > > > How? ?My website? ?Google Code? ?Too small for source forge, I think. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Any of those 3 would work fine, but the last two are probably better > (sourceforge hosts plenty of tiny projects) if you don't want to have to > manage your server and related infrastructure yourself. > > Kris I decided on Google Code. The demo creates 'mappedtree.dat' at 3000 bytes, and allocates or frees memory blocks in it at random. There is a insert-stress test, and a concurrent read-write test too. Tested on WinXP with Python 2.5. Have a look. http://code.google.com/p/pymmapstruct/source/browse/trunk/allocbuf.py From pavlovevidence at gmail.com Wed Aug 6 07:03:29 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 6 Aug 2008 04:03:29 -0700 (PDT) Subject: Locking around References: <87ej547vqs.fsf@nokile.rath.org> <87y73aa3se.fsf@nokile.rath.org> <87sktia0uf.fsf@nokile.rath.org> Message-ID: <1836659a-99e9-4b51-953d-b5622c22fec5@k37g2000hsf.googlegroups.com> On Aug 6, 6:34?am, Nikolaus Rath wrote: > Nikolaus Rath writes: > >> This should work, at least the idea is not flawed. However, I'd say > >> there are too many locks involved. Rather, you just need a simple > >> flag and the global lock. Further, you need a condition/event that > >> tells waiting threads that you released some of the files so that it > >> should see again if the ones it wants are available. > > > I have to agree that this sounds like an easier implementation. I > > just have to think about how to do the signalling. Thanks a lot! > > Here's the code I use now. I think it's also significantly easier to > understand (cv is a threading.Condition() object and cv.locked_keys a > set()). > > ? ? def lock_s3key(s3key): > ? ? ? ? cv = self.s3_lock > > ? ? ? ? try: > ? ? ? ? ? ? # Lock set of locked s3 keys (global lock) > ? ? ? ? ? ? cv.acquire() > > ? ? ? ? ? ? # Wait for given s3 key becoming unused > ? ? ? ? ? ? while s3key in cv.locked_keys: > ? ? ? ? ? ? ? ? cv.wait() > > ? ? ? ? ? ? # Mark it as used (local lock) > ? ? ? ? ? ? cv.locked_keys.add(s3key) > ? ? ? ? finally: > ? ? ? ? ? ? # Release global lock > ? ? ? ? ? ? cv.release() > > ? ? def unlock_s3key(s3key): > ? ? ? ? cv = self.s3_lock > > ? ? ? ? try: > ? ? ? ? ? ? # Lock set of locked s3 keys (global lock) > ? ? ? ? ? ? cv.acquire() > > ? ? ? ? ? ? # Mark key as free (release local lock) > ? ? ? ? ? ? cv.locked_keys.remove(s3key) > > ? ? ? ? ? ? # Notify other threads > ? ? ? ? ? ? cv.notify() > > ? ? ? ? finally: > ? ? ? ? ? ? # Release global lock > ? ? ? ? ? ? cv.release() Freaky... I just posted nearly this exact solution. I have a couple comments. First, the call to acquire should come before the try block. If the acquire were to fail, you wouldn't want to release the lock on cleanup. Second, you need to change notify() to notifyAll(); notify alone won't cut it. Consider what happens if you have two threads waiting for keys A and B respectively. When the thread that has B is done, it releases B and calls notify, but notify happens to wake up the thread waiting on A. Thus the thread waiting on B is starved. Carl Banks From notifications at hallmark.com Tue Aug 19 19:05:40 2008 From: notifications at hallmark.com (hallmark.com) Date: Tue, 19 Aug 2008 18:05:40 -0500 (CDT) Subject: You've received A Hallmark E-Card! Message-ID: <20080819230540.826B295834B@crechemania.com> An HTML attachment was scrubbed... URL: From money.maker20096 at gmail.com Sat Aug 16 02:10:54 2008 From: money.maker20096 at gmail.com (money_maker) Date: Fri, 15 Aug 2008 23:10:54 -0700 (PDT) Subject: Google Adsense Program Is Like Finding Money In The Street. Message-ID: <37742f69-1f74-4cbe-94c1-c3bac9f0dadc@m44g2000hsc.googlegroups.com> Google Adsense Program Is Like Finding Money In The Street. http://money-maker2009.blogspot.com/2008/08/google-adsense-program-is-like-finding.html Hit Success Street With Google Adsense http://money-maker2009.blogspot.com/2008/08/hit-success-street-with-google-adsense.html The Google Adsense Program Is A Great Tool For Every Webmaster http://money-maker2009.blogspot.com/2008/08/google-adsense-program-is-great-tool.html Earn Money Running Ads http://money-maker2009.blogspot.com/2008/08/earn-money-running-ads.html Make Money With Adsense ? Who Say Novices Can?t Make Money Using Adsense http://money-maker2009.blogspot.com/2008/08/make-money-with-adsense-who-say-novices.html how And Where To Get Jobs At Home? http://money-maker2009.blogspot.com/2008/08/how-and-where-to-get-jobs-at-home.html How Do You Become A Successful Affiliate Marketer? http://money-maker2009.blogspot.com/2008/08/how-do-you-become-successful-affiliate.html 7 Ways You Can Make Money On-line http://money-maker2009.blogspot.com/2008/08/7-ways-you-can-make-money-on-line.html At Home Moms Jobs http://money-maker2009.blogspot.com/2008/08/2008-at-home-moms-jobs.html Why Do Most People Fail At Working From Home? http://money-maker2009.blogspot.com/2008/08/why-do-most-people-fail-at-working-from.html Work At Home Data Entry Job - Have Your Tried Looking Local? http://money-maker2009.blogspot.com/2008/08/work-at-home-data-entry-job-have-your.html Earn $500 To $1000 Daily Working From Home. http://money-maker2009.blogspot.com/2008/08/earn-500-to-1000-daily-working-from.html Can Money Be Made Online Or Is It Just A Waste Time And Money? http://money-maker2009.blogspot.com/2008/08/can-money-be-made-online-or-is-it-just.html Earn Money Online Securely http://money-maker2009.blogspot.com/2008/08/earn-money-online-securely.html Earn Your Income From An Internet Home Based Business http://money-maker2009.blogspot.com/2008/08/earn-your-income-from-internet-home.html How do I make money from home? http://money-maker2009.blogspot.com/2008/08/how-do-i-make-money-from-home.html Work From Home - Are There Really Good Jobs Available? http://money-maker2009.blogspot.com/2008/08/work-from-home-are-there-really-good.html Trading On The Forex Market With Forexautomoney http://money-maker2009.blogspot.com/2008/07/trading-on-forex-market-with.html Is It Really Necessary To Quit Your Day Job And To Start An Online Home Business http://money-maker2009.blogspot.com/2008/07/is-it-really-necessary-to-quit-your-day.html How Do You Research A Business Opportunity To Find If They Are Legitimate? http://money-maker2009.blogspot.com/2008/07/how-do-you-research-business.html Getting Your Sites Notice And Make Profit With Online Reviews http://money-maker2009.blogspot.com/2008/07/getting-your-sites-notice-and-make.html Stealth Money Maker - Insider's Review http://money-maker2009.blogspot.com/2008/07/stealth-money-maker-insiders-review.html The Best Online Money Maker Ever http://money-maker2009.blogspot.com/2008/07/best-online-money-maker-ever.html How To Trade Forex The Easy Way http://money-maker2009.blogspot.com/2008/07/how-to-trade-forex-easy-way.html Online Trading http://money-maker2009.blogspot.com/2008/07/online-trading.html Quick Ways To Make Money Online 3 http://money-maker2009.blogspot.com/2008/07/quick-ways-to-make-money-online-3.html Click Affiliate Review http://money-maker2009.blogspot.com/2008/07/1-click-affiliate-review.html forex rates, forex options, forex traders, fx forex, global forex, spot forex, forex pips, dollar forex, euro forex, forex pip, valuta forex, forex currencies, forex valutakurser, forex trade, forex exchange, forex se, fxcm forex, oanda forex, forex signals, forex broker, forex markets, forex chart, forex brokers, refco forex, cms forex, forex trader, realtime forex, forex quotes, forex futures, forex forecast, forex stock, forex platform, forex strategy, forex v? xla, forex rate, forex currency, forex analysis, managed forex, forex charting, daily forex, forex account, forex margin, usd forex, hedging forex, forex financial, us forex, forex foreign exchange, forex kurser, acm forex, gft forex, forex street, gci forex, forex directory, forex strategies, interbank forex, forex forecasts, forex signal, forex reuters, cfd forex, forex stocks, forex sek, dealing forex, real time forex, money forex, capital forex, fxstreet forex, trend forex, forex trades, forex com, automated forex, forex spread, forex pairs, forex foreign, forex accounts, forex currency converter, how to trade forex, foreign exchange, forex factory, forex made easy, forex converter, the forex, currency converter, forex exchange rates, forex exchange rate, forex demo, lkp forex, exchange rates, forex cargo, forex currency exchange, currency exchange, easy forex com, global forex trading, forex club, forex technical analysis, forex trading signals, forex arbitrage, exchange rate, forex books, nz forex, forex brokerage, day forex, forex bank, forex blog, forex day trading, www easy forex, v?xla pengar, forex risk, forex demo account, forex managed account, forex trading online, forex review, premiere trade forex, forex uk, forex book, forex company, gold forex, le forex, city forex, forex api, forex indonesia, day trading, forex enterprises, automated forex trading, forex trading hours, scalping forex, live forex rates, forex managed accounts, ???????? forex, forex glossary, forex download, forex prices, forex scams, forex jobs, singapore forex, easy forex co il, peter bain forex, live forex charts, ????? forex, forex definition, forex commentary, northsea forex, forex danmark, forex risk management, forex trading signal, technical analysis, what is forex trading, forex trading tips, forex video, www forex fi, forex stock market, foreign currency, forex technical, forex articles, private forex, live forex quotes, fibo forex, ifx forex, forex sverige, tokyo forex, forex in india, canada forex, forex brokerage firm, real forex, london forex, australian forex, forex reserves india, pannelli forex, forex data feed, pvc forex, north sea forex, premier forex, forex net, forex card, world forex, gain forex, forex ro, forex spreads, forex betting, forex sa, forex outlook, forex on line, icici forex, mt4 forex, forex simulation, forex g?teborg, forex, concorde forex group, forex brasil, rand forex, asp forex, forex material, atic forex, forex market trading, efx forex, forex sweden, forex ?????, forex advice, forex system trading, forex software, broker forex, currency forex trading, forex seminar, forex online trading, beat forex from high identify in market odds pattern percentage profit trading trading wiley, chart forex, forex news, forex learn, forex training, broker broker.drivensuccess.com forex, course forex trading, forex strategy trading, education forex trading, day forex trading, forex software trading, forex online, exchange forex, forex profiting, day forex tactic technique thirty trade trading trading wiley, com forex, account forex managed, forex mini trading, easy forex made, forex system, forex learn trading, easy forex, candlestick cd forex future market pivot point rom setup stock trading trigger, currency forex system trading, forex maniac, forex managed, currency forex online trading, broker forex online, chart forex free, factory forex, forex forum, 6 dollar easy forex made trade ways, forex platform trading, day forex system trading, forex signal trading, forecast forex, forex premier trade, best forex kept maximum off profit secret street trading wall, forex spot, brain forex in left mindset right success technique trading, broker forex trading, currency forex, demo forex, forex global trading, forex online system trading, currency forex learn online trading, forex option, education forex, account demo forex, course course course.com forex forex forex master trading training, forex quote, forex trading training, account forex trading, course course course course.com forex forex forex forex master trading trading training, forex global, book forex, chart forex live, forex future trading, forex learn trade, currency day forex trading, forex free signal, course forex, capital forex market, forex real time, cargo forex, course course course.com forex forex forex master trading trading training, forex hedging, course course course.com forex forex forex master trading trading, data forex, forex managed trading, best broker forex, forex information, enterprise forex, forex premiere trade, forex online software trading, charting forex, forex spot trading, d Why read online stock-trading articles? http://money-maker2009.blogspot.com/2008/07/why-read-online-stock-trading-articles.html HOW TO START AND OPERATE YOUR OWN PROFITABLE IMPORT/EXPORT BUSINESS AT HOME http://money-maker2009.blogspot.com/2008/07/how-to-start-and-operate-your-own.html How To Trade Forex The Easy Way http://money-maker2009.blogspot.com/2008/07/how-to-trade-forex-easy-way.html Mini Forex Trading Golden Tips And Advice http://money-maker2009.blogspot.com/2008/07/mini-forex-trading-golden-tips-and.html Simple Forex Trading System For Faster Forex Profits http://money-maker2009.blogspot.com/2008/07/simple-forex-trading-system-for-faster.html Forex Cash Cow Strategies http://money-maker2009.blogspot.com/2008/07/forex-cash-cow-strategies.html Forex Strategies - How To Develop A System To Win http://money-maker2009.blogspot.com/2008/07/forex-strategies-how-to-develop-system.html From cvrebert+clp at gmail.com Fri Aug 29 14:48:25 2008 From: cvrebert+clp at gmail.com (Chris Rebert) Date: Fri, 29 Aug 2008 11:48:25 -0700 Subject: Using class-attribute as key to sort? In-Reply-To: <712b9e5d-9127-4213-8478-8cf49349068e@a1g2000hsb.googlegroups.com> References: <712b9e5d-9127-4213-8478-8cf49349068e@a1g2000hsb.googlegroups.com> Message-ID: <47c890dc0808291148p10f347b8pe299d22e110c0f76@mail.gmail.com> Just use the "key" argument to list.sort; e.g. class Foo(object): def __init__(self, x): self.x = x def __repr__(self): return "Foo:"+str(self.x) foos = [Foo(75), Foo(10), Foo(-1)] foos.sort(key = lambda foo: foo.x) print foos #=> [Foo:-1, Foo:10, Foo:75] - Chris ======== Follow the path of the Iguana... http://rebertia.com On Fri, Aug 29, 2008 at 11:22 AM, cnb wrote: > In median grade, can I sort on Review-grade somehow? > something like: > sr = self.reviews.sort(key=self.reviews.instance.grade) > > class Review(object): > def __init__(self, movieId, grade, date): > self.movieId = movieId > self.grade = grade > self.date = date > > class Customer(object): > def __init__(self, idnumber, review): > self.idnumber = idnumber > self.reviews = [review] > > def addReview(self, review): > self.reviews.append(review) > > def averageGrade(self): > tot = 0 > for review in self.reviews: > tot += review.grade > return tot / len(self.reviews) > > #general sort that takes list+spec of objectkey to sort on? > def sortReviews(self): > def qsort(lista): > if len(lista) != 0: > return qsort([x for x in lista[1:] if x.grade < > lista[0].grade]) + [lista[0]] + \ > qsort([x for x in lista[1:] if x.grade >= > lista[0].grade]) > else: > return [] > return qsort(self.reviews) > > def medianGrade(self): > length = len(self.reviews) > sr = self.sortReviews() > #sr = self.reviews.sort(key=self.reviews.instance.grade) > if length % 2 == 0: > return (sr[int(length/2)].grade + sr[int(length/ > 2-1)].grade) / 2 > else: > if length == 1: > return sr[0].grade > else: > return sr[int(round(length/2)-1)].grade > -- > http://mail.python.org/mailman/listinfo/python-list > From marco.bizzarri at gmail.com Sat Aug 30 13:37:16 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 30 Aug 2008 19:37:16 +0200 Subject: Writing to ms excel In-Reply-To: References: Message-ID: <3f0d61c40808301037x22eaa45fic5e7b94bf924a65f@mail.gmail.com> On Sat, Aug 30, 2008 at 4:41 PM, Marin Brkic wrote: > Hello all, > > > I'm trying to find a way to write data to excel cells (or to be more > specific to an .xls file), let's say for the sake of argument, data > readen from a file (although it will be calculated in the process). > I've been searching, but couldn't find any examples which allows that. Is it suitable for you to use a python program talking with a running instance of openoffice? in that case, pyuno could help you. -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From sjmachin at lexicon.net Mon Aug 4 18:46:40 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 4 Aug 2008 15:46:40 -0700 (PDT) Subject: xlrd References: Message-ID: <0347252b-95ed-451f-84ad-1a115c8a7236@b30g2000prf.googlegroups.com> On Aug 4, 11:08 pm, Edwin.Mad... at VerizonWireless.com wrote: > here is working code that will read & display contents of all rows & columns in all the sheets, you need xlrd 0.6.1 > > import xlrd, os, sys > > book = xlrd.open_workbook(sys.argv[1]) > print "The number of worksheets is", book.nsheets > for shx in range(book.nsheets): > sh = book.sheet_by_index(shx) > print 'tab:%s rows:%s cols:%s ' % (sh.name, sh.nrows, sh.ncols) > for rx in range(sh.nrows): > for cx in range(sh.ncols): > try: > if sh.row_types(rx)[cx] and sh.row_values(rx)[cx]: Having "and sh.row_values(rx)[cx]" means that it does not "display contents of all rows & columns in all the sheets"; it omits cells which contain 0., "", or FALSE. Consider getting the row_types and the row_values once per row instead of once per cell. > print '%4s %s' % (xlrd.cellname(rx, cx), sh.row_values(rx)[cx]) If the contents of the cell are a date or an error code, the display will be rather meaningless. > except: > print xlrd.cellname(rx, cx), 'Exception - could not read' I'm having difficulty imagining what could go wrong in your try block, apart from an IndexError (but you are not addressing cells outside the arena). If something does go wrong, it would be rather drastic, and very nice to know exactly what the problem is. As well as printing the cellname, you should get sys.exc_info()[:2] and print the exception details. But for unexpected exceptions, I'd prefer to print the "where am I" info and just re-raise the exception, instead of trying to continue. > print You can use the supplied script runxlrd.py to get similar information e.g. on Windows assuming default setup: prompt>c:\python25\scripts\runxlrd.py show yourfile.xls For help on displaying dates and error codes, see the get_row_data function in runxlrd.py, and read the documentation on the Cell class. Cheers, John From fredrik at pythonware.com Wed Aug 13 09:55:36 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Aug 2008 15:55:36 +0200 Subject: Perl to Python using MqSQLdb In-Reply-To: <20080813110520.GD87062@nexus.in-nomine.org> References: <20080813110520.GD87062@nexus.in-nomine.org> Message-ID: Jeroen Ruigrok van der Werven wrote: >> cursor=db.cursor() >> cursor.execute(sql) >> while (1): >> row = cursor.fetchone() >> if row == None: >> break >> combined = ', '.join(row) > > Why not something like: > > for row in cursor.fetchall(): > combined = ', '.join(row) which can be written as combined = ', '.join(cursor.fetchall()) but probably won't work, since fetchall() returns a sequence of tuples, unless I'm mistaken. Try something like this instead: combined = ', '.join(row[0] for row in cursor.fetchall()) From skip at pobox.com Wed Aug 27 06:11:56 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 27 Aug 2008 05:11:56 -0500 Subject: use of Queue In-Reply-To: <6hkmncFmeh9gU1@mid.uni-berlin.de> References: <6hkmncFmeh9gU1@mid.uni-berlin.de> Message-ID: <18613.10348.610110.440906@montanaro-dyndns-org.local> Diez> Put a sentinel into the queue that gets interpreted as "terminate" Diez> for the workers. You need of course to put it in there once for Diez> each worker. Or make the consumers daemon threads so that when the producers are finished an all non-daemon threads exit, the consumers do as well. Skip From straton at lampsacos.demon.co.uk Mon Aug 25 15:09:36 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Mon, 25 Aug 2008 20:09:36 +0100 Subject: Private attribute In-Reply-To: References: Message-ID: Ken Starks wrote: > I have a class with an attribute called 'gridsize' and I want > a derived class to force and keep it at 0.8 (representing 8mm). > > Is this a correct, or the most pythonic approach? > > #################### > > def __getattr__(self,attrname): > if attrname == 'gridsize': > return 0.8 > > def __setattr__(self,attrname,value): > if attrname == 'gridsize': > pass > else: > self.__dict__[attrname]=value > > ##################### > > > Cheers, > Ken. Perhaps I should mention the alternative I had in mind: ################### class xyz: def __init__(self): self.__dict__['a'] = 123 self.b=456 def __setattr__(self,attrname,value): if attrname == 'a': pass else: self.__dict__[attrname]=value # __getattr__() not redefined. ############################ From fredrik at pythonware.com Wed Aug 27 05:56:47 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 27 Aug 2008 11:56:47 +0200 Subject: atomic increment In-Reply-To: <63533495-5cca-4430-9c9d-fbe1cfee0e1e@s50g2000hsb.googlegroups.com> References: <6297cf93-5eec-4bf3-9104-0605a82f7186@p10g2000prf.googlegroups.com> <6hinduFmfmsrU1@mid.uni-berlin.de> <63533495-5cca-4430-9c9d-fbe1cfee0e1e@s50g2000hsb.googlegroups.com> Message-ID: Frank Millman wrote: > Just out of interest, would the following, without a lock, be safe? > > old, atomic_int = atomic_int, atomic_int+1 nope. there's some information here (make sure you read the comments): http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm and some additional discussion here: http://mail.python.org/pipermail/python-dev/2006-November/thread.html#69981 From aahz at pythoncraft.com Wed Aug 13 21:47:02 2008 From: aahz at pythoncraft.com (Aahz) Date: 13 Aug 2008 18:47:02 -0700 Subject: Upgrading to DB-API (was Re: Corrupted images ...) References: <73674d9f-891b-4acb-8a01-a20232ecf8ce@34g2000hsh.googlegroups.com> Message-ID: In article , Fredrik Lundh wrote: > >Ouch. Please use parameters instead of explicit escapes and string >formatting; Python's not PHP. How would you recommend upgrading an application that is more than ten years old and contains something like 100K lines of code? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From mensanator at aol.com Sat Aug 9 18:38:57 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 9 Aug 2008 15:38:57 -0700 (PDT) Subject: How to round a floating point to nearest 10? References: <13cc5423-4437-4359-a4d1-35d727045358@v13g2000pro.googlegroups.com> Message-ID: <14052b1f-8077-4ccc-8c97-7d065bffa8db@56g2000hsm.googlegroups.com> On Aug 9, 4:54?pm, John Machin wrote: > On Aug 10, 1:19 am, Mensanator wrote: > > > On Aug 9, 6:31 am, Will Rocisky wrote: > > > > I want my 76.1 to be rounded to decimal 80 and 74.9 to decimal 70. > > > How can I achieve that? > > >>> print '%.0e' % 74.9 > > 7e+01 > > >>> print '%.0e' % 76.1 > > > 8e+01 > > But:>>> print '%.0e' % 176.1 > > 2e+002 Which would be correct if your goal was to restrain to 1 significant digit. > > Giving the Subject ("How to round a floating point to nearest 10?"), > there's a strong presumption that the OP would want the answer to be > 180, not 200. Well, I can't read the OP's mind and the cases I HAVE encountered are concerned about the number of significant digits. When laboratories report 3 digits, all my manipulations (ppm conversion, dividing non-detect reporting limits by 2, comparison to TACO, etc. are required to also have exactly 3 digits of significance). >>> print '%.2e' % 0.00000123456 1.23e-006 >>> print '%.2e' % 123456 1.23e+005 >>> print '%.2e' % 0.123000456 1.23e-001 It all depends on what the OP actually wants. He's free to ignore my example. From paul at boddie.org.uk Sat Aug 30 14:17:23 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 30 Aug 2008 11:17:23 -0700 (PDT) Subject: Counting Elements in an xml file References: <7dd68868-5490-464d-9cc1-ddf6a2c50dbe@l42g2000hsc.googlegroups.com> Message-ID: <56fb275e-7f2a-45fa-aa2f-a1111638bebe@m36g2000hse.googlegroups.com> On 30 Aug, 19:37, Ouray Viney wrote: > > > > I would like to be able to count the number of TestCases that contain > the "execute=true" but not the ones that contain "execute=false". With XPath-capable libraries, it should be enough to execute an XPath query on the document. For example: import libxml2dom d = libxml2dom.parse(filename) number_of_cases = d.xpath("count(//Testcase[@execute='true'])") This applies the XPath count function to all Testcase elements in the document having an execute attribute with a value of 'true', thus returning the number of matching elements. Paul From drakonik at gmail.com Sun Aug 3 08:44:55 2008 From: drakonik at gmail.com (Nick Dumas) Date: Sun, 03 Aug 2008 08:44:55 -0400 Subject: proposal, change self. to . In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 It's also worth noting that you can use a different name for the object that represents your class. If you did def __init__(foo):pass, then you would be able to access the class's objects with foo.objectname. Using self is simply the recommended standard. Heiko Wundram wrote: > Am 03.08.2008, 12:51 Uhr, schrieb Equand : >> how about changing the precious self. to . >> imagine >> >> self.update() >> >> .update() >> >> simple right? > > What about: > > class x: > > def x(self,ob): > ob.doSomethingWith(self) > > ? Not so simple anymore, isn't it? If you're not trolling, there's > hundreds of reasons why the explicit self is as it is, and it's not going > to go away, just as a thread that produced immense amounts of response > demonstrated around a week ago. Read that, and rethink. > > --- Heiko. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkiVqEcACgkQLMI5fndAv9j8KgCgmS2e+bTOT+sUPLYhtHBOVlyq kxwAn028YSOGYGB4RyHZxYq6n4+tsSd+ =vH9d -----END PGP SIGNATURE----- From CRhode at LacusVeris.com Mon Aug 18 10:19:24 2008 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Mon, 18 Aug 2008 09:19:24 -0500 Subject: Good python equivalent to C goto References: <48a744b6$0$299$7a628cd7@news.club-internet.fr> Message-ID: On Sun, 17 Aug 2008 09:08:35 -0500, Grant Edwards wrote: > In Python one uses try/raise/except. At the risk of introducing an anachronism and in deference to Mr. "ElementTree" Lundh, I now invoke Godwin's Law (1990): Isn't *try/except* kinda sorta like the musty, old *come from* construct proposed for *fortran*? Here there be typos (abject apologies): o Clark, R. Lawrence. "A Linguistic Contribution to GOTO-less Programming." _Datamation_ Dec. 1973. 18 Aug. 2008 . -- .. Be Seeing You, .. Chuck Rhode, Sheboygan, WI, USA .. Weather: http://LacusVeris.com/WX .. 71? ? Wind W 9 mph From fabiofz at gmail.com Wed Aug 13 09:01:35 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 13 Aug 2008 10:01:35 -0300 Subject: Looking out a module for Subversion In-Reply-To: References: <48A14FB6.4020009@sellerengine.com> <27cbc0fa0808120250t5d41af68u1d72b66f46ad0995@mail.gmail.com> Message-ID: > > I've installed Ulipad and must say it is a small nice tool. Thanks > I also want to give eclipse a try. I referred eclispe web site for this and > it does not mention what basic things need installation before you use the > Dynamic Language Toolkit. So, my question is : what combination of > packages are required for using eclipse as an IDE for python? > > Download eclipse 3.3 from http://download.eclipse.org/eclipse/downloads/drops/R-3.3.2-200802211800/index.php(you can download only the "Platform Runtime Binary" in that link) and then follow the instructions to install Pydev at http://fabioz.com/pydev/manual_101_install.html Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Sun Aug 31 15:20:19 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 31 Aug 2008 15:20:19 -0400 Subject: (in memory) database In-Reply-To: Message-ID: <20080831192019.29191.788708876.divmod.quotient.20148@ohm> On Sun, 31 Aug 2008 18:05:08 +0000, Cameron Laird wrote: >In article , >Paul Boddie wrote: > [snip] > >Thanks for pursuing this, Paul. You have me curious now. > >Let's take a definite example: I have a convenient > Ubuntu 8.04.1 >The content of /etc/apt/sources.list is > deb http://us.archive.ubuntu.com/ubuntu hardy main restricted > deb http://us.archive.ubuntu.com/ubuntu hardy-updates main restricted > deb http://us.archive.ubuntu.com/ubuntu hardy universe multiverse > deb http://security.ubuntu.com/ubuntu hardy-security main restricted >I do > apt-get update > apt-get upgrade > apt-get install python2.5 >then > # python2.5 > Python 2.5 (r25:51908, Dec 11 2006, 21:09:56) > [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. It doesn't seem likely to me that this is the Python 2.5 packaged in Ubuntu 8.04. It's build timestamp is almost a year and a half before 8.04 was released. Here's the header on my installation: Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. This could be a bug in the upgrade from a previous version of Ubuntu installed on the host or perhaps you have a different Python 2.5 installed on the machine that's not from the Ubuntu package repository? Jean-Paul From rasheethkhn at gmail.com Tue Aug 12 07:46:51 2008 From: rasheethkhn at gmail.com (priya) Date: Tue, 12 Aug 2008 04:46:51 -0700 (PDT) Subject: EARN MONEY $1000-25000 PER MONTH TAKE Message-ID: <463d457a-1417-46bb-a740-40661000f67a@b2g2000prf.googlegroups.com> EARN MONEY $1000-25000 PER MONTH TAKE SIMPLE ONLINE SURVEYS CREATE FREE ACCOUNT OTHER DETAILS LOG ON TO *************************************************** http://romanticmoviess.com/ *************************************************** From metaperl at gmail.com Thu Aug 28 15:23:10 2008 From: metaperl at gmail.com (Terrence Brannon) Date: Thu, 28 Aug 2008 12:23:10 -0700 (PDT) Subject: re.compile versus r'' Message-ID: <0bf4b8de-e11e-451c-8d18-58c1a4138375@e53g2000hsa.googlegroups.com> Hello, I'm using a tool (PLY) which apparently expects the tokens to be created using r'' But because one token is a rather complex regular expression, I want to create the regular expression programmatically. How can I generate a string and then create something of the same type that the r'' function does? Concretely, in the program below, consonant is not the same type as t_NAME, but I assume that it needs to be for PLY to use it for tokenizing: import re t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*' guttural = 'kh?|gh?|\"n' palatal = '(?:chh?|jh?|\~n)' cerebral = '\.(?:th?|dh?|n)' dental = '(?:th?|dh?|n)' semivowel = '[yrlv]' sibilant = '[\"\.]?s' aspirant = 'h' consonant = re.compile('|'.join([guttural , palatal , cerebral , dental , semivowel , sibilant , aspirant])) print consonant print t_NAME From steve at REMOVE-THIS-cybersource.com.au Fri Aug 22 21:36:51 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 23 Aug 2008 01:36:51 GMT Subject: Early halt for iterating a_list and iter(a_list) References: <4cf5a96d-c70c-487d-82e3-1d5a1288ab86@n33g2000pri.googlegroups.com> Message-ID: <00bf6479$0$20312$c3e8da3@news.astraweb.com> On Fri, 22 Aug 2008 07:23:18 -0700, Lie wrote: [...] >> iterators are once-only objects. ?there's nothing left in "c" when you >> enter the inner loop the second time, so nothing is printed. >> >> > Ah, now I see. You have to "restart" the iterator if you want to use it > the second time (is it possible to do that?). In general, no, iterators can't be restarted. Think of it as squeezing toothpaste out of a tube. You can't generally reverse the process. [...] > I see, but if/when a function expects a sequence but then fed with an > iterator, it would be against duck-typing to check whether something is > a sequence or an iterator, but iterator is good for one iteration only > while sequence is good for multiple usage. So is there a clean way to > handle this? (i.e. a design pattern that allows sequence and iterator to > be treated with the same code) The only clean way to treat iterators and sequences identically is to limit yourself to behaviour that both use. That pretty much means a simple for loop: for item in iterator_or_sequence: do_something(item) Fortunately that's an incredibly useful pattern. I often find myself converting sequences to iterators, so I can handle both types identically: def treat_first_item_specially(iterator_or_sequence): it = iter(iterator_or_sequence) try: first_item(it.next) except StopIteration: pass else: for item in it: other_items(item) > If there is no such design pattern for that problem, should one be > available? I'm thinking of one: "all iterables would have > iterable.restart() method, which is defined as 'restarting the iterator > for iterator' or 'do nothing for sequences'." But not all iterators can be restarted. Here's a contrived example: def once_only_iterator(directory): """Return the name of files being deleted.""" for filename in os.list(directory): yield filename os.remove(filename) You can't restart that one, at least not with a *lot* of effort. In general, the only ways to restart an arbitrary iterator are: (1) make a copy of everything the iterator returns, then iterate over the copy; or (2) exploit idiosyncratic knowledge about the specific iterator in question. That in turn may mean: find the non-iterator data that your iterator uses, and use it again. e.g. data = {'a': 1, 'b': 2, 'c': 4, 'd': 8} def make_iterator(data): items = sorted(data.items()) for item in items: yield item it = make_iterator(data) for i in it: print i # Restart the iterator. it = make_iterator(data) That's not exactly what you were hoping for, but in the generic case of arbitrary iterators, that's the best you're going to get. Another example of exploiting specific knowledge about the iterator is that, starting from Python 2.5, generators become co-routines that can accept information as well as yield it. I suggest you read this: http://docs.python.org/whatsnew/pep-342.html but note carefully that you can't just call send() on any arbitrary iterator and expect it to do something sensible. Lastly, you can write your own iterator, and give it it's own restart() method. I recommend the exercise. Once you see how much specific knowledge of the iterator is required, you may understand why there can't possibly be a generic restart() method that works on arbitrary iterators. [...] > Wait a minute... I've got an idea, we could use itertools.tee to copy > the iterator and iterating on the copy, like this right?: > > for a_ in a: > b, b_copy = itertools.tee(b) > for b_ in b_copy: > c, c_copy = itertools.tee(c) > for c_ in c_copy: > print a_, b_, c_ > > That works with both "requirement": able to handle sequence and iterator > with the same code and the code for common cases where iterators are > used once only wouldn't need to be changed. Personally though, I don't > think it's a clean solution, looks a bit of hackery. itertools.tee() works by keeping a copy of the iterator's return values. If your iterator is so huge you can't make a copy of its data, then tee() will fail. -- Steven From george.sakkis at gmail.com Fri Aug 29 13:25:49 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 29 Aug 2008 10:25:49 -0700 (PDT) Subject: How to check is something is a list or a dictionary or a string? References: Message-ID: <68e5ea6d-08fd-4f7c-9780-df5d1fabfded@p25g2000hsf.googlegroups.com> On Aug 29, 12:16 pm, dudeja.ra... at gmail.com wrote: > Hi, > > How to check if something is a list or a dictionary or just a string? > Eg: > > for item in self.__libVerDict.itervalues(): > self.cbAnalysisLibVersion(END, item) > > where __libVerDict is a dictionary that holds values as strings or > lists. So now, when I iterate this dictionary I want to check whether > the item is a list or just a string? if isinstance(item,basestring): # it's a string ... else: # it should be a list # typically you don't have to check it explicitly; # even if it's not a list, it will raise an exception later anyway if you call a list-specific method HTH, George From ckumwaka at googlemail.com Thu Aug 14 01:27:43 2008 From: ckumwaka at googlemail.com (Cyprian Kumwaka) Date: Thu, 14 Aug 2008 08:27:43 +0300 Subject: Installing gasp Message-ID: <1ee11ba30808132227i11a6e20dqeb9f0cb1a8b3bbfa@mail.gmail.com> Find attached a screen capture of the message I get. Thanks.. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: gasp_error.GIF Type: image/gif Size: 10857 bytes Desc: not available URL: From zondo42 at googlemail.com Fri Aug 29 15:12:09 2008 From: zondo42 at googlemail.com (Glenn Hutchings) Date: Fri, 29 Aug 2008 20:12:09 +0100 Subject: Process "Killed" References: <48a554c6-eeb3-4605-bdf2-a4b7de17bca3@b1g2000hsg.googlegroups.com> Message-ID: dieter writes: > I'm doing some simple file manipulation work and the process gets > "Killed" everytime I run it. No traceback, no segfault... just the > word "Killed" in the bash shell and the process ends. The first few > batch runs would only succeed with one or two files being processed > (out of 60) before the process was "Killed". Now it makes no > successful progress at all. Just a little processing then "Killed". > > Any Ideas? Is there a buffer limitation? Do you think it could be the > filesystem? > Any suggestions appreciated.... Thanks. > > The code I'm running: > ================== > > from glob import glob > > def manipFiles(): > filePathList = glob('/data/ascii/*.dat') > for filePath in filePathList: > f = open(filePath, 'r') > lines = f.readlines()[2:] > f.close() > f = open(filePath, 'w') > f.writelines(lines) > f.close() > print file Have you checked memory usage while your program is running? Your lines = f.readlines()[2:] statement will need almost twice the memory of your largest file. This might be a problem, depending on your RAM and what else is running at the same time. If you want to reduce memory usage to almost zero, try reading lines from the file and writing all but the first two to a temporary file, then renaming the temp file to the original: import os infile = open(filePath, 'r') outfile = open(filePath + '.bak', 'w') for num, line in enumerate(infile): if num >= 2: outfile.write(line) infile.close() outfile.close() os.rename(filePath + '.bak', filePath) Glenn From alan.franzoni.xyz at gmail.com Sat Aug 30 21:04:48 2008 From: alan.franzoni.xyz at gmail.com (Alan Franzoni) Date: Sun, 31 Aug 2008 01:04:48 GMT Subject: starting gazpacho on windows References: <48b95d18$0$7014$426a34cc@news.free.fr> Message-ID: <1r9si1lttzo47.1i5snd6ismpdr$.dlg@40tude.net> nntpman68 was kind enough to say: [cut] I didn't check, but if c:\python25 is your python install dir, you'll very likely find it in c:\python2.5\bin or c:\python25\scripts. -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From ironfroggy at gmail.com Wed Aug 13 11:38:11 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Wed, 13 Aug 2008 11:38:11 -0400 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: <74583B8642AB8841B30447520659FCA92CC054B5@dnce01.ent.ti.com> References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> <76fd5acf0808120651u259e5d8dt32a8d49bb5d77add@mail.gmail.com> <200808122240.22517.maric@aristote.info> <76fd5acf0808121415h41cc580bj85d96e648c54ab4b@mail.gmail.com> <74583B8642AB8841B30447520659FCA92CC054B5@dnce01.ent.ti.com> Message-ID: <76fd5acf0808130838h6a2723a4me6cdfc42a89ca45a@mail.gmail.com> On Wed, Aug 13, 2008 at 11:32 AM, Cousson, Benoit wrote: >> Defining it as a nested class saves you one line >> of code, but IMHO makes the result just a bit more cluttered, while >> reducing the elegance of reusing the metaclass. > > The whole point of nested class is to avoid polluting the namespace with classes that are only used locally. So the argument about the elegance of reusing is not very valid in that case. There is no point of nested classes because nested classes _are not_ supported by python. They are simply an artifact of not actively denying the syntax non-globally. I would fully support a change to the language to actively forbid a class definition that is not module-level. > I agree that they are other ways using module to avoid namespace pollution, but in some case it is easier to use nested class instead and keep everything in the same file. I don't consider it pollution. If you want it considered "private" to the module, name it with an underscore. > In my case, I'm trying to use a similar approach as XIST's one, meaning using Python class to model hierarchical data. So clearly nested class is a very nice and easy understandable way to do that. I don't find that this is clear in anyway. I can't imagine why you'd think a nested class is even useful here, rather than an instance with some understandable attributes. I've seen a lot of places nested classes are used and not one of them that should be been doing it. But, on that note, there is a point where a discussion is obviously not going to resolve with either side changing their minds. This is obviously such a case. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy From joshbloom at gmail.com Tue Aug 12 19:04:54 2008 From: joshbloom at gmail.com (Josh Bloom) Date: Tue, 12 Aug 2008 16:04:54 -0700 Subject: Python + Some sort of Propel + Creole In-Reply-To: <65c3648d0808121518l76cb70e4i98587c0762e75bde@mail.gmail.com> References: <65c3648d0808121518l76cb70e4i98587c0762e75bde@mail.gmail.com> Message-ID: http://sqlobject.org/ http://www.sqlalchemy.org/ Django's built in ORM is also quite good for web development tasks. -josh On Tue, Aug 12, 2008 at 3:18 PM, Samuel Morhaim wrote: > Hi, I come from an extensive background developing webapps with Symfony... > Symfony uses Propel/Creole a lot. > > Is there something similar to Propel/Creole for Python? > > I found a few DB abstraction layers (Creole) but I am not sure which one is > the best.. can somebody point me to a good one? Also can somebody point me > to a good > object relational mapper? (Like Doctrine or Propel for php.. ? ) > > I am really just interested in: > -Being able to talk to sqlite, mysql and mssql. > -Being able to easily create DB schemas (Like done with propel in which you > use a YAML or XML file to specify a schema) > > > Thanks. > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cgrebeld at gmail.com Mon Aug 25 17:00:25 2008 From: cgrebeld at gmail.com (chris) Date: Mon, 25 Aug 2008 14:00:25 -0700 (PDT) Subject: How to get PyTypeObject from PyObject? Message-ID: <11602cd4-f5ff-42f1-b3de-ff1afdc0c91f@j1g2000prb.googlegroups.com> I want to check the type of an object, right now I am doing strcmp( object->ob_type->tp_name, "MyClass") Which seems slow, is there a way I can find the pointer to the global PyTypeObject for MyClass, and then just call PyObject_TypeCheck? Thanks From cvrebert+clp at gmail.com Thu Aug 28 15:32:03 2008 From: cvrebert+clp at gmail.com (Chris Rebert) Date: Thu, 28 Aug 2008 12:32:03 -0700 Subject: re.compile versus r'' In-Reply-To: <0bf4b8de-e11e-451c-8d18-58c1a4138375@e53g2000hsa.googlegroups.com> References: <0bf4b8de-e11e-451c-8d18-58c1a4138375@e53g2000hsa.googlegroups.com> Message-ID: <47c890dc0808281232q1bede29coc8733a0775e14681@mail.gmail.com> On Thu, Aug 28, 2008 at 12:23 PM, Terrence Brannon wrote: > Hello, I'm using a tool (PLY) which apparently expects the tokens to > be created using r'' > > But because one token is a rather complex regular expression, I want > to create the regular expression programmatically. > > How can I generate a string and then create something of the same type > that the r'' function does? The "r" prefix isn't a function or a type, it's merely a special literal syntax for strings that's handy when you're writing regexes and therefore have to deal with another level of backslash escaping. See the second to last paragraph of http://docs.python.org/ref/strings.html for more info. Regards, Chris > > Concretely, in the program below, consonant is not the same type as > t_NAME, but I assume that it needs to be for PLY to use it for > tokenizing: > > import re > > t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*' > > guttural = 'kh?|gh?|\"n' > palatal = '(?:chh?|jh?|\~n)' > cerebral = '\.(?:th?|dh?|n)' > dental = '(?:th?|dh?|n)' > semivowel = '[yrlv]' > sibilant = '[\"\.]?s' > aspirant = 'h' > > consonant = re.compile('|'.join([guttural , palatal , cerebral , > dental , semivowel , sibilant , aspirant])) > > print consonant > print t_NAME > -- > http://mail.python.org/mailman/listinfo/python-list > From atulskulkarni at gmail.com Fri Aug 8 06:56:24 2008 From: atulskulkarni at gmail.com (Atul.) Date: Fri, 8 Aug 2008 03:56:24 -0700 (PDT) Subject: regular expressions. Message-ID: <23cd7bec-264e-4a1d-a285-4683b48bf99d@a21g2000prf.googlegroups.com> Hey All, I have been playing around with REs and could not get the following code to run. import re vowel = r'[aeiou]' re.findall(vowel, r"vowel") anything wrong I have done? Regards, Atul. From twic at urchin.earth.li Thu Aug 14 12:09:26 2008 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 14 Aug 2008 17:09:26 +0100 Subject: strptime and timezones In-Reply-To: References: Message-ID: On Wed, 13 Aug 2008, Christian Heimes wrote: > Tom Anderson wrote: > >> Secondly, do you really have to do this just to parse a date with a >> timezone? If so, that's ridiculous. > > No, you don't. :) Download the pytz package from the Python package > index. It's *the* tool for timezone handling in Python. The time zone > definition are not part of the Python standard library because they > change every few of months. Stupid politicians ... My problem has absolutely nothing to do with timezone definitions. In fact, it involves less timezone knowledge than the time package supplies! The wonderful thing about RFC 1123 timestamps is that they give the numeric value of their timezone, so you don't have to decode a symbolic one or anything like that. Knowing about timezones thus isn't necessary. The problem is simply that the standard time package doesn't think that way, and always assumes that a time is in your local timezone. That said, it does look like pytz might be able to parse RFC 1123 dates. Ill check it out. tom -- Come on thunder; come on thunder. From paul.hankin at gmail.com Sat Aug 2 16:46:23 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 2 Aug 2008 13:46:23 -0700 (PDT) Subject: why goes the time change after import statement ? References: <011a92b4-b911-4f63-9339-be46b48d5f76@v1g2000pra.googlegroups.com> Message-ID: <6ae5acd5-3d5d-4e81-af2f-a32a9c833122@y38g2000hsy.googlegroups.com> On Aug 2, 10:35?pm, binaryjesus wrote: > hi i am working on a S3 project and facing a really weird problem! > take a look at the following import statements and the time output > > >>> import time > >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) > > 'Sat, 02 Aug 2008 20:21:56 GMT' > > # OK > > >>> import pygtk > >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) > > 'Sat, 02 Aug 2008 20:22:04 GMT' > > # OK > > >>> import gtk > >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) > > 'Sat, 02 Aug 2008 08:22:11 PM GMT' > > # HOW THE HELL THIS HAPPEN ??? not DATE_RFC2822 format gmt time ! Reading the manual page for strftime -- http://docs.python.org/lib/module-time.html -- says that '%X' is the locale's appropriate time representation, so obviously gtk is adjusting your locale. Perhaps use a formatting string that doesn't depend on the locale: '%H:%M:%S' instead of '%X' seems to give your preferred format. -- Paul Hankin From paul at boddie.org.uk Sat Aug 2 15:31:16 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 2 Aug 2008 12:31:16 -0700 (PDT) Subject: interpreter vs. compiled References: <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <4rl294duo83eujnq6tjbk215mavpl87o9r@4ax.com> <43f519dd-6763-4cc0-a6d2-1e671da54c2c@d45g2000hsc.googlegroups.com> <92716c9e-b940-453f-a817-1c95c00727d1@26g2000hsk.googlegroups.com> Message-ID: <5a7f3ab7-c71b-466f-a477-dfbdda582e46@m73g2000hsh.googlegroups.com> On 2 Aug, 08:33, castironpi wrote: > On Aug 1, 5:24 am, Paul Boddie wrote: > > > a + b # in Python > > > > ...is not sufficiently represented by... > > > > ldr r1, a > > ldr r2, b > > add r3, r1, r2 > > > > ...in some assembly language (and the resulting machine code), mostly > > because the semantics of Python addition are more complicated. > > No, it is not sufficiently represented. Python runs checks before and > after, to check for overflows. It does more than this... > test safeinteger a > test safeinteger b > ldr r1, a > ldr r2, b > add r3, r1, r2 > test not overflow > > However, no implementation of Python can do better, given Python's > specification. In fact, as was probably mentioned before, it does something more like this: get method __add__ on a (if possible) or jump to (1) populate an invocation frame with a and b call the method test the result against the special NotImplemented value if result is not NotImplemented then jump to (3) (1) get method __radd__ on b (if possible) or jump to (2) populate an invocation frame with b and a call the method test the result against the special NotImplemented value if result is not NotImplemented then jump to (3) (2) raise a TypeError exception (3) provide the result to whatever gets evaluated next The instructions that you list, which is based on the really simple case which I mentioned, happens in the method that gets called (eg. __add__), and then only for integers. Note that seemingly trivial things like getting the methods can be quite a few instructions in any low-level code. [...] > Another factor, a and b are known to be and are always integers, in a > given C context. > > int a, b; > ... > a + b > > The C compilation process outputs: > > ldr r1, a > ldr r2, b > add r3, r1, r2 Right. That's why some people want to have type declarations in Python, and others want to be able to generate specialised code at run- time for such cases. > and you are correct. However, for: > > string a, b; > a + b > > performs a concatenation which is not that simple. The point is, C > compilation runs, and you actually have -ldr, ldr, add- lying around > in a file somewhere, which can run as three consecutive instructions > on a processor. It's already in the interpreter in Python, and you > have the -test, test, ldr, ldr, add, test- sequence somewhere in > Python.exe, specifically wherever the object code for ceval.c is > going. Right. The way to think about this is that due to the mechanics of working out what kind of operations should be performed (should it be an integer addition, a string concatentation, something else?), there's a lot of code executed which is really "dancing around" the actual work, and then for short bursts of instructions, the work actually gets done. It's like having to jet around the world, sampling drinks in different locations, rather than just lining the different drinks up at home. Paul From jonmosco at gmail.com Sat Aug 9 15:32:41 2008 From: jonmosco at gmail.com (hypermonkey2) Date: Sat, 9 Aug 2008 12:32:41 -0700 (PDT) Subject: "shelve" save object Message-ID: <46f0f2bd-4267-4dc8-ad8c-4a6c0b05878d@d45g2000hsc.googlegroups.com> Hi there! I am using the "shelve" module in a script to save information in between runtime sessions of the program. (its a sort of data collector, so its important to hold on to anything computed ). In any case, I shelve into a file "test.txt". I notice that when i try running the program on a different computer (by either emailing or transfering the file "test.txt" via USB key), the program is unable to load the shelve file. What can I do to fix this? It would be a great shame to see that after collecting all this information and shelving it that I cannot move to another computer or share the information through the "save.txt" file. Thanks in advance! Jon From aaron.hildebrandt at gmail.com Mon Aug 18 12:16:13 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Mon, 18 Aug 2008 09:16:13 -0700 (PDT) Subject: mod_python and updated files Message-ID: I have mod_python running on my server, but when I chance a Python file on the server, Apache needs to be restarted in order to have the changes take effect. I assume this is so mod_python can run persistently, but it's becoming quite a headache for development. Is there a way to turn off the persistence, or a way to force mod_python to compile and run the new version of the file? From peter.anderson at internode.on.net Fri Aug 8 01:58:57 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Fri, 08 Aug 2008 15:58:57 +1000 Subject: very newbie question Message-ID: <489BE0A1.8020202@internode.on.net> Try this: # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money import random print "\tWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 100." print "Try to guess it in as few attempts as possible.\n" # set the initial values the_number = random.randrange(100) + 1 tries = 0 def ask_number(): guess = int(raw_input("Take a guess: ")) tries = 1 while (guess != the_number): if (guess > the_number): print "Lower..." else: print "Higher..." tries += 1 guess = int(raw_input("Take a guess: ")) tries += 1 ask_number() print "You guessed it! The number was", the_number print "And it only took you", tries, "tries!\n" raw_input("\n\nPress the enter key to exit.") The variables "the_number" and "tries" were not available outside the "ask_number()" module. Alternatively drop the def function and lump it all into a simple script. -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From sjmachin at lexicon.net Wed Aug 20 06:43:08 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 20 Aug 2008 03:43:08 -0700 (PDT) Subject: Basic importing question References: Message-ID: On Aug 20, 8:08?pm, Hussein B wrote: > Hey, > Suppose I have a Python application consists of many modules (lets say > it is a Django application). > If all the modules files are importing sys module, how many times the > sys module will be compiled and executed? > Only once (the first time the PVM locates, compiles and executes the > sys module)? or once for each module importing sys? > Thanks. sys is a built-in module, so the answer is zero times. For a non-builtin module foo where there exists: (1) only a foo.py, it will be compiled into foo.pyc (2) only a foo.pyc, it will be used (3) both a foo.py and a foo.pyc, Python compiles the foo.py if the pyc is out of date or (so I believe [*]) was created by a different version of Python. Subsequent imports will use the in-memory copy (in sys.modules, IIRC [*]) ... [*] == Please save me the bother of checking this in the manual :-) HTH, John From exarkun at divmod.com Thu Aug 14 10:36:45 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 14 Aug 2008 10:36:45 -0400 Subject: Trying ZODB, background in Relational: mimic auto_increment? In-Reply-To: <6git1dFfta1fU1@mid.uni-berlin.de> Message-ID: <20080814143645.29191.298476970.divmod.quotient.14347@ohm> On Thu, 14 Aug 2008 16:15:11 +0200, "Diez B. Roggisch" wrote: >Jean-Paul Calderone wrote: > >> On Thu, 14 Aug 2008 05:22:35 -0700 (PDT), Phillip B Oldham >> wrote: >>> [snip] >>> >>>How would one assign a unique ID to the root at that point? >> >> Here's one way >> >> class Sequence(Persistence): >> def __init__(self): >> self.current = 0 >> >> def next(self): >> self.current += 1 >> return self.current >> >> ticketSequence = Sequence() >> >> class Ticket(Persistence): >> def __init__(self): >> self.id = ticketSequence.next() > >Be aware that this isn't working concurrently. Depending on your >application, this can be mitigated using a simple threading.Lock. > ZODB has transactions. That's probably the best way to make this code safe for concurrent use. A threading.Lock would make threaded use safe, but wouldn't give you multiprocess concurrency safety. Jean-Paul From smbaker at gmail.com Tue Aug 12 20:02:51 2008 From: smbaker at gmail.com (Scott) Date: Tue, 12 Aug 2008 17:02:51 -0700 (PDT) Subject: passing a variable argument list to a function Message-ID: I'm trying to write a function that accepts a variable number of arguments and passes those arguments to another function. Here is an example: def foo(*args): print "I'm going to call bar with the arguments", args bar(args) This doesn't do quite what I want. For example, if I call foo(1,2,3,4) then it calls bar((1,2,3,4)). It passes a tuple rather than expanding the argument list back out. I suspect there's a simple bit of syntax that I'm missing -- can anyone give me a hand? Thanks Scott From see.signature at no.spam Thu Aug 14 05:01:32 2008 From: see.signature at no.spam (Eric Brunel) Date: Thu, 14 Aug 2008 11:01:32 +0200 Subject: Tkinter updates - Easiest way to install/use Tile? References: Message-ID: On Wed, 13 Aug 2008 19:10:47 +0200, Mudcat wrote: [snip] > I was reading about Tile, and it sounds like I should be able to wrap > a style around my current code to give it a different look. However it > doesn't sound like it's quite ready for prime time yet. I downloaded > the latest stable version of Python 2.5 which apparently still uses > Tcl 8.4. So my options at this point appear to be: > > 1) Download beta version of Python 2.6 which has Tcl 8.5. > Tile is supposed to be included with Tcl 8.5, but there's not much > information on how to use it with older code. Do I still need wrapper > code, or if I install 2.6 will it be available already. Well, if you do it today and look in the Lib/lib-tk directory, you'll see that there is nothing specific to Tile/ttk in any of the module. So ATM, new wrappers are needed indeed. If I had to say which wrappers have the best chance to actually become "official", I'd bet on Guilherme Polo's ones here: http://gpolo.ath.cx:81/projects/ttk_to_tkinter/ These seem to be the most complete, and somebody's actually working on them. > 2) Install Tcl 8.5 to use with Python 2.5. > How do you do this? In other posts it mentions recompiling source tcl > code with Python. If that's the case it doesn't sound like something I > want to mess with. If I stray too far from default configurations I > start to have problems with py2exe. I guess it would probably be better to at least recompile the _tkinter.c module to get the new tcl/tk header files. I think I also read somewhere that there were API incompatibilities between tcl/tk 8.4 and 8.5. Don't know if it has any impact on Tkinter. > 3) Install Tile with Python 2.5 and Tcl 8.4 and use wrapper code to > make it work. > However all the posts concerning this approach assume that Tile is > already installed. I downloaded the code for the latest version of > Tile which was a .kit extension. This also may need to be compiled, > and if that's the case I again start to have problems with freezing my > application. This doesn't look like the way to go for me: you'll add the burden of having to install the Tile package at tcl/tk level while not gaining anything, since you'll still have to use wrappers that may or may not be official in the end. > What's the easiest way to do this? I really couldn't find a place that > gave instructions for any of the current release configurations. It > sounds if it's available already in Python 2.6 that it would be the > easiest way, but I couldn't find any threads talking about the > availability of it for that release yet. As I said above, if I had to choose today, I'd go Python 2.6 + tcl/tk 8.5 + Guilherme Polo's ttk wrappers. But if you can do it, I'd say: just wait. Things are moving fast: the latest Python 2.6 beta release is less than a month old, and Guilherme Polo has marked his ttk wrappers project as complete only 3 days ago. So maybe the next Python beta will actually include them... And BTW, the final release for Python 2.6 is planned at the beginning of October, so this is not that far away. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From __peter__ at web.de Fri Aug 15 05:35:32 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 15 Aug 2008 11:35:32 +0200 Subject: getattr nested attributes References: Message-ID: Gregor Horvath wrote: > Peter Otten schrieb: > >> make your own function that loops over the attributes, or spell it >> >>>>> reduce(getattr, "a.test".split("."), B) >> 'test' >> > > Thank's, but this does not work for this case: > > class A(object): > test = "test" > > class B(object): > a = [A(),] > > In [70]: reduce(getattr, "a[0].test".split("."), B) > --------------------------------------------------------------------------- > Traceback (most recent call > last) > > / in () > > : type object 'B' has no attribute > 'a[0]' Like the screwdriver doesn't work with a nail? > Seems that I have to use eval ? > I have a mapping text file (data) which contains such attributes strings > and those attributes should be read. When you pass data to eval() it becomes code. If you trust the source of that text file that would be the easiest approach. Otherwise google for 'safe eval'. Peter From byte8bits at gmail.com Wed Aug 27 14:38:55 2008 From: byte8bits at gmail.com (brad) Date: Wed, 27 Aug 2008 14:38:55 -0400 Subject: Python multimap In-Reply-To: <4d2f1ac5-c21c-42d9-977e-6493f0c23573@d77g2000hsb.googlegroups.com> References: <4d2f1ac5-c21c-42d9-977e-6493f0c23573@d77g2000hsb.googlegroups.com> Message-ID: castironpi wrote: > I don't understand what a multimap does that a map of lists doesn't do. It counts both keys individually as separate keys. The Python workaround does not... see examples... notice the key(s) that are '4' Python output (using the k = [] idea): Key: 4 Value: [[13, 'Visa'], [16, 'Visa']] Key: 51 Value: [16, 'MC'] Key: 65 Value: [16, 'Discover'] Key: 2131 Value: [15, 'JCB'] Key: 300 Value: [14, 'Diners CB'] Key: 301 Value: [14, 'Diners CB'] Key: 302 Value: [14, 'Diners CB'] Key: 303 Value: [14, 'Diners CB'] Key: 304 Value: [14, 'Diners CB'] Key: 305 Value: [14, 'Diners CB'] Key: 35 Value: [16, 'JCB'] Key: 34 Value: [15, 'Amex'] Key: 55 Value: [16, 'MC or Diners US and CA'] Key: 36 Value: [14, 'Diners Intl'] Key: 37 Value: [15, 'Amex'] Key: 1800 Value: [15, 'JCB'] Key: 54 Value: [16, 'MC'] Key: 6011 Value: [16, 'Discover'] Key: 52 Value: [16, 'MC'] Key: 53 Value: [16, 'MC'] Key: 385 Value: [14, 'Diners CB'] 21 is the size of the dict A C++ multimap Key: 1800 Value: JCB 15 Key: 2131 Value: JCB 15 Key: 300 Value: Diners_Club 14 Key: 301 Value: Diners_Club 14 Key: 302 Value: Diners_Club 14 Key: 303 Value: Diners_Club 14 Key: 304 Value: Diners_Club 14 Key: 305 Value: Diners_Club 14 Key: 34 Value: American_Express 15 Key: 35 Value: JCB 16 Key: 36 Value: Diners_Club 14 Key: 37 Value: American_Express 15 Key: 385 Value: Diners_Club 14 Key: 4 Value: Visa 16 Key: 4 Value: Visa 13 Key: 51 Value: MasterCard 16 Key: 52 Value: MasterCard 16 Key: 53 Value: MasterCard 16 Key: 54 Value: MasterCard 16 Key: 55 Value: MasterCard 16 Key: 6011 Value: Discover 16 Key: 65 Value: Discover 16 22 is the size of the multimap From benjamin.kaplan at case.edu Thu Aug 28 00:33:48 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 28 Aug 2008 00:33:48 -0400 Subject: [Q] How to ignore the first line of the text read from a file In-Reply-To: References: Message-ID: On Thu, Aug 28, 2008 at 12:11 AM, youngjin.michael at gmail.com < youngjin.michael at gmail.com> wrote: > Hello, > > I am new to Python and have one simple question to which I cannot find > a satisfactory solution. > I want to read text line-by-line from a text file, but want to ignore > only the first line. I know how to do it in Java (Java has been my > primary language for the last couple of years) and following is what I > have in Python, but I don't like it and want to learn the better way > of doing it. > > file = open(fileName, 'r') > lineNumber = 0 > for line in file: > if lineNumber == 0: > lineNumber = lineNumber + 1 > else: > lineNumber = lineNumber + 1 > print line > > Can anyone show me the better of doing this kind of task? > > Thanks in advance. > > -- Files are iterators, and iterators can only go through the object once. Just call next() before going in the for loop. Also, don't use "file" as a variable name. It covers up the built-in type. afile = open(file_name, 'r') afile.next() #just reads the first line and doesn't do anything with it for line in afile : print line > > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bhood2 at comcast.net Tue Aug 26 10:41:42 2008 From: bhood2 at comcast.net (bhood2 at comcast.net) Date: Tue, 26 Aug 2008 08:41:42 -0600 Subject: Need help with extension modules built in debug mode References: Message-ID: On Tue, 26 Aug 2008 08:20:44 +0200, Fredrik Lundh wrote: >bhood2 at comcast.net wrote: > >> I've come to the conclusion that posting about Embedded Python on the >> Python forums is a complete waste of time. I hope I can get some >> useful insights here. > >(just curious, but what are the "Python forums"? isn't the >newsgroup/mailing list *the* Python forum?) http://python-forum.org/pythonforum/index.php From ce at mail.net.sk Wed Aug 13 01:08:56 2008 From: ce at mail.net.sk (Mahdi) Date: Wed, 13 Aug 2008 13:08:56 +0800 Subject: Python web framework choice Message-ID: Guys! I need to develop a medium-sized database web application for my company. Given that: I don't know much about building web UI(s) but i have fair knowledge about HTML & My schedule is tight. a recommendation is v v v appreciated. thanks! From anishchapagain at gmail.com Mon Aug 4 09:27:51 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Mon, 4 Aug 2008 06:27:51 -0700 (PDT) Subject: Wrapping C API References: <24f5104e-b89a-4351-880b-7cdc7c04631c@z66g2000hsc.googlegroups.com> Message-ID: <29ee7157-bc9b-4dca-b1db-02cf67a996e9@79g2000hsk.googlegroups.com> On 4 Aug, 14:20, Ulrich Eckhardt wrote: > Anish Chapagain wrote: > > I'm new to python and have a task for Wrapping up an old program > > written in C(20.c files), to provide GUI and chart,graph feature in > > Python. I've tried using SWIG but am not getting well in windows > > system, wish to receive guidelines for initiating the task... > > Two ways come to mind: > 1. ctypes > 2. popen > > The former is basically an interface to the C language types which makes it > rather easy to load C DLLs and call functions therein. The latter is a way > to start a program with redirected input and output, something that can be > used to remote-control any commandline application. > > Uli > > -- > Sator Laser GmbH > Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 For, plotting chart and graph through C, dll in pyhton will ctype be more easy.. if there any example would like to see once.. thank's From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 19 07:38:09 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 19 Aug 2008 13:38:09 +0200 Subject: Handling Property and internal ('__') attribute inheritance and creation In-Reply-To: References: Message-ID: <48aab09b$0$6986$426a74cc@news.free.fr> Fredrik Lundh a ?crit : > Eric Brunel wrote: > >> To add to what others have already said, it is not only 'just extra >> work', it is also quite dangerous. See: >> >> class A(object): >> children = [] > > the OP is aware of that, of course: > > > I set anything that is constant but anything variable is set again in > > __init__() > > as long as if you're aware of the issues involved (which you should be > if you're using Python professionally), using class-level attributes is > a perfectly valid Python style. Using class attributes is perfectly valid Python style, indeed. But in this case - ie: using class attributes as a pseudo-declaration of instance attributes -, I would not call this good style : it's a waste of time, a violation of DRY, and a potential source of confusion for the class's users / maintainers. From castironpi at gmail.com Wed Aug 13 18:21:25 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 13 Aug 2008 15:21:25 -0700 (PDT) Subject: Inquisitive computing References: <41264be6-3dae-4ca3-ab6f-aba20130a0c1@l42g2000hsc.googlegroups.com> Message-ID: <14334770-fb04-485a-a701-2dba1fc1ea6a@m36g2000hse.googlegroups.com> On Aug 13, 4:29?pm, bearophileH... at lycos.com wrote: > David C. Ullrich: > > > If you look at the end of the article you see the author > > agrees (I don't quite follow his complaint about not feeling > > at home with the interactive mode, but it's funny to read about > > how he uses Lisp but realizes he's not going to talk people > > into that...) > > That well know author thinks Python is almost fit, but not quite (no > rationals, he seems to not like imports, and he wants optional types, > and native compilation performance too, etc), and I think he likes > Scheme a lot (not right CLisp). You may want to take a look at the > article to see if I am right. > > Bye, > bearophile He didn't mention a debugger, which Python does have. But in mentioning Python he didn't distinguish between the live interpreter console and executing a script. Also, the idea of language- independent editor isn't explored; they're too closely coupled. (Except maybe Bloodshed Dev, which has a Tools menu, you can customize to say \python\python %curfile%.) From gh at ghaering.de Mon Aug 18 07:33:48 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 18 Aug 2008 13:33:48 +0200 Subject: SQLite's default ON CONFLICT algorithm In-Reply-To: <20080818102428.GA6049@hccnet.nl> References: <20080818102428.GA6049@hccnet.nl> Message-ID: egbert wrote: > Yes, I know that this is off-topic, but I feel justified by sqlite3 > being a builtin. > > The default ON CONFLICT algorithm in SQLite is ABORT. > The SQLite documentation ("ON CONFLICT clause") says that when > a constraint violation occurs under ABORT, no rollback is executed, > so changes from prior commands within the same transaction are > preserved. > Isn't this a strange choice for a default ? No, it's just like every other database error - the command fails but the connection is left untouched. > After all, you expect that either all changes within a transaction > are preserved, or that nothing at all is preserved. Sure, the successful ones ;-) > The Python Library Reference on sqlite3 says in paragraph 13.13.5 > that I should not use the ROLLBACK conflict algorithm in my sql. > Instead I have to catch the IntegrityError and call the rollback method. FWIW, this restriction is not any longer true in Python 2.6 and 3.0 btw. You can now safely use "ON CONFLICT ROLBLACK" with the sqlite3 module. > Does that mean that I have to wrap all multi-command transactions > in a try-except if I don't like the default ABORT choice ? Well, you have to do that *always* anyways if you want your app to behave correctly. Typical usage of the DB-API looks like this: cur = con.cursor() try: cur.execute(...) cur.execute(...) cur.execute(...) con.commit() except .DatabaseError: con.rollback() With the sqlite3 module, there's a shortcut: from __future__ import with_statement with con: cur.execute(...) cur.execute(...) cur.execute(...) which does exactly the same as the code above. -- Gerhard From aahz at pythoncraft.com Wed Aug 13 11:11:05 2008 From: aahz at pythoncraft.com (Aahz) Date: 13 Aug 2008 08:11:05 -0700 Subject: dict.update() useful or not? References: <00b06f78$0$14351$c3e8da3@news.astraweb.com> Message-ID: In article <00b06f78$0$14351$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > >What do other people find? Do you find use for dict.update()? What other >idioms do you use for combining dictionaries? My company's code relies heavily on d.update() -- it's extremely handy in the context of a web form. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From rhamph at gmail.com Fri Aug 1 18:06:15 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Fri, 1 Aug 2008 15:06:15 -0700 (PDT) Subject: when does the GIL really block? References: Message-ID: <8894ad9e-cac5-43b2-80cc-7b605de6866a@v8g2000prm.googlegroups.com> On Jul 31, 7:27?pm, Craig Allen wrote: > I have followed the GIL debate in python for some time. ?I don't want > to get into the regular debate about if it should be gotten rid of > (though I am curious about the status of that for Python 3)... > personally I think I can do multi-threaded programming well, but I > also see the benefits of a multiprocess approach. I'm not so > egotistical that I don't realize perhaps my mt programming has not > been "right" (though it worked and was debuggable) or more likely that > doing it right I have avoided even trying some things people want mt > programming to do... i.e. to do mt programming right you start to use > queues a lot, inter-threadasynchronous, non-blocking, communication, > which is essentially the multi-process approach, using IPC (except > that thethreads can see the same memory when, in your special case, > you know that's ok. Given something like a reader-writer lock, this > can have benefits... but again, whatever. > > My question is that given this problem, years ago before I started > writing in python I wrote some short programs in python which could, > in fact, busy both my CPUs. ?In retrospect I assume I did not have > code in my run function that causes a GIL lock... so I have done this > again. > > I start twothreads... I use gkrellm to watch my processors (dual > processor machine). ?If I merely print a number... both CPUS are > getting 90% simultaneous loads. If I increment a counter and print it > too, the same, and if I create a small list and sort it, the same. I > did not expect this... I expected to see one processor pegged at > around 100%, which should sometimes switch to the other processor. > Granted, the same program in C/C++ would peg both processors at > 100%... but given that the overhead in the interpreter cannot explain > the extra usage, I assume the code in mythread's run functions is > actually executing non-serially. Try using sys.setcheckinterval(10000) (or even larger), overriding the default of 100. This will reduce the locking overhead, which might by why you see both CPUs as busy. > I assume this is because what I am doing does not require the GIL to > be locked for a significant part of the time my code is running... > what code could I put in my run function to see the behavior I > expected? ?What code could I put there to take advantage of the > possibility that really the GIL is not locked enough to cause actual > serialization of thethreads... ?anyone care to explain? The GIL is locked during *all* access to the python interpreter. There's nothing pure python code can do to avoid it - only a C extension that doesn't access python could. From harrrrpo at gmail.com Sat Aug 23 20:27:46 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Sun, 24 Aug 2008 03:27:46 +0300 Subject: Imports visibility in imported modules problem Message-ID: <538050a90808231727w63b78c48ueefaf37ec864e72e@mail.gmail.com> Hello , The problem I'm asking about is how can imported modules be aware of other imported modules so they don't have to re-import them (avoiding importing problems and Consicing code and imports ) Take Example :- in A.py :- import B print dir() # no problems we can see B which contain re module and C module B.C.W() # our problem here we get an empty list in B.py :- import re import C in C.py :- def W(): print dir() # when called from A we get [] though other imports has been made to re and others my goal is basically making W() aware of the re module when called from A ---- why am i doing this in the first place I'm in the process of a medium project where imports of modules start to make a jungle and i wanted all needed imports to be in a single file (namely __init__.py) and then all imports are made once and other modules feel it another reason to do this that my project is offering 2 interfaces (Console and GUI through Qt) and i needed a general state class ( whether i'm in Console or GUI mode) to be available for all , for determining state and some public functions ,and just injecting Imports everywhere seems a bad technique in many ways (debugging , modifying ...etc ) in PHP "Require" would do the trick neatly ... so is there is something I'm missing here or the whole technique is bad in which case what do you suggest ? Thanks, Regards, Mohamed Yousef From hv at tbz-pariv.de Thu Aug 14 10:41:57 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Thu, 14 Aug 2008 16:41:57 +0200 Subject: Trying ZODB, background in Relational: mimic auto_increment? In-Reply-To: References: Message-ID: <6giuhlFfvq3kU1@mid.individual.net> auto increment: > Here's one way > > class Sequence(Persistence): > def __init__(self): > self.current = 0 > > def next(self): > self.current += 1 > return self.current > > ticketSequence = Sequence() > > class Ticket(Persistence): > def __init__(self): > self.id = ticketSequence.next() > I am sorry, but this does not work if several threads or processes try to get a new id. Have a look at: http://www.zope.org/Documentation/Books/ZDG/current/Persistence.stx "Resolving Conflicts". BTW, that's one of the points why I switched from ZODB to Postgres. HTH, Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From vinay_sajip at yahoo.co.uk Wed Aug 27 09:30:25 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 27 Aug 2008 06:30:25 -0700 (PDT) Subject: logging exceptions References: <3c8c0b98-54ea-4112-8db9-e0040929e558@w1g2000prk.googlegroups.com> <200e9b4d-c062-4984-bcec-581666458071@79g2000hsk.googlegroups.com> <1868e033-8313-414c-a82a-35a8852ffb77@v57g2000hse.googlegroups.com> Message-ID: <6938d476-2eb7-4cfb-b3d4-b8f2f6cd45fc@w7g2000hsa.googlegroups.com> On Aug 27, 10:30 am, Rob Wolfe wrote: > Vinay Sajip napisa?(a): > > > > > On Aug 26, 10:36 am, Alexandru Mosoi wrote: > > > why doesn'tloggingthrow any exception when it should? how do I > > > configureloggingto throw exceptions? > > > > >>> try: > > > > ... logging.fatal('asdf %d', '123') > > > ... except: > > > ... print 'this line is never printed' > > > ... > > > Traceback (most recent call last): > > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > > python2.5/logging/__init__.py", line 744, in emit > > > msg = self.format(record) > > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > > python2.5/logging/__init__.py", line 630, in format > > > return fmt.format(record) > > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > > python2.5/logging/__init__.py", line 418, in format > > > record.message = record.getMessage() > > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > > python2.5/logging/__init__.py", line 288, in getMessage > > > msg = msg % self.args > > > TypeError: int argument required > > > Was your traceback from the snippet you posted? If it was, then the > > exception (a TypeError) *is* being raised fromlogging. So I don't > > understand your question "why doesn'tloggingthrow any exception when > > it should?", becauseloggingis raising an exception here. > > No, it isn't. > This traceback is *printed* in `Handler.handleError` method: > You're right - silly me. I wasn't paying attention :-( > > variable would normally be set to 0 in a production environment, where > > you don't wantlogging-related exceptions to bring an application > > down. > > Well, I think that it will not help. The exception will be printed > not raised. The only solution is to redefine `handleError` method > or maybe I've missed something? > No, you're right. To do custom handling of exceptions, handleError needs to be overridden. Regards, Vinay From rafesacks at gmail.com Fri Aug 15 11:40:31 2008 From: rafesacks at gmail.com (Rafe) Date: Fri, 15 Aug 2008 08:40:31 -0700 (PDT) Subject: Passing an object through COM which acts like str but isn't References: <3c632ccb-2fb0-436f-ae7f-b2c3ae5c803f@s1g2000pra.googlegroups.com> Message-ID: <7256565d-f8a1-4e47-91de-cd86ec5b31b5@v13g2000pro.googlegroups.com> On Aug 15, 10:27 pm, Wolfgang Grafen wrote: > Rafe schrieb: > > > Forgive me if I mangle any terminology here, but please correct me if > > I do... > > > I have an object which acts exactly like a string as long as I stay in > > Python land. However, I am using the object in Softimage|XSI, a 3D > > application on Windows. I'm getting variant erros when trying to use > > my instances as I would a string. > > > XSI was created while (briefly) owned by Microsoft, so knowledge of > > COM with excel, or anything else, should be applicable I should think. > > I should also say I am a COM novice and still learning the depths of > > Python. > > > Here is an example... > > > class StrLike(object): > > def __init__(self, s): self.__data = s > > def __repr__(self): return repr(self.__data) > > def __cmp__(self, string): return cmp(self.__data, string) > > def __contains__(self, char): return char in self.__data > > > __data = "" > > def __Set(self, value): self.__data = value > > def __Get(self): return self.__data > > data = property(fget = __Get, > > fset = __Set, > > fdel = None, > > doc = "string-like example") > > >>>> s = StrLike("test") > >>>> s > > 'test' > >>>> if s == "test": print "cmp works" > > cmp works > > > Now if I try to pass this as I would a string, roughly like so... > >>>> s = StrLike("test") > >>>> Application.AnObject.attribute = "test" # works fine > >>>> Application.AnObject.attribute = s > > ERROR : Traceback (most recent call last): > > File " ------=_NextPart_000_22D9BBBE_1.3E24F6BA-- ------=_NextPart_000_22D9BBBE_0.3E24F6BA-- From dullrich at sprynet.com Fri Aug 8 13:18:19 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 08 Aug 2008 12:18:19 -0500 Subject: Psycho question References: Message-ID: In article , "Delaney, Timothy (Tim)" wrote: > David C. Ullrich wrote: > > > f: 0.0158488750458 > > g: 0.000610113143921 > > h: 0.00200295448303 > > f: 0.0184948444366 > > g: 0.000257015228271 > > h: 0.00116610527039 > > I suspect you're hitting the point of diminishing returns with g, and > any further investigations into optimisation are purely for fun and > learning ;) No doubt. Hadn't meant to get into optimization, at least not here, but various people made various comments - when someone suggests this or that seems like I should try it. Curiously g is exactly how I'd planned on doing it before trying anything. The one thing that puzzles me about all the results is why // is so much slower than / inside that Psyco loop. > Tim Delaney -- David C. Ullrich From straton at lampsacos.demon.co.uk Mon Aug 25 18:09:52 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Mon, 25 Aug 2008 23:09:52 +0100 Subject: Private attribute In-Reply-To: <6hgmj5Flo1i6U4@mid.uni-berlin.de> References: <076a50cb-99ad-44c5-b4eb-17a45ee1abe9@c65g2000hsa.googlegroups.com> <6hgmj5Flo1i6U4@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Mon, 25 Aug 2008 21:44:49 +0100, Ken Starks wrote: > >>>> #################### >>>> >>>> def __getattr__(self,attrname): >>>> if attrname == 'gridsize': >>>> return 0.8 >>>> >>>> def __setattr__(self,attrname,value): >>>> if attrname == 'gridsize': >>>> pass >>>> else: >>>> self.__dict__[attrname]=value >>> [?] >> I admit I haven't used properties, and had to look them up. Pretty cool >> indeed ! But an extra unnecessary level of complexity for my needs >> here, I feel. > > Compare this with your approach above and point out the extra complexity > please: > > @property > def gridsize(self): > return 0.8 > > Ciao, > Marc 'BlackJack' Rintsch mea culpa. As i mentioned, I haven't used them before. I have already changed my class Foo: to class Foo(object): and I'll do the rest tomorrow. From deets at nospam.web.de Wed Aug 27 08:43:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 27 Aug 2008 14:43:27 +0200 Subject: unexpected from/import statement behaviour References: <42780654-8a54-470e-a494-ca53fd0504f5@p25g2000hsf.googlegroups.com> <7dbab131-7f7b-4266-b706-fff52670e9e1@l64g2000hse.googlegroups.com> Message-ID: <6hl0gdFmjg0iU2@mid.uni-berlin.de> nisp wrote: > On Aug 27, 9:56 am, Peter Otten <__pete... at web.de> wrote: >> nisp wrote: >> > Hi all ! >> >> > I'm trying to capture stderr of an external module I use in my python >> > program. I'm doing this >> > by setting up a class in my module overwriting the stderr file object >> > method write. >> > The external module outputs to stderr this way: >> >> > from sys import std err >> >> > .... >> >> > print >> stderr, "Some text" >> >> > While in my module I use >> >> > import sys >> >> > ..... sys.stderr ... sys.stdout >> >> > Well, as long as I do not change in the external module those from/ >> > import statements to just >> >> > import sys >> >> > .... >> >> > print >> sys.stderr, "Some text" >> >> > I'm not able to capture its stderr and of course I would like not to >> > do this kind of change. >> > I've always been convinced of the equivalence of the two ways of using >> > the import statement >> > but it's clear I'm wrong :-( >> >> > Please, someone can tell me what's going on ? >> >> > Thanks in advance ! >> >> A practical approach to complement Diez' link to the explanation: >> >> Instead of modifying the external module you can either redirect stderr >> before you import the external module >> >> import sys >> sys.stderr = whatever >> import external >> >> or monkey-patch: >> >> import sys >> import external >> >> sys.stderr = external.sterr = whatever >> >> Peter > > Hi all ! > > Thanks first of all ! I read the interesting Diez's link but something > still remains to me unclear, on the other hand it's clear the my > problem is concentrated there and on symbols. > Here is what I'm trying to do > > HelloWorld.py: this is a real simplification of my external module > though still reflecting its structure (commented out is the version > that, let's say, works) > > from sys import stderr This is your problem. You create a HelloWorld.stderr-alias to the object bound to sys.stderr. Rebinding the latter won't affect the former. That is precisely what the link I gave you explains. The short answer to the whole issue is: dont' use the from-import syntax until you really know what you are doing. Or not at all. Diez From steve at REMOVE-THIS-cybersource.com.au Mon Aug 18 10:23:20 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2008 14:23:20 GMT Subject: Bizarre method keyword-arg bug. References: <73104fb9-3f05-445e-83e6-2b1939316f15@d77g2000hsb.googlegroups.com> <4b056d24-5d3c-4610-a551-1a917fd765d4@m36g2000hse.googlegroups.com> Message-ID: <00b980c0$0$20315$c3e8da3@news.astraweb.com> On Mon, 18 Aug 2008 04:07:14 -0700, Paul Boddie wrote: > Ultimately, I suppose one could enforce some kind of least surprising > "best practice" by limiting default parameter values to being literals > of immutable objects or names, as opposed to expressions, thus > eliminating some potential confusion. -1 Firstly, I *like* the ability to use mutable objects as default arguments. I don't do it often, but when I do, I do it deliberately. I find it useful. Secondly, I think forbidding expressions as default arguments would be far worse than the so-called "problem" you wish to fix. It would make such simple default arguments as these unnecessarily complicated: def foo(x=2**64, sentinel=object()) Please don't try to "fix" this feature. -- Steven From dblubaugh at belcan.com Tue Aug 26 15:36:41 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Tue, 26 Aug 2008 15:36:41 -0400 Subject: Using Python to shared memory resources between Linux and Windows In-Reply-To: References: Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3804CF59D8@AWMAIL04.belcan.com> To All, I was wondering if it was possible to utilize python to share a memory resource between a linux and windows system?? It should be stated that both the Linux (CENTOS 5) and windows are physically located on the same computer. Is any of this possible? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From tjreedy at udel.edu Sun Aug 10 14:32:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 10 Aug 2008 14:32:14 -0400 Subject: Validation of parameters In-Reply-To: <4785d2c9-f1ce-4226-acfe-2cf35b8303dd@34g2000hsh.googlegroups.com> References: <1578181c-6013-4944-8abe-68148ca53960@d45g2000hsc.googlegroups.com> <4785d2c9-f1ce-4226-acfe-2cf35b8303dd@34g2000hsh.googlegroups.com> Message-ID: Kless wrote: > On 10 ago, 15:03, Paddy wrote: >> If you just want the absense of _foo to raise an exception then why to >> just reference self._foo and leave the hard work to ptyhon? Something >> like: >> >> self._foo >> >> If it is present then fine, if it is not then an exception is raised. > It only was an example but I need show a better message. The usual idiom is try: self._foo except AttrError as m: #3.0 From shahmed at sfwmd.gov Mon Aug 18 13:42:03 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Mon, 18 Aug 2008 13:42:03 -0400 Subject: help with parsing email In-Reply-To: References: Message-ID: -----Original Message----- From: python-list-bounces+shahmed=sfwmd.gov at python.org [mailto:python-list-bounces+shahmed=sfwmd.gov at python.org] On Behalf Of Werner F. Bruhin Sent: Monday, August 18, 2008 1:04 PM To: python-list at python.org Cc: python-win32 at python.org Subject: Re: help with parsing email Ahmed, Shakir wrote: > Thanks everyone who tried to help me to parse incoming email from an exchange server: > > Now, I am getting following error; I am not sure where I am doing wrong. I appreciate any help how to resolve this error and extract emails from an exchange server. > > > First I tried: >>>> mailserver = 'EXCHVS01.my.org' >>>> mailuser = 'myname' >>>> mailpasswd = 'mypass' >>>> mailserver = poplib.POP3(mailserver) > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\lib\poplib.py", line 96, in __init__ > raise socket.error, msg > error: (10061, 'Connection refused') > > > > The other way: > >>>> mailserver = 'pop.EXCHVS01.ad.my.org' >>>> mailuser = 'myname at my.org' >>>> mailpasswd = 'mypass' >>>> mailserver = poplib.POP3(mailserver) > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\lib\poplib.py", line 84, in __init__ > for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): > gaierror: (11001, 'getaddrinfo failed') Haven't used poplib myself, but was intrigued. Did you see this: http://www.python.org/doc/lib/pop3-example.html To me it looks like you are not setting the user/password. So, maybe something like: M = poplib.POP3(mailserver) M.user(mailuser) M.pass_(mailpasswd) .... Werner -- but I am getting error before that point and could not go to the user account or pass. M = poplib.POP3(mailserver) Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\lib\poplib.py", line 96, in __init__ raise socket.error, msg error: (10061, 'Connection refused') From fredrik at pythonware.com Fri Aug 15 03:35:21 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 15 Aug 2008 09:35:21 +0200 Subject: precedence of [] vs . In-Reply-To: <466f1a6b-d443-4803-8f9f-c10776dfa9f8@l42g2000hsc.googlegroups.com> References: <48390979-4759-43de-967c-8d9b712b61f7@l42g2000hsc.googlegroups.com> <15801a83-ddac-45ad-90e9-0d503f2bda73@d77g2000hsb.googlegroups.com> <466f1a6b-d443-4803-8f9f-c10776dfa9f8@l42g2000hsc.googlegroups.com> Message-ID: Carl Banks wrote: >> http://docs.python.org/ref/summary.html > > I think the summary is correct (am not going to bother to double- > check), but there's a subtle point you're missing. Here is a > simplified explanation. the rendered summary is broken; see my other post. From news1234 at free.fr Wed Aug 20 18:15:52 2008 From: news1234 at free.fr (nntpman68) Date: Thu, 21 Aug 2008 00:15:52 +0200 Subject: Negative integers In-Reply-To: References: Message-ID: <48ac9798$0$27334$426a74cc@news.free.fr> Hi, Dan's solution is probably the clearest. Just out of curiousity:. How would you in your program's context like 0 to be treated. should it be treated as a positive number or should it be treated as a case part. my suggestion a*b > 0 for example wouldn't work if you want 0 to be treated as positive number or if you compare 0 with 0 and want 'same sign' as answer bye N johnewing wrote: > I am trying to figure out how to test if two numbers are of the same > sign (both positive or both negative). I have tried > > abs(x) / x == abs(y) / y > > but that fails when one of the numbers is 0. I'm sure that there is > an easy way to do this. Any suggestions? > > Thanks From ricaraoz at gmail.com Wed Aug 20 09:19:02 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 20 Aug 2008 10:19:02 -0300 Subject: who to call a list of method inside the class itself In-Reply-To: References: <48ab30a4$0$12032$426a34cc@news.free.fr> Message-ID: <48AC19C6.5040309@bigfoot.com> Terry Reedy wrote: > > maduma at pt.lu wrote: >> Is the following code is ok. who to call all method. >> It is working but the call to m() without a reference to self seems >> strange > > The reference to self is bound to the methods by the way you look them up. > > >> class CustomMethod: >> def method1(self): >> .... >> def method2(self): >> .... >> def method3(self): >> .... >> >> def getAllMethod(self): >> return [self.method1, self.method2, self.method3] >> >> def applyAll(self): >> for m in self.getAllMethod(): >> m() > > If the list is static, there is no need to calculate it more than once, > at class-definition time. I might do this like so: > > class CustomMethod: > ... > all_methods = [method1, method2, method3] > def apply_all(self): > for m in self.all_methods: > m(self) > > Class code has access to the results of previous class code. > BTW, how would you guys go about registering the functions to be returned by apply_all()? I mean something like : class CustomMethod(object) : def __init__(self) : self.methodList = [] def method1(self) : ... self.registerMe(????send a reference to this method????) def method2(self) : ... self.registerMe(????send a reference to this method????) def registerMe(????receive a reference to some method????) : self.methodList.append(????the reference to the method????) def getAllMethods(self) : return self.methodList etc. From gminick at bzt.bzt Tue Aug 19 09:11:42 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Tue, 19 Aug 2008 13:11:42 +0000 (UTC) Subject: searching through a string and pulling characters References: <19039594.post@talk.nabble.com> Message-ID: On Mon, 18 Aug 2008 15:34:12 -0700 (PDT), Alexnb wrote: > Also, on a side-note, does anyone know a very simple dictionary site, that > isn't dictionary.com or yourdictionary.com. This one is my favourite: http://www.lingro.com/ -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From eliben at gmail.com Wed Aug 20 01:24:45 2008 From: eliben at gmail.com (eliben) Date: Tue, 19 Aug 2008 22:24:45 -0700 (PDT) Subject: exception handling in complex Python programs References: Message-ID: """ between file() and open() in Python 2 and 3, a NameError is thrown with open() in Python 3 and an IOError is thrown in the other three cases . """ This is *exactly* my concern with Python exceptions. You just never know what can be thrown at you. > You want to look up Easier to Ask Forgivness than Permission (EAFP) > which is touted as the "canonical" error-handling paradigm for Python. Any (semi)complete guides on this canonical paradigm online ? I've only found some references in maillist discussions. > ? def do_something(filename): > ? ? if not os.access(filename,os.R_OK): > ? ? ? return err(...) > ? ? f = open(filename) > ? ? ... > But does os.access cover absolutely all the errors that can happen during open() ? What guarantees it, and how can I know without you teaching me, just from the docs ? From michele.simionato at gmail.com Thu Aug 28 02:12:04 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 27 Aug 2008 23:12:04 -0700 (PDT) Subject: List of modules available for import inside Python? References: Message-ID: <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> On Aug 28, 6:21?am, ssecorp wrote: > Is there a way to view all the modules I have available for import > from within Python? > Like writing in the interpreter: Try: >>> help() help> modules Please wait a moment while I gather a list of all available modules... From eckhardt at satorlaser.com Wed Aug 6 04:39:48 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 06 Aug 2008 10:39:48 +0200 Subject: Locking around References: <87ej547vqs.fsf@nokile.rath.org> Message-ID: Nikolaus Rath wrote: > I need to synchronize the access to a couple of hundred-thousand > files[1]. It seems to me that creating one lock object for each of the > files is a waste of resources, but I cannot use a global lock for all > of them either (since the locked operations go over the network, this > would make the whole application essentially single-threaded even > though most operations act on different files). Just wondering, but at what time do you know what files are needed? If you know that rather early, you could simply 'check out' the required files, do whatever you want with them and then release them again. If one of the requested files is marked as already in use, you simply wait (without reserving the others) until someone releases files and then try again. You could also wait for that precise file to be available, but that would require that you already reserve the other files, which might unnecessarily block other accesses. Note that this idea requires that each access locks one set of files at the beginning and releases them at the end, i.e. no attempts to lock files in between, which would otherwise easily lead to deadlocks. Further, you could distinguish between read-only and read-write access as an optimisation. > My idea is therefore to create and destroy per-file locks "on-demand" > and to protect the creation and destruction by a global lock > (self.global_lock). For that, I add a "usage counter" > (wlock.user_count) to each lock, and destroy the lock when it reaches > zero. [...code...] > - Does that look like a proper solution, or does anyone have a better > one? This should work, at least the idea is not flawed. However, I'd say there are too many locks involved. Rather, you just need a simple flag and the global lock. Further, you need a condition/event that tells waiting threads that you released some of the files so that it should see again if the ones it wants are available. > - Did I overlook any deadlock possibilities? The normal deadlock possibilities when multiple locks are involved apply, you must make sure that they are always acquired in an order that prevents two threads waiting for a resource held by the other. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From jsmith1703 at aol.com Tue Aug 19 22:14:51 2008 From: jsmith1703 at aol.com (YouOverThere) Date: Tue, 19 Aug 2008 19:14:51 -0700 (PDT) Subject: IOError: decoder zip not available when using PIL Message-ID: <2362c6e2-1165-40ea-977a-f7056aab370b@o40g2000prn.googlegroups.com> I keep getting the error message "IOError: decoder zip not available" when using the Python Imaging Library. The error has occurred when trying to work with PNGs or JPEGs or when loading the fonts supplied with PIL. I can work with GIFs. I assume that I did something wrong when I built Python and/or PIL, but I'm at a loss as to what. I am running Python 2.5.1 with PIL 1.1.6 under SUSE Linux 10.2. I am stuck working on my own because our SysAdmin staff is loathe to install any Python packages. Thanks in advance! From Eric_Dexter at msn.com Fri Aug 22 05:13:14 2008 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Fri, 22 Aug 2008 02:13:14 -0700 (PDT) Subject: running exe file References: Message-ID: <5eaa72fa-fe51-4e45-ab02-d95a4c34d0f8@v1g2000pra.googlegroups.com> On Aug 22, 12:12?am, Saurabh Sharma wrote: > How can I run .exe file from my python script? import os os.startfile('file.exe') The downside is that it doesn't work on the mac.. but it does work on stuff like os.startfile('notepad.txt') I have been waiting for a good hacker to write a version to check what op system you have and then execute... I have more examples in my dex tracker package (use google) From stefan_ml at behnel.de Sun Aug 10 09:01:20 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 10 Aug 2008 15:01:20 +0200 Subject: Replace value of node using getElementsByTagName In-Reply-To: <2bc46eb6-d637-442f-b931-60f8f8fccad1@c58g2000hsc.googlegroups.com> References: <2bc46eb6-d637-442f-b931-60f8f8fccad1@c58g2000hsc.googlegroups.com> Message-ID: <489ee6a0$0$12942$9b4e6d93@newsspool2.arcor-online.net> Ouray Viney wrote: > Is there an easy way to replace the node value of ? Perhaps I am > trying to use the wrong python XML library? Looks like it. Try ElementTree. from xml.etree import ElementTree tree = ElementTree.parse("yourfile.xml") for ib in tree.findall("//ib"): ib.text = calculate_new_value(ib.text) Stefan From castironpi at gmail.com Sun Aug 24 10:02:09 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 24 Aug 2008 07:02:09 -0700 (PDT) Subject: property() usage - is this as good as it gets? References: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> Message-ID: On Aug 24, 5:00?am, alex23 wrote: > castironpi wrote: > > and we'll write Python. > > I haven't seen anything you've contributed to this group that would so > far be considered well-written Python. > > Confusing and border-line insane, yes. Pythonic? Not at all. > > Here's a tip: try actually developing some real-world application in > Python for a while, rather than the god-knows-what-you're-doing > attempts that you keep hijacking various threads with. Your code isn't > anywhere near as clever as you seem to think. Python isn't as clever as you think. It's a language. Do you want a link to clever code? I like to encourage creativity. From smanek at gmail.com Wed Aug 13 14:50:09 2008 From: smanek at gmail.com (shaneal) Date: Wed, 13 Aug 2008 11:50:09 -0700 (PDT) Subject: RPM Control from Python Message-ID: Hello, I'm trying to script some sysadmin stuff, that requires rpm manipulation (querying installed packages, removing packages, installing packages). Rather than manually parsing rpm's output, I noticed that someone had written python-bindings for the rpmlib library (called rpm-python). This seems much cleaner, but the documentation is sparse, and I haven't been able to get uninstalling to work. As root, I run the following: >>> import rpm >>> ts=rpm.ts() >>> ts.addErase("lynx") >>> I get no error messages/exceptions, but lynx is not removed. I've also tried things along the lines of: >>> mi = ts.dbMatch(rpm.RPMTAG_NAME, "lynx") >>> for idx in mi: ... instance = mi.instance() ... ts.addErase(instance) and >>> mi = ts.dbMatch(rpm.RPMTAG_NAME, "lynx") >>> for idx in mi: ... ts.addErase(idx) I've further confirmed that ts.dbMatch(rpm.RPMTAG_NAME, "lynx") does in fact find the header for the lynx package via something like: >>> mi = ts.dbMatch(rpm.RPMTAG_NAME, "lynx") >>> for hdr in mi: ... print hdr['name'], hdr['version'] ... lynx 2.8.5 The only real documentation I've been able to find is http://people.redhat.com/pnasrat/rpm-python/rpm-python-slides/frames.html Is there some other module I should be using for rpm manipulation? Or, if not, does anyone know what I'm doing wrong with this one? From mensanator at aol.com Tue Aug 26 19:16:55 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 26 Aug 2008 16:16:55 -0700 (PDT) Subject: Identifying the start of good data in a list References: <94524253-b946-4ffa-ae2e-ae6a555d4e7c@a1g2000hsb.googlegroups.com> Message-ID: <877a0a07-5dcd-4606-82ea-f5c87ac6b83e@m45g2000hsb.googlegroups.com> On Aug 26, 4:49?pm, tkp... at hotmail.com wrote: > I have a list that starts with zeros, has sporadic data, and then has > good data. I define the point at ?which the data turns good to be the > first index with a non-zero entry that is followed by at least 4 > consecutive non-zero data items (i.e. a week's worth of non-zero > data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, > 9], I would define the point at which data turns good to be 4 (1 > followed by 2, 3, 4, 5). > > I have a simple algorithm to identify this changepoint, but it looks > crude: is there a cleaner, more elegant way to do this? > > ? ? flag = True > ? ? i=-1 > ? ? j=0 > ? ? while flag and i < len(retHist)-1: > ? ? ? ? i += 1 > ? ? ? ? if retHist[i] == 0: > ? ? ? ? ? ? j = 0 > ? ? ? ? else: > ? ? ? ? ? ? j += 1 > ? ? ? ? ? ? if j == 5: > ? ? ? ? ? ? ? ? flag = False > > ? ? del retHist[:i-4] > > Thanks in advance for your help > > Thomas Philips Here's my attempt: LL = [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] i = 0 while (i Hi, I've used CTYPES module to access a function from a dll. This function provides me the version of the dll. This information is accessible to me as an array of 4 long inetegers. information as : 2, 1, 5, 0 I want to display these elements concatenated as "v2.1.5.0". This string ( I'm thinking of writing the above 4 array elements to a string) is to be displayed as label in a GUI ( the GUI used is Tk) Please suggest how can I write these elements to a string to get me the desired results as "v2.1.5.0". And, is writing to a string is right way? PS: this string also needs to be displayed in the GUI label well. FYI, the code written to access function from dll is as under: ******** from ctypes import * abc = windll.af1xEvdoRDll GetVersion = abc.af1xEvdoRDll_GetVersion print GetVersion versionArr = c_long * 4 version = versionArr(0, 0, 0, 0) GetVersion(version) print version for i in version: print i ************* Results are : 2, 1, 5, 0 Cheers, Rajat From bdesth.quelquechose at free.quelquepart.fr Wed Aug 13 12:11:20 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 13 Aug 2008 18:11:20 +0200 Subject: Calling "def" functions from another file. In-Reply-To: <8870982d-017b-418e-be50-5e46c463c1a4@8g2000hse.googlegroups.com> References: <8870982d-017b-418e-be50-5e46c463c1a4@8g2000hse.googlegroups.com> Message-ID: <48a3239c$0$29472$426a34cc@news.free.fr> frankrentef a ?crit : > Newbie here.... > > I'm writing a Python program that has "def" functionality functions > growing in > leaps and bounds. I'm a newbie to Python so be detailed. Is there a > way to create a py file with all the "def's" listed and just call them > from the "program" py file? yes. Put all your functions in a .py file, and import that file from the main 'program' file. > How would I do this? All this is in the FineManual(tm), here: http://docs.python.org/tut/node8.html I strongly suggest you read this first, experiment a bit, then come back here if you have any trouble or question. > Say my "def" py > file was named def.py Bad name. 'def' is a reserved word, so you can't name a module (a .py file) that way. From nodrogbrown at gmail.com Fri Aug 29 13:18:08 2008 From: nodrogbrown at gmail.com (gordon) Date: Fri, 29 Aug 2008 10:18:08 -0700 (PDT) Subject: Tkinter event loop question References: <9eaef6c3-c913-497f-8ca2-0466eb178c7a@z6g2000pre.googlegroups.com> Message-ID: <759a12fe-75c8-429a-9a64-19dc73a0b779@b30g2000prf.googlegroups.com> On Aug 29, 4:45 am, "Russell E. Owen" wrote: >your Controller object should not create root nor should > it call mainloop to start the event loop. guys thanks for the helpful replies..I rewrote the code as you advised. It creates a controller object and a gui object from main script.However i had to chain some method calls in my code.i am wondering if that can be avoided in some way. this is the sequence 1.user enters some value in the textfield,and clicks OKbutton 2.on OKbuttonclick ,the gui takes userinput value and quits eventloop.It then calls controller and pass the userinputvalue. 3.controller does some calculation(i shd have an external program to do calculation,but for simplicity i just wrote a method inside controller) with the given value,obtains the result and calls gui's updateDisplay(), passing the result value. 4.the gui creates the result as text on a canvas.then the mainloop() is called to resume event loop again user enters some value in the textfield,and clicks OKbutton ... I exit the application by clicking quitButton that calls destroy() on top level window. I tried my application by entering some value on text field and then clicking OKbutton ,the calculated result is displayed on canvas .I do this process say 3 times ..Then i click the Quit button and the window closes. I have put a print statement inside the gui's updateDisplay()method right after the resuming of event loop by parent.mainloop().This print statement gets printed as many times as i had clicked the OK button(here in this case 3 times).Is this due to clearing of the stack ? I feel that it was not a good design ..I would be grateful if someone would tell me how i could improve it..can those chaining of method calls be avoided? this is how i restructured the code moduleA.py ----------- import moduleB from Tkinter import Tk class MyController(object): def __init__(self): print "controller()" def validateSelection(self,userinputVal): if(userinputVal > 50 or userinputVal==0): userinputVal=50 self.doSomeCalculation(userinputVal) def doSomeCalculation(self,userinputVal): resultvalue=2*userinputVal +10 self.updateResults(resultvalue) def updateResults(self,resultvalue): self.myapp.updateDisplay(resultvalue); if __name__ == "__main__": controller=MyController() root = Tk() root.wm_title("MyUIApp") controller.myapp =moduleB.MyUI(root,controller) root.mainloop() moduleB.py ----------- from Tkinter import * class MyUI(object): def __init__(self, parent,controller): self.myParent = parent self.mainframe = Frame(parent,background="grey") self.mainframe.pack(fill=BOTH,expand=YES) self.controller=controller ....added a canvas and OK,QUIT buttons def okBtnClick(self): print "okBtnClicked" self.okButton.configure(state=DISABLED) userinputvalue = self.getUserInputValue() self.myParent.quit() #quits event loop self.controller.validateSelection(userinputvalue) def quitBtnClick(self): print "Quit Btn clicked" self.myParent.destroy() def updateDisplay(self,resultValue): message='result is='+str(resultValue) self.canvresult.delete(ALL) self.canvresult.create_text(1, 40, anchor=W, text=message, width=280) self.okButton.configure(state=NORMAL) self.myParent.mainloop() # resumes event loop print 'in updateDisplay():called mainloop' thanks gordon From arigo+google at codespeak.net Sat Aug 23 13:22:37 2008 From: arigo+google at codespeak.net (arigo+google at codespeak.net) Date: Sat, 23 Aug 2008 10:22:37 -0700 (PDT) Subject: Psycho question References: Message-ID: On Aug 8, 7:18 pm, "David C. Ullrich" wrote: > The one thing that puzzles me about > all the results is why // is so much slower than / inside > that Psyco loop. Just an oversight. The optimization about '/' between integers was not copied for the case of '//' between integers. Fixed in the svn head :-) Armin From elessar at nienna.org Sun Aug 17 15:23:08 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Sun, 17 Aug 2008 13:23:08 -0600 Subject: Good python equivalent to C goto In-Reply-To: <1a1eedf0-2164-4377-a77a-be105b37cceb@k37g2000hsf.googlegroups.com> References: <48a744b6$0$299$7a628cd7@news.club-internet.fr> <1a1eedf0-2164-4377-a77a-be105b37cceb@k37g2000hsf.googlegroups.com> Message-ID: <48A87A9C.1060407@nienna.org> info at orlans-amo.be wrote: > On Aug 17, 8:09 pm, Matthew Fitzgibbons wrote: >> Kurien Mathew wrote: >>> Hello, >>> Any suggestions on a good python equivalent for the following C code: >>> while (loopCondition) >>> { >>> if (condition1) >>> goto next; >>> if (condition2) >>> goto next; >>> if (condition3) >>> goto next; >>> stmt1; >>> stmt2; >>> next: >>> stmt3; >>> stmt4; >>> } >>> Thanks >>> Kurien >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> I would not be too happy if I saw C code like that in my repository. >> This is equivalent: >> >> while (loopCondition) { >> if (!(condition1 || condition2 || condition3)) { >> stmt1; >> stmt2; >> } >> stmt3; >> stmt4; >> >> } >> >> In Python: >> >> while (loopCondition): >> if not (condition1 or condition2 or condition3): >> stmt1 >> stmt2 >> stmt3 >> stmt4 >> >> If stmt3 and stmt4 are error cleanup code, I would use try/finally. >> >> while loopCondition: >> try: >> if condition1: >> raise Error1() >> if condition2: >> raise Error2() >> if condition3: >> raise Error3() >> stmt1 >> stmt2 >> finally: >> stmt3 >> stmt4 >> >> This will also bail out of the loop on and exception and the exception >> will get to the next level. If you don't want that to happen, put an >> appropriate except block before the finally. >> >> -Matt- Hide quoted text - >> >> - Show quoted text - > > class Goto_Target(Exception): > pass > > def Goto_is_not_dead(nIn): > try: > if (nIn == 1): raise Goto_Target > if (nIn == 2): raise Goto_Target > > inv = 1.0 / nIn > print 'Good Input ' + str(nIn) + ' inv=' + str(inv) > > except Goto_Target: > pass > except Exception, e: > print 'Error Input ' + str(nIn) + ' ' + str(e) > finally: > print 'any input ' + str(nIn) > > if __name__ == '__main__': > Goto_is_not_dead(0) > Goto_is_not_dead(2) > Goto_is_not_dead(3) > -- > http://mail.python.org/mailman/listinfo/python-list > I think this is needlessly ugly. You can accomplish the same with a simple if-else. In this case you're also masking exceptions other than Goto_Target, which makes debugging _really_ difficult. If you need to have the cleanup code executed on _any_ exception, you can still use try-finally without any except blocks. Your code is equivalent to this: def goto_is_dead(n): try: if n == 0 or n == 1 or n == 2: # if you're validating input, validate the input print "Error Input %s" % n else: print "Good Input %s inv= %s" % (n, (1. / n)) finally: print "any input %s" % n if __name__ == '__main__': goto_id_dead(0) goto_id_dead(2) goto_id_dead(3) More concise, readable, and maintainable. -Matt From tjreedy at udel.edu Fri Aug 1 17:06:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 01 Aug 2008 17:06:57 -0400 Subject: Strong/weak typing In-Reply-To: <6727fa22-aee9-4a9b-b9c0-08534aab6b34@m45g2000hsb.googlegroups.com> References: <6727fa22-aee9-4a9b-b9c0-08534aab6b34@m45g2000hsb.googlegroups.com> Message-ID: MartinRinehart at gmail.com wrote: > I'm writing Python as if it were strongly typed, never recycling a > name to hold a type other than the original type. Names are bound to objects with types. > Is this good software engineering practice, If you expand 'type' to 'category', then yes. > or am I missing something Pythonic? Most Python code is or could be generic. def sum(iterable,start): for item in iter(iterable): start += item return start Iterable can be any collection that is homogeneous with respect to the class of start and the operation of addition. And throughout my code, I never use 'iterable' for anything other that a homegeneous-for-the-purpose collection. I would never, for instance, bind it to a number. tjr From elessar at nienna.org Tue Aug 26 12:50:15 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Tue, 26 Aug 2008 10:50:15 -0600 Subject: Programmatically exit the REPL In-Reply-To: References: <288810.50426.qm@web7904.mail.in.yahoo.com> Message-ID: <48B43447.60700@nienna.org> Alexander Schmolck wrote: > Without reading your post properly or having tried to do the same thing > myself: I think you might want to have a look at ipython; it gives a better > REPL and "embedding ipython" should give you plenty of hits as well. > Thanks for the tip; I hadn't heard of ipython before. I will certainly check it out. However, if anyone knows how to break out of the interactive interpreter from another thread, I'd still very much like to hear about it. :) -Matt From ewertman at gmail.com Sat Aug 30 21:32:18 2008 From: ewertman at gmail.com (Eric Wertman) Date: Sat, 30 Aug 2008 21:32:18 -0400 Subject: Writing to ms excel In-Reply-To: References: Message-ID: <92da89760808301832o716d89e2s138d5f46b91645d2@mail.gmail.com> Yes sorry, that's a really poorly formed sentence all the way around... not a dig on xlrd, but a warning to the OP that they may not find what they are looking for there. > On Aug 31, 12:57 am, "Eric Wertman" wrote: >> If you have >> to interface with an exsisting excel file, you can try http://pypi.python.org/pypi/xlrd, but it may not support writing xls >> files, still. > > That remark appears to be an inverted cousin of the old joke question > "Have you stopped beating your wife?" :-) From thomasmallen at gmail.com Thu Aug 14 09:54:15 2008 From: thomasmallen at gmail.com (tmallen) Date: Thu, 14 Aug 2008 06:54:15 -0700 (PDT) Subject: An FTP Client...My first real program! References: <228e4214-01cf-4152-acdb-3743594f0581@e53g2000hsa.googlegroups.com> Message-ID: On Aug 13, 11:53?pm, "Python Nutter" wrote: > sorry cut off due to original email being sent not to the list due to gmail: > > A second for that suggestion--the ftp module in the python standard library is > very low level and not very useful for beginners as a lot of the heavy > lifting and management is still left up to you, the programmer. > > 2008/8/14 Python Nutter : > > > ery low level and not very useful for beginners as a lot of the heavy > > lifting and management is still left up to you, the programmer. > > > The module ftputil is a high-level interface to the ftplib module. The > > FTPHost objects generated from it allow many operations similar to > > those of os and os.path. An example: > > > # download some files from the login directory > > host = ftputil.FTPHost('ftp.domain.com', 'user', 'secret') > > names = host.listdir(host.curdir) > > for name in names: > > ? if host.path.isfile(name): > > ? ? ? host.download(name, name, 'b') ?# remote, local, binary mode > > # make a new directory and copy a remote file into it > > host.mkdir('newdir') > > source = host.file('index.html', 'r') ?# file-like object > > target = host.file('newdir/index.html', 'w') ?# file-like object > > host.copyfileobj(source, target) ?# similar to shutil.copyfileobj > > source.close() > > target.close() > > > Now if you are again purely in it for a challenge or for and > > educational roller coaster ride, ignore the suggestion to look at > > higher level ftp modules =) > > > Cheers, > > PN > > What work, specifically, am I duplicating? I have my eyes on a larger application, so if this part can easily be taken care of, I'm all ears. From sjmachin at lexicon.net Wed Aug 27 20:48:25 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 27 Aug 2008 17:48:25 -0700 (PDT) Subject: finding out the number of rows in a CSV file [Resolved] References: <3aaa109e-9a7e-4d02-8af5-0161251d7678@t54g2000hsg.googlegroups.com> <0bc6097f-af52-4951-a413-e9a983df93c7@79g2000hsk.googlegroups.com> Message-ID: <59b93881-47e6-4108-87ca-074f23df48b0@v39g2000pro.googlegroups.com> On Aug 28, 7:51 am, norseman wrote: > Peter Otten wrote: > > John S wrote: > > >> [OP] Jon Clements wrote: > >>> On Aug 27, 12:54 pm, SimonPalmer wrote: > >>>> after reading the file throughthe csv.reader for the length I cannot > >>>> iterate over the rows. How do I reset the row iterator? > >> A CSV file is just a text file. Don't use csv.reader for counting rows > >> -- it's overkill. You can just read the file normally, counting lines > >> (lines == rows). > > > Wrong. A field may have embedded newlines: > > >>>> import csv > >>>> csv.writer(open("tmp.csv", "w")).writerow(["a" + "\n"*10 + "b"]) > >>>> sum(1 for row in csv.reader(open("tmp.csv"))) > > 1 > >>>> sum(1 for line in open("tmp.csv")) > > 11 > > > Peter > > -- > >http://mail.python.org/mailman/listinfo/python-list > > ============================= > Well..... a semantics's problem here. > > A blank line is just an EOL by its self. Yes. Or a line containing blanks. Yes what? > I may want to count these. Could be indicative of a problem. If you use the csv module to read the file, a "blank line" will come out as a row with one field, the contents of which you can check. > Besides sum(1 for len(line)>0 in ...) handles problem if I'm not > counting blanks and still avoids tossing, re-opening etc... What is "tossing", apart from the English slang meaning? What re-opening? > > Again - it's how you look at it, but I don't want EOLs in my dbase > fields. Most people don't want them, but many do have them, as well as Ctrl-Zs and NBSPs and dial-up line noise (and umlauts/accents/suchlike inserted by the temporarily-employed backpacker to ensure that her compatriots' names and addresses were spelled properly) ... and the IT department fervently believes the content is ASCII even though they have done absolutely SFA to ensure that. > csv was designed to 'dump' data base fields into text for those > not affording a data base program and/or to convert between data base > programs. By the way - has anyone seen a good spread sheet dumper? One > that dumps the underlying formulas and such along with the display > value? That would greatly facilitate portability, wouldn't it? (Yeah - > the receiving would have to be able to read it. But it would be a start > - yes?) Everyone got the point? Just because it gets abused doesn't > mean .... Are we back on track? Number of lines equals number of > reads - which is what was requested. No bytes magically disappearing. No > slight of hand, no one dictating how to or what with .... > > The good part is everyone who reads this now knows two ways to approach > the problem and the pros/cons of each. No loosers. IMHO it is very hard to discern from all that ramble what the alleged problem is, let alone what are the ways to approach it. From ryanlists at gmail.com Thu Aug 7 11:11:24 2008 From: ryanlists at gmail.com (Ryan Krauss) Date: Thu, 7 Aug 2008 10:11:24 -0500 Subject: problem calling parent's __init__ method Message-ID: I am trying to call a parent's __init__ method from the child's: class ArbitraryBlock(InnerBlock): def __init__(self, codelist, noout=False, **kwargs): InnerBlock.__init__(self, codelist, noout=noout, **kwargs) I get this error: : unbound method __init__() must be called with InnerBlock instance as first argument (got ArbitraryBlock instance instead) I found a thread that talked about the parent and child being different types, so I tried setting up the parent class 3 different ways: class InnerBlock: class InnerBlock(object): class InnerBlock(empty_class): where class empty_class(object): def __init__(self,_d={},**kwargs): kwargs.update(_d) self.__dict__=kwargs I still get the same error. Why doesn't this work? Thanks, Ryan From 4564 at 755189.45 Thu Aug 7 03:49:59 2008 From: 4564 at 755189.45 (Enrico) Date: Thu, 7 Aug 2008 09:49:59 +0200 Subject: Using an DTD not specified in XML file for validation References: <87ej547vqs.fsf@nokile.rath.org> <87y73aa3se.fsf@nokile.rath.org><87sktia0uf.fsf@nokile.rath.org> <1836659a-99e9-4b51-953d-b5622c22fec5@k37g2000hsf.googlegroups.com><87prom9vcu.fsf@nokile.rath.org> Message-ID: <489aa952$0$1079$4fafbaef@reader2.news.tin.it> "Brian Quinlan" ha scritto nel messaggio news:mailman.1200.1218043709.922.python-list at python.org... > Hey, > > I'm trying to figure out how I can validate an XML file using a DTD that > isn't specified in the XML file. I did it once using lxml. You can read from: http://codespeak.net/lxml/validation.html With this package is quite simple (code not tested): from lxml import etree dtd = etree.DTD('mydtd.dtd') f = file('mydoc.xml') xml = etree.XML(f.read()) dtd.validate(xml) Enrico From steve at REMOVE-THIS-cybersource.com.au Fri Aug 22 20:52:14 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 23 Aug 2008 00:52:14 GMT Subject: Generators can only yield ints? References: Message-ID: <00bf5a06$0$20312$c3e8da3@news.astraweb.com> On Fri, 22 Aug 2008 15:44:15 -0700, defn noob wrote: > def letters(): > a = xrange(ord('a'), ord('z')+1) > B = xrange(ord('A'), ord('Z')+1) > while True: > yield chr(a) > yield chr(B) > > >>>> l = letters() >>>> l.next() > > Traceback (most recent call last): > File "", line 1, in > l.next() > File "", line 5, in letters > yield chr(a) > TypeError: an integer is required >>>> >>>> > > Any way to get around this? Yes, write code that isn't buggy :) Generators can return anything you want. Your problem is that you're passing an xrange object to chr() instead of an int. Try this: def letters(): a = xrange(ord('a'), ord('z')+1) B = xrange(ord('A'), ord('Z')+1) for t in zip(a, B): yield chr(t[0]) yield chr(t[1]) But (arguably) a better way is: def letters(): from string import ascii_letters as letters for a,b in zip(letters[0:26], letters[26:]): yield a yield b Note that it is important to use ascii_letters rather than letters, because in some locales the number of uppercase and lowercase letters differ. -- Steven From dudeja.rajat at gmail.com Sun Aug 17 10:25:29 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sun, 17 Aug 2008 10:25:29 -0400 Subject: Windows / Tkinter - problem with grid - not able to place widgets at desired places Message-ID: Hi, I'm learning Python and Tkinter. I've started programming in Eclipse with PyDev. I'm intending to create a GUI. I'm not able to understand the Grid manager perhaps because there is quite a less documentation available for it on the net. My desired GUI is attached in the mail. Although I've tried writing a class module for this GUI but I'm not able to set all things right in the GUI. The Biggest problem seems to be with the Grid Manager in terms how it divides a window in Rows / columns. etc. I'm not able to place none of the widgets correctly in the GUI. For your convenience, I'm attaching this code also as myModule1.py . Please some one review it and help create me this GUI. PS: The desired GUI is attached as a GIF file. The version v1.4.5.1 is a label the contents of which are dynamically picked. Thanks and regards, Rajat -------------- next part -------------- A non-text attachment was scrubbed... Name: Desired GUI.GIF Type: image/gif Size: 21640 bytes Desc: not available URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: myModule1.py URL: From __peter__ at web.de Mon Aug 25 09:45:49 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 25 Aug 2008 15:45:49 +0200 Subject: Python String Immutability Broken! References: <000b01c906f1$a493bb80$0d00a8c0@hendrik> <00c2a9b1$0$20312$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Mon, 25 Aug 2008 03:43:01 -0700, Ken Seehart wrote: > >> You can also use ctypes to globally change the value of integers less >> than 101. Personally, I don't particularly like the number 14. I >> changed it to 9 and I am much happier now. > > Okay, you've got me curious. How do you do that, and why only up to 101? Up to 256 in current Python. Small integers are shared to save memory. After a quick look into the ctypes tutorial and the python source I came up with # 64-bit linux >>> from ctypes import * >>> libc = cdll.LoadLibrary("libc.so.6") >>> libc.memset(id(14)+16, 0, 8) 7742336 >>> 14 0 >>> 14 == 0 True Peter From castironpi at gmail.com Tue Aug 26 00:11:24 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 25 Aug 2008 21:11:24 -0700 (PDT) Subject: Return a string result with out breaking loop References: Message-ID: <631fff4c-0332-427f-9a1f-9ce7f47788ff@k7g2000hsd.googlegroups.com> On Aug 25, 6:37?pm, Andrew wrote: > Hi I was wondering if there is anyway with XML RPC to send a string of > text from the server to the client with out calling return thus breaking > ? my loop > > for example > > ? def somefunc(): > ? ? ? ?for action, files in results: > ? ? ? ? ? ? ? ?full_filename = os.path.join(path_to_watch, files) > ? ? ? ? ? ? ? ?theact = ACTIONS.get(action, "Unknown") > ? ? ? ? ? ? ? ?out2 = ?str(full_filename) + ?" " + str(theact) > ? ? ? ? ? ? ? ?return out2 > > the return statement will return a result breaking my loop. My goal is > to have it continue looping and updating the client > > any ideas? > > Cheers > > Andrew > > Thanks in advance > > Pyhon 2.5.2 > > Windows XP Andrew, I have generators working on both sides of a SimpleXMLRPCServer instance. You ask for a server-side generator, and I won't post the whole program, as it's long, so here's an important part: server = SimpleXMLRPCServer(("localhost", 8000)) server.register_introspection_functions() def gen( ): while 1: yield 1 yield 2 yield 3 servg= gen( ) server.register_function( servg.next, 'gen' ) Called 's.gen( )' four times, output: localhost - - [25/Aug/2008 23:08:28] "POST /RPC2 HTTP/1.0" 200 - 1 localhost - - [25/Aug/2008 23:08:29] "POST /RPC2 HTTP/1.0" 200 - 2 localhost - - [25/Aug/2008 23:08:30] "POST /RPC2 HTTP/1.0" 200 - 3 localhost - - [25/Aug/2008 23:08:31] "POST /RPC2 HTTP/1.0" 200 - 1 As expected. I guess that your problem was on this line: server.register_function( servg.next, 'gen' ) where instead you just wrote server.register_function( servg, 'gen' ) #wrong or perhaps even server.register_function( gen, 'gen' ) #wrong I'll offer an explanation of the difference too, for the asking. From deets at nospam.web.de Thu Aug 28 09:10:45 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 28 Aug 2008 15:10:45 +0200 Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> <6fe0scFaus40U1@mid.uni-berlin.de> <6bc8bc07-eab0-4303-b8a4-c9470f96038d@c65g2000hsa.googlegroups.com> <6fe1n2Faus40U3@mid.uni-berlin.de> <6ff0ifFbbpfbU1@mid.uni-berlin.de> Message-ID: <6hnmffFn5mm9U1@mid.uni-berlin.de> > Zen's lesson for today: > THOU SHALT NOT MESS WITH ANY PYTHON'S SEMI-GODS, DEMI-GODS, AND > PYTHON'S GOD. > > You're lucky Diez still want to help you with your attitude like that. > May I remind you that we here helps you for free in our free time, be > rude, especially to a frequent member, and you'll get what you deserve. Thanks Lie, but I certainly don't consider myself being part of Python's olymp... :) Others here of course are, and a friendly and open attitude from everybody sure helps keeping this institution helpful. This goes also for frequent members - and I do include myself here, as I *sometimes* forget that myself, but try hard not to. Diez From deets at nospam.web.de Tue Aug 26 12:15:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Aug 2008 18:15:33 +0200 Subject: Are dictionaries the same as hashtables? References: <6hi153Fliuu4U1@mid.uni-berlin.de> Message-ID: <6hioi7Fmdo37U1@mid.uni-berlin.de> Cameron Laird wrote: > In article <6hi153Fliuu4U1 at mid.uni-berlin.de>, > Diez B. Roggisch wrote: >>Martin Marcher wrote: >> >>> On 2008-08-26 00:32:20, cnb wrote: >>>> Are dictionaries the same as hashtables? > . > . > . >>Python does not have a "one key maps to a list of values"-semantics - >>which I consider the sane choice... >> >>However, you can have that using the defaultdict for example: >> >>listdict = defaultdict(list) >> >>listdict[key].append(value) >> >>Diez > > ? I'm lost. As I understand your terms, Python's dictionaries > map keys to objects, but you would prefer that Python's > dictionaries map keys only to lists of values. That *sounds* > like a complexification, at best. Are you trying to make a > point about implementation aligning with semantics? The OP seems to want that (or at least sees it as one of two viable design choices), see his other answer in this thread. I certainly *don't* agree with that, I merely pointed out that python comes with means to easily create such a data-structure in the case it is needed. Diez From castironpi at gmail.com Mon Aug 25 01:49:52 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 24 Aug 2008 22:49:52 -0700 (PDT) Subject: property() usage - is this as good as it gets? References: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> <9dc512a3-a0ba-461a-a242-c2681b7db42e@a8g2000prf.googlegroups.com> <7098004b-3bc2-4740-870d-ce32ab81bf6c@25g2000prz.googlegroups.com> Message-ID: On Aug 24, 10:41?pm, alex23 wrote: > On Aug 25, 12:42?pm, castironpi wrote: > > > I'm baffled. ?I don't understand what you write. ? > > Which is pretty much how I feel about -all- of your posts. Alright. You're articulate. I'm getting a better picture of what your problem with me is. What we have is a misunderstanding, *not a war*. If you think I leave the grounds of civil argument, be sure to say so. Otherwise, I'll expect observation, premise, conclusion. Just like a good A.I. would. (Computers are good at something, and that's logic.) > > I think someone in > > my shoes would be justified in dismissing it as either malicious or a > > miscommunication. ? > > No, it's frustration at the sharp decrease in signal:noise that this > newsgroup has undertaken since your arrival. You also want to assign causality and/or blame as a result. The evidence is circumstantial. I'm sorry you're frustrated. If I've had a negative influence, which is hard to prove, that would mean that I'm influential (in the bad way). I'm not sure I can accept that at this point in my life. It's a problem. But I also feel that I've been plonked without hearing me out, which only escalates the frustration. (Google search castironpi+plonk. Ha.) > But how about this, your code snippet from this very thread, > your -first- of two seemingly independent replies to the original > post: > > > ?def _getbalance( self ): > > ? ?return self._tree.geti( > > ? ? ?self.where+ self.lookup[ 'balance' ] ) > > > ?def _getparent( self ): > > ? ?return self._tree.getI( > > ? ? ?self.where+ self.lookup[ 'parent' ] ) > > > Where 'balance' and 'parent' could both come from something generic: > > > balance= property( tree_lookup( 'balance' ) ) > > parent= property( tree_lookup( 'parent' ) ) > > In your 'example', you reference one marked-as-implementation > attribute, two unspecified attributes, one unspecified method and one > unspecified function. That you refer to one function as both 'geti' > and 'getI' leads me to believe this -isn't- workable code and you've > just re-keyed this in without testing. It is from real code. If you want the link say so. It's an in-place memory manager that I think is quite nifty... *and* functional. *And* pure Python. Others earlier proposed similar things; mine was just more specialized. Miles: x = defaultproperty('_x') y = defaultproperty('_y') Medardo: x = property(*attrmanager('_x')) y = property(*attrmanager('_y')) I see a similarity between theirs and mine, but you only criticize mine. Do you agree that mine was similar? If I would have said, "Where 'balance' and 'parent' both share something generic", instead of "could both come from something generic", would that have made more sense? That would definitely be my fault. Word choice is definitely a weakness and I am not perfect. > I've also -no- idea what you're trying to demonstrate here. It's not > clear nor obvious, and I can't see how your _getwhatever methods tie > in with the property definition. My point was, "Here's one snippet you could clear up with some abstraction." It answers the OP's question directly: "It works well enough, but I can't help feeling there a cleaner more readable way of doing this (with less duplication, etc). Is this as good as it gets?" But I did not organize my post well, so I can see your confusion. > > For instance, "I won't like it if you do" and "I won't think it's > > clever if you do" aren't consistent belief structures, they're fight > > structures. ?You have made such claims. > > No, what I've stated is I've yet to see -any- code samples that you've > provided be of any real, clear use to -anyone-. This isn't a 'fight > structure', this is an opinion formed by the overwhelming amount of > evidence you keep contributing to this group. I'm lost. Do you want to see some clever code, even if I wrote it, and even if I think it is clever too? I am wanting a code review. > > In the post above, I make two claims, ask two questions, and encourage > > a brainstorm. ?I don't see how what you say applies to it. > > What you said was: "When brainstorming, don't restrict yourself to > Python syntax-- make > something up, and we'll write Python." > > What I'm contesting is your ability to write Python. > > Furthermore, people -aren't- posting questions to the "castironpi > hour", they're asking questions to help further their understanding of > Python, not to give you further opportunity to emphasise your > misunderstanding of it. Suggesting they 'brainstorm' without any > understanding of the language itself and that you'll somehow magically > generate Python code for them is, based on what you've written here, > laughable. No, and this is not my editorial, blog, or advice column, no matter how much I write. Brainstorming is healthy and productive. The OP was looking for a way to improve something he'd written and was already working. I was urging him to think outside the box, then get help getting back "in to the box," metaphorically. This is different than inviting someone to brainstorm who is asking for help with the 'range' function, you know. Python makes a lot of things possible that other languages don't, and I don't believe that anyone knows the extent of that. > > I am willing to change the way I communicate. ?I want to communicate > > effectively. ?But, until someone takes something I want to say, and > > says it the right way, I can't learn how. ?So I wait and write Python, > > and share my frustration with my peers. > > Given how many people have publicly killfiled you on this group, I'm > not sure who you consider to be your 'peers'. There was a -lot- of > initial frustration at your post, along with even more dismissal of it > as the output of a poorly written AI experiment. YES, no kidding. I'm amazed myself, but I just chalk it up to my being new on Usenet and bad with people. I'll work on it but Rome wasn't built in a day. My peer is someone who is bad at communicating. How am I supposed to establish communication with him or her? > You're -failing- the Turing test. If that isn't telling you something > is wrong with your communication style, I don't really know what will. I am aware, thanks to the group, that something is wrong. But I don't know what it is. > Assumed by someone... [snip, ok?] > Which leads me to reiterate my original statement, only framing it now > as a question: what -real world- applications or systems have you > worked on...in -any- language? I find it difficult to believe you've > ever worked on any, or even more pointedly, had to work on -someone > else's real world code-. Because the sample code fragments you post, > when not broken, at best seem to relate to pointless wankery on your > behalf, without any practical application whatsoever, and at worst > carry deep-seated misunderstandings about how Python works. Most of my programming is either academic research, academic study, or hobbyist. If you're asking if I have any experience, yes I do. If you're asking whether I've been forced to write awful code under someone else's deadline, no I haven't. That's important. I don't know what trait that gives my code, maybe abstractness, but no my experience is not typical. And the academic research wasn't for the business colleges either. If you want my credentials, e-mail me. I went to a 4-year Research 1, but I believe that people's work should speak for itself. My offer stands to show you my code. Probably not my resume or work history though. Fair? Lastly, if I spend too much time on the newsgroup (300 in February, wow), that is, on this one newsgroup, it's important to bring that to my attention. That is not something that anyone can judge for themselves. (A famous philosopher contends that friends are the harshest critics.) It is Ok to have that opinion and it's ok if you notice it; that doesn't automatically mean you do too. I could use a kick in the rear to branch out, and perhaps diversify my time. I think I would find it most productive to point-blank say so. From gzlist at googlemail.com Tue Aug 26 11:20:05 2008 From: gzlist at googlemail.com (Martin (gzlist)) Date: Tue, 26 Aug 2008 16:20:05 +0100 Subject: [ctypes-users] ctypes - loading 'librsvg-2-2.dll' In-Reply-To: <48B3B8B3.5070309@sil.org> References: <48B3B8B3.5070309@sil.org> Message-ID: On 26/08/2008, Tim Grove wrote: > Any ideas why a particular dll won't load on Windows XP Pro using > ctypes? I'm going to take a stab in the dark here and suggest it's because you have multiple (different) copies of iconv.dll on your PATH. > l=CDLL(r'D:\SILSign\librsvg-2-2.dll') > Traceback (most recent call last): > File "", line 1, in > File "C:\PYTHON25\LIB\ctypes\__init__.py", line 349, in __init__ > self._handle = _dlopen(self._name, mode) > WindowsError: [Error 127] The specified procedure could not be found I get this on my current setup, where I've been messing around trying to recompile lynx against iconv. I also get a popup saying "The procedure entry point libiconv_set_relocation_prefix could not be located in the dynamic link library iconv.dll." Doing this worked for me: C:\>set PATH=C:\Program Files\Common Files\GTK\2.0\bin C:\>"C:\Python24\python.exe" -c "import ctypes; print ctypes.CDLL('librsvg-2-2')" Change the paths to your equivalents and try it, see if you have the same or a similar dependency problem. Martin From mathieu.prevot at ens.fr Thu Aug 21 01:41:54 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Thu, 21 Aug 2008 07:41:54 +0200 Subject: subprocess seems to "detach" / ignore wait() In-Reply-To: References: Message-ID: <3e473cc60808202241j2825bc3cl7f1050f1ec68563b@mail.gmail.com> 2008/8/20 Gabriel Genellina : > En Wed, 20 Aug 2008 12:22:16 -0300, Wojtek Walczak escribi?: > >> On Wed, 20 Aug 2008 15:09:11 +0200, Mathieu Prevot wrote: >> >>> child = Popen(cmd.split(), stderr=flog) >>> print "Server running [PID %s]"%(child.pid) >>> fpid.write(child.pid) >> >> I think that the problem here is that fpid.write() fails silently >> (probably TypeError), because it takes string as its first argument, >> not integer. > > Exactly, but it doesn't fail "silently" (that would be a bug). The exception is raised, but due to the finally clause ending in sys.exit(0), it has no chance of being handled. > This is the original code, for reference: > > flog = open(logfile, 'w') > fpid = open(pidfile, 'w') > try: > child = Popen(cmd.split(), stderr=flog) > print "Server running [PID %s]"%(child.pid) > fpid.write(child.pid) > child.wait() > except KeyboardInterrupt: > print "INT sent to vnc server" > finally: > fpid.close() > flog.close() > os.remove(pidfile) > os.remove(logfile) > sys.exit(0) > > -- > Gabriel Genellina Indeed, I got TypeError: argument 1 must be string or read-only character buffer, not int and Wojtek's code works. So what is the right thing to do so my script returns 1 or 0 depending on its state and success ? Mathieu From harrrrpo at gmail.com Mon Aug 25 12:57:04 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Mon, 25 Aug 2008 19:57:04 +0300 Subject: QT 4.4 and timedelta In-Reply-To: References: Message-ID: <538050a90808250957j573f7a0ascf21aa0f9179c81e@mail.gmail.com> I'm not very sure about this , but it's logicallay enough to be said i think the QTableView ordering mechanism must provide some overriding functionality through accepting a comparing function from you check it On Mon, Aug 25, 2008 at 7:48 PM, admoore wrote: > Maybe I'm missing something obvious, but is there a QT object to > represent time intervals, a la datetime.timedelta? > > I'm working on a utility that displays database query results from a > postgres database (using psycopg2) in a QTableView. For columns > created using "age(some_date_column)", I get a datetime.timedelta > object from psycopg2. > > What I'd like is to be able to format this column in a friendly way > (say "7 years, 2 months, 4 days"), yet have the QTableView treat it > properly (e.g. for sorting purposes, not sorting it lexically but by > the actual length of time). > > Anyone have any input or ideas on this? > -- > http://mail.python.org/mailman/listinfo/python-list > From castironpi at gmail.com Thu Aug 21 13:50:11 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 21 Aug 2008 10:50:11 -0700 (PDT) Subject: getattr() on nested functions? References: <48abe483$0$31875$426a74cc@news.free.fr> <48AC322E.9000404@arimaz.com> <48ad5980$0$4634$426a74cc@news.free.fr> <48ad8631$0$3819$426a74cc@news.free.fr> Message-ID: <8f3774ac-2c90-4a7a-a3d8-e39bcd8738cd@79g2000hsk.googlegroups.com> On Aug 21, 10:14?am, Bruno Desthuilliers wrote: > Gabriel Rossetti a ?crit : > > > > > Bruno Desthuilliers wrote: > >> Gabriel Rossetti a ?crit : > >>> Terry Reedy wrote: > >> (snip) > >>>> Unlike the class approach, this requires recreating the constant > >>>> functions and dict with each call to _test. ?Quick to write but a > >>>> bit 'dirty', in my opinion. ?Another standard idiom is to set up the > >>>> constants outside the function: > > >>>> def request(params): > >>>> ? ? pass > >>>> def submit(params, values): > >>>> ? ? pass > >>>> def update(params, values): > >>>> ? ? pass > >>>> def delete(params): > >>>> ? ? pass > >>>> dispatch = {'request':request, 'submit':submit, 'update':update, > >>>> 'delete':delete} > > >>>> def _test(self, action, *args): > >>>> ? ? return resultToXmo(dispatch[action](*args)) > > >>> That's how I had done it originally (before the use of eval()), but > >>> in this case also, since the functions are still nested, > > >> Uh ??? You probably want to re-read the above code snippet. > > > Uh...yes, I didn't see the external/parent function was no longer there. > > I prefer to nest mine though because I have several parent functions for > > different tasks, so each child/nested function has a diff. > > implementation, I find that cleaner than having n*4+n top-level > > functions (+ n dicts), e.g. I prefer this : > > > ? ?def __task1(self, action, *args): > > ? ? ? ?def request(params): > > ? ? ? ? ? ?pass > > ? ? ? ?def submit(params, values): > > ? ? ? ? ? ?pass > > ? ? ? ?def update(params, values): > > ? ? ? ? ? ?pass > > ? ? ? ?def delete(params): > > ? ? ? ? ? ?pass > > ? ? ? ?return resultToXml(locals()[action](*args)) > > > ? ?def __task2(self, action, *args): > > ? ? ? ?def request(params): > > ? ? ? ? ? ?pass > > ? ? ? ?def submit(params, values): > > ? ? ? ? ? ?pass > > ? ? ? ?def update(params, values): > > ? ? ? ? ? ?pass > > ? ? ? ?def delete(params): > > ? ? ? ? ? ?pass > > ? ? ? ?return resultToXml(locals()[action](*args)) > > > over this : > > (snip) > > > I could use your callable approach, but like you said it may not be > > worth the trouble. > > The "trouble" I was talking about was not with using callable objects, > but with trying to hack func.func_code to extract nested functions (if > ever possible). > > But anyway... The point of using callable objects is to avoid going thru > the whole "setup" part again and again and again. Now if all your task > functions only differ by the dispatch dict, there's at least another > ways to avoid this runtime repetition - as well as coding repetition > FWIW (warning : untested code): > > def _make_task(func): > ? ? ?dispatch = func() > ? ? ?def _task(action, *args): > ? ? ? ? ?return resultToXml(dispatch[action](*args)) > ? ? ?_task.__name__ = _task.func_name = func.__name__ > ? ? return _task > > @_make_task > def _task1(): > ? ? ?def request(params): > ? ? ? ? ?pass > ? ? ?def submit(params, values): > ? ? ? ? ?pass > ? ? ?def update(params, values): > ? ? ? ? ?pass > ? ? ?def delete(params): > ? ? ? ? ?pass > ? ? ?return locals() > > HTH Here's more ideas: Use a wrapper to give the function access to itself as an object: @auto def f( self, arg ): assert self== f In your original example: @auto def toto( toto ): def titi(): pass f = getattr(toto, "titi") print str(f) Should work, untested. Another is to use a wrapper to participate functions in a dictionary: @entry( 'a' ) def a( arg ): a_stuff( ) @entry( 'b' ) def b( arg ): b_stuff You could even make 'entry' a class instance, so you can specialize and vary it in other cases, untested. Last one is just use a class, untested: class __Test: def __test(self, action, *args): result = getattr(self, action)(*args) return resultToXml(result) def request(self,params): pass def submit(self,params, values): pass def update(self,params, values): pass def delete(self,params): pass Keep us posted which one works for you. From alexis.boutillier at arteris.com Fri Aug 29 03:48:59 2008 From: alexis.boutillier at arteris.com (Alexis Boutillier) Date: Fri, 29 Aug 2008 09:48:59 +0200 Subject: Syntax error in ".py" file and globals variable values not available. In-Reply-To: References: <48B5232D.6080205@arteris.com> <48B6647F.8090402@arteris.com> Message-ID: <48B7A9EB.4020003@arteris.com> Timothy Grant a ?crit : > On Thu, Aug 28, 2008 at 1:40 AM, Alexis Boutillier > wrote: >> Timothy Grant a ?crit : >>> On Wed, Aug 27, 2008 at 2:49 AM, Alexis Boutillier >>> wrote: >>>> Hi, >>>> >>>> I have a strange behaviour of python with pdb and import statement. >>>> Here is the example code : >>>> >>>> file my1.py: >>>> import my2 >>>> >>>> file my2.py: >>>> a=5 >>>> toto >>>> >>>> I intentionnaly put a syntax error in file my2.py. >>>> >>>> If I run "python -i my2.py" and run pdb I got : >>>> NameError: name 'toto' is not defined >>>>>>> import pdb >>>>>>> pdb.pm() >>>> -> toto >>>>>>> print a >>>> 5 >>>> >>>> If I run "python -i my1.py" and run pdb I got : >>>> NameError: name 'toto' is not defined >>>>>>> import pdb >>>>>>> pdb.pm() >>>> -> toto >>>>>>> print a >>>> None >>>> >>>> Why can't I get access to variable a in pdb when the process generating >>>> the >>>> error came from an import statement ? >>>> >>>> With python 2.3.5, it works fine and in the two cases I get the correct >>>> value of 5 for variable "a". >>>> with python 2.43,2.5.1,2.5.2, it doesn't work and I get "None" value for >>>> variable a. >>>> >>>> Somebody can explain me this behaviour ? >>>> >>>> >>>> Thanks. >>>> -- >>>> Boutillier Alexis >>>> Methodology engineer >>>> >>>> Arteris SA >>>> The Network-on-Chip Company TM >>>> www.arteris.net >>>> >>>> 6 par Ariane Immeuble Mercure >>>> 78284 Guyancourt Cedex >>>> France >>>> Office: (+33) 1 61 37 38 71 >>>> Fax: (+33) 1 61 37 38 41 >>>> Alexis.Boutillier at arteris.net >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>>> >>> >>> Because of the syntax error the module wasn't loaded. >>> >>> What kind of behaviour would you expect on code that has been flagged >>> as not executable? >>> >> I got the same behaviour with : >> file my2.py: >> a=5 >> raise SystemError,"" >> >> In pdb, I can't have the value of attribute a. >> So this is not linked to the fact that it is a SyntaxError or a SystemError. >> >> I expect to be able to have the value of all attributes that have been used >> before the error occured. >> This is problematic because in a more complicated code, you can't have the >> value of the attribute that was used before the error occured. >> Python know that this attribute exist, it only don't have its value. other >> attribute affected are : __name__,__doc__,__file__. >> >> -- >> Boutillier Alexis >> Methodology engineer >> >> Arteris SA >> The Network-on-Chip Company TM >> www.arteris.net >> >> 6 par Ariane Immeuble Mercure >> 78284 Guyancourt Cedex >> France >> Office: (+33) 1 61 37 38 71 >> Fax: (+33) 1 61 37 38 41 >> Alexis.Boutillier at arteris.net >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > So if you were writing C code and the file failed to compile you would > still expect to have a working executable that just worked up until > the point of the syntax error? > > I'm not sure why you just don't fix the syntax error and move on. > > As you can see in my last response, this problem is not linked to the type of error, If I "raise" a SystemError instead of creating a SyntaxError I still can't access variable defined before the error. -- Boutillier Alexis Methodology engineer Arteris SA The Network-on-Chip Company TM www.arteris.net 6 par Ariane Immeuble Mercure 78284 Guyancourt Cedex France Office: (+33) 1 61 37 38 71 Fax: (+33) 1 61 37 38 41 Alexis.Boutillier at arteris.net From castironpi at gmail.com Sun Aug 24 11:28:50 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 24 Aug 2008 08:28:50 -0700 (PDT) Subject: In-place memory manager, mmap (was: Fastest way to store ints and floats on disk) References: <1cf85075-17a1-4a1d-8ea5-bf5104541528@s50g2000hsb.googlegroups.com> Message-ID: On Aug 24, 9:52?am, Kris Kennaway wrote: > castironpi wrote: > > Hi, > > > I've got an "in-place" memory manager that uses a disk-backed memory- > > mapped buffer. ?Among its possibilities are: storing variable-length > > strings and structures for persistence and interprocess communication > > with mmap. > > > It allocates segments of a generic buffer by length and returns an > > offset to the reserved block, which can then be used with struct to > > pack values to store. ?The data structure is adapted from the GNU PAVL > > binary tree. > > > Allocated blocks can be cast to ctypes.Structure instances using some > > monkey patching, which is optional. > > > Want to open-source it. ?Any interest? > > Just do it. ?That way users can come along later. > > Kris How? My website? Google Code? Too small for source forge, I think. From paul at boddie.org.uk Fri Aug 29 15:15:24 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 29 Aug 2008 12:15:24 -0700 (PDT) Subject: problem with packages and path References: <8c1351f9-d349-4c0c-97a4-024c9472bff3@z11g2000prl.googlegroups.com> <41e605c6-05e3-4a5a-a8f4-978d63e64cf6@k36g2000pri.googlegroups.com> Message-ID: On 29 Aug, 19:08, Daniel wrote: > > I have tried running both commands above from the mypackage directory > and unittests directory. I get the following response universtally. > > C:\mypackage>dir > Volume in drive C is Default > > Directory of C:\mypackage > > 08/29/2008 11:04 AM
. > 08/29/2008 11:04 AM .. > 08/29/2008 11:05 AM module1 > 08/29/2008 11:05 AM module2 > 08/29/2008 11:06 AM unittests > 08/29/2008 11:04 AM 0 __init__.py > 1 File(s) 0 bytes > 5 Dir(s) 55,402,070,016 bytes free If you run unittests\alltests.py from here, sys.path will initially refer to this directory (C:\mypackage) and to anything else set up in your environment. The extra path modification that you put in alltests.py will append (or insert) the following... os.path.normpath( os.path.join( __file__, "../../" )) -> os.path.normpath( os.path.join( "C\\:mypackage\\unittests\ \alltests.py", "../../" )) -> os.path.normpath( "C\\:mypackage" ) -> "C\\:mypackage" Since the import statement then tries to access mypackage, which isn't itself in the C:\mypackage directory - it's in the C:\ directory - the import fails. The previous, automatically added entry in sys.path is duplicated by the path modifications shown above, so that won't help here, either. > C:\mypackage>dir unittests > Volume in drive C is Default > > Directory of C:\mypackage\unittests > > 08/29/2008 11:06 AM . > 08/29/2008 11:06 AM .. > 08/29/2008 11:05 AM 0 alltests.py > 08/29/2008 11:05 AM 0 test1.py > 08/29/2008 11:05 AM 0 test2.py > 08/29/2008 11:04 AM 0 __init__.py > 4 File(s) 0 bytes > 2 Dir(s) 55,401,988,096 bytes free Here, sys.path should refer to C:\mypackage\unittests somewhere, which won't help Python find mypackage. The path modification in alltests.py should perform as above, producing C:\mypackage which won't help. I guess the easiest thing to do is to change the path modification code to use "../../.." which should produce a reference to C:\ instead of C:\mypackage. The confusion with this particular piece of the code is the way ".." doesn't cause os.path.join to operate on the directory C:\mypackage\unittests but instead on the file C:\mypackage\unittests \alltests.py - that's almost to be expected, however, since os.path.join doesn't really know that its first argument is really a file or that ".." is being combined with a file. What I tend to do, especially with __file__, is to first use os.path.split to remove the filename - strictly speaking, it's the leafname - and then to apply the kind of modifications mentioned above, although there's probably no real difference or, indeed, any advantage with either approach. Paul From ggpolo at gmail.com Thu Aug 14 11:05:32 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 14 Aug 2008 12:05:32 -0300 Subject: Tkinter updates - Easiest way to install/use Tile? In-Reply-To: References: Message-ID: On Wed, Aug 13, 2008 at 2:10 PM, Mudcat wrote: > So I haven't programmed much in Python the past couple of years and > have been catching up the last few days by reading the boards. I'll be > making commercial Python applications again and wanted to see what's > new in the Gui department. > > I started using Tkinter several years ago and have a lot of stuff > written in it. As a result, it's hard to switch to another interface > (wxPython, PyQt, etc) with all the hours it would take to reproduce > code I will re-use. (I mention this to avoid the inevitable post > asking why I'm still using it). While I was able to produce some nice > applications in the past and am comfortable with the functionality I > was able to achieve I still wanted to find a way to improve the look > since the old look is even more dated now. > > I was reading about Tile, and it sounds like I should be able to wrap > a style around my current code to give it a different look. However it > doesn't sound like it's quite ready for prime time yet. I downloaded > the latest stable version of Python 2.5 which apparently still uses > Tcl 8.4. So my options at this point appear to be: > > 1) Download beta version of Python 2.6 which has Tcl 8.5. > Tile is supposed to be included with Tcl 8.5, but there's not much > information on how to use it with older code. Do I still need wrapper > code, or if I install 2.6 will it be available already. > > 2) Install Tcl 8.5 to use with Python 2.5. > How do you do this? In other posts it mentions recompiling source tcl > code with Python. If that's the case it doesn't sound like something I > want to mess with. If I stray too far from default configurations I > start to have problems with py2exe. > > 3) Install Tile with Python 2.5 and Tcl 8.4 and use wrapper code to > make it work. > However all the posts concerning this approach assume that Tile is > already installed. I downloaded the code for the latest version of > Tile which was a .kit extension. This also may need to be compiled, > and if that's the case I again start to have problems with freezing my > application. The other points were answered already, so let me give some more insight on this last one. For Windows there is a .zip you can download (following the links at http://tktable.sourceforge.net/tile/) which requires no installation, just unpacking. For Linux there is a package named tk-tile in Ubuntu. In case you are using Windows, just unpacking the .zip doesn't guarantee that Tk will find the tile package (unless you unpack at whatever places Tk looks by default). If Tk doesn't find it, you need to set the TILE_LIBRARY environment variable to whatever place tile was unzipped to. I'm assuming you will be using the previously mentioned ttk wrapper, which will look at TILE_LIBRARY, if necessary, to load tile. > > What's the easiest way to do this? I really couldn't find a place that > gave instructions for any of the current release configurations. It > sounds if it's available already in Python 2.6 that it would be the > easiest way, but I couldn't find any threads talking about the > availability of it for that release yet. > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From simon at mullis.co.uk Thu Aug 14 05:26:31 2008 From: simon at mullis.co.uk (Simon Mullis) Date: Thu, 14 Aug 2008 11:26:31 +0200 Subject: From Ruby to Python? In-Reply-To: <23d7e1bb0808130545w28fb4c04s205c1de2a39dcb36@mail.gmail.com> References: <23d7e1bb0808130545w28fb4c04s205c1de2a39dcb36@mail.gmail.com> Message-ID: <23d7e1bb0808140226r63fed22ev2ad83718b591f398@mail.gmail.com> In case anyone else has the same question: This has been very useful: http://www.poromenos.org/tutorials/python Short, concise. Enough to get me going. SM 2008/8/13 Simon Mullis > Hi All, > > I just finally found 30 minutes to try and write some code in Python and > realized after a couple of minor syntactic false starts that I'd finished my > initial attempt without needing to refer to any documention... And after the > first few minutes I stopped noticing the whitespace thing that had scared me > off previously. (Admittedly it's a very basic script using telnetlib to log > into a bunch of network devices via a few console servers and put the > results of some remote commands into a data-structure). > > So, after this initially promising start: > > Are there any good cheatsheets / guides for a Ruby programmer to learn > Python? > > I searched this list and couldn't find anything, and wasn't successful with > google either... > > Many thanks in advance, > > SM > > -- > -- Simon Mullis _________________ simon at mullis.co.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: From mdboldin at gmail.com Wed Aug 6 15:40:12 2008 From: mdboldin at gmail.com (mmm) Date: Wed, 6 Aug 2008 12:40:12 -0700 (PDT) Subject: SMTP via GMAIL References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> Message-ID: <93afa637-9292-4628-9028-ca6f8b299914@x35g2000hsb.googlegroups.com> On Aug 5, 12:18?am, Tim Roberts wrote: > >But when using smtp.gmail.com as the server I learned that any > >@gmail.com address in the ?Cc: text block would > >receive mail even if I changed the code to have the RECEIVERS list to > >ignore the CC addresses or not include the gmail address in the CC > >list as below > > Interesting. ?If true, that is incorrect behavior. I ran some more tests and now I am pretty sure session.sendmail(SENDER, RECEIVERS, BODY) is only sending to the RECEIVERS list, ignoring the Cc: field in the body (as it should) What fooled me is that I was using my own gmail account (i.e., me at gmail.com) as a Cc: field and not putting it in the RECEIVERS list. It seems Gmail creates two links (or copies?) to the message: (1) as it is stored in the SENT box (as it should since the message was sent by my gmail account) and (2) another in my INBOX because the mail reading software reads the Cc: field. Other smtp servers such as comcast do not create the stored SENT mail and hence behave different in terms of how they treat Cc: fields of the same account (me at comcast.net in this case). Most important, using another gmail account (not me at gmail.com) as a Cc: field does not create another sent message (outside of what is in the RECEIVERS field). Sorry for confusion, and I do appreciate the tips as I now see how almost anything To:, Cc:, Bcc: combination can be handled by a proper RECEIVERS list. Below is python code that can be used by anyone that wants to test what I did (just fill in the SMTPuser and password variables) and then check you gmail inbox import sys, os, glob, datetime, time import smtplib ## Parameters for SMTP session port=587 SMTPserver= 'smtp.gmail.com' SMTPuser= 'you at gmail.com' pw= 'fill in here' SENDER= SMTPuser ## Message details FROM= SENDER TO= 'notgmail at a.com' CC=FROM ##RECEIVERS= (TO, CC) ##proper way to send to both TO and CC RECEIVERS= (TO,) ## ignore the CC address subject= 'Test 1a' message='*** Email test *** ' print 'Starting SMTP mail session on %s as %s ' % (SMTPserver,SMTPuser) session = smtplib.SMTP(SMTPserver,port) session.set_debuglevel(0) # set debug level to 1 to see details session.ehlo(SMTPuser) # say hello session.starttls() # TLS needed session.ehlo(SMTPuser) # say hello again, not sure why session.login(SMTPuser, pw) ##Create HEADER + MESSAGE HEADER= 'From: %s\r\n' % FROM HEADER= HEADER + 'To: %s\r\n' % TO HEADER= HEADER + 'Cc: %s\r\n' % CC HEADER= HEADER + 'Subject: %s\r\n' % subject BODY= HEADER + '\r\n' + message print BODY SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) ## send email session.close() From mikael at isy.liu.se Thu Aug 21 04:06:59 2008 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 21 Aug 2008 10:06:59 +0200 Subject: Negative integers In-Reply-To: References: Message-ID: Derek Martin wrote: > Zero is a problem, no matter how you slice it. I definitely agree with that. Depends on the the real problem that is behind the OP:s question. > Zero can be considered > positive or negative (mathematically, 0 = -0). I've read quite a few articles written by mathematicians and mathematically oriented engineers, and my impression is that most of them, and therefore me included, use those words with the following meaning: Positive: >0 Negative: <0 When zero is to be included, the following terms are used: Non-negative: >=0 Non-positive: <=0 Using this convention, zero is neither positive nor negative. Wikipedia seems to agree with that: http://en.wikipedia.org/wiki/Positive_number /MiO From zondo42 at googlemail.com Fri Aug 29 14:26:37 2008 From: zondo42 at googlemail.com (Glenn Hutchings) Date: Fri, 29 Aug 2008 19:26:37 +0100 Subject: When to use try and except? References: <8a2dd955-6641-493d-b7eb-3e29c14686a5@26g2000hsk.googlegroups.com> <914fde08-5084-455f-ac68-bef7e06cc3dc@i76g2000hsf.googlegroups.com> Message-ID: cnb writes: > A ZeroDivisionError is better avoided wth an if-clause, don't you > think? It is a predictable exception... It depends. If zero-division is unlikely, then things would probably[*] run faster without checking. If speed is what you're interested in, that is... Glenn [*] Haven't checked, so don't really know :-) From fredrik at pythonware.com Wed Aug 13 17:31:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Aug 2008 23:31:42 +0200 Subject: Replace Several Items In-Reply-To: References: <513926b0-64fe-4fdc-bb33-bc4b8ad3ab10@a70g2000hsh.googlegroups.com> Message-ID: Wojtek Walczak wrote: >> I wish to replace several characters in my string to only one. >> Example, "-", "." and "/" to nothing "" >> I did like that: >> my_string = my_string.replace("-", "").replace(".", "").replace("/", >> "").replace(")", "").replace("(", "") >> >> But I think it's a ugly way. >> >> What's the better way to do it? > > The regular expression is probably the best way to do it, > but if you really want to use replace, you can also use > the replace method in loop: suggested exercise: benchmark re.sub with literal replacement, re.sub with callback (lambda m: ""), repeated replace, and repeated use of the form if ch in my_string: my_string = my_string.replace(ch, "") on representative data. From david at abbottdavid.com Sat Aug 2 16:34:02 2008 From: david at abbottdavid.com (David) Date: Sat, 02 Aug 2008 16:34:02 -0400 Subject: raw_input on several lines In-Reply-To: References: Message-ID: <4894C4BA.90309@abbottdavid.com> TP wrote: > Hi everybody, > > When using raw_input(), the input of the user ends when he types Return on > his keyboard. > How can I change this behavior, so that another action is needed to stop the > input? For example, CTRL-G. It would allow the user to input several lines. > > Thanks > > Julien > > > How about; student_scores = {} name = raw_input("Please enter a student name (q quits): ") while(name != 'q'): score = input("Please enter the students score: ") student_scores[name] = score name = raw_input("Please enter a student name (q quits): ") for current_key in student_scores.keys(): print "The current students are:", current_key -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From vinay_sajip at yahoo.co.uk Wed Aug 20 07:02:25 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 20 Aug 2008 04:02:25 -0700 (PDT) Subject: Logging library unicode problem References: <4d726712-ef30-4292-9b1d-28e3cb8c3282@r35g2000prm.googlegroups.com> Message-ID: On 13 Aug, 11:08, Victor Lin wrote: > Hi, > I'm writting a application using python standardloggingsystem. I > encounter some problem with unicode message passed tologginglibrary. > I found that unicode message will be messed up bylogginghandler. > > piese of StreamHandler: > > try: > self.stream.write(fs % msg) > except UnicodeError: > self.stream.write(fs % msg.encode("UTF-8")) > > It just write the message to stream. If there is some unicode error, > it would rewrite msg with utf8 encoding. > > I write some code to try: > > import sys > print u'?????' > print sys.stdout.encoding > sys.stdout.write(u'??') > > result of that program: > > ????? > cp950 > Traceback (most recent call last): > File "update_stockprice.py", line 92, in > sys.stdout.write(u'???') > UnicodeEncodeError: 'ascii' codec can't encode characters in position > 0-1: ordin > al not in range(128) > > It show that.... > > 1. print statement encode what it get with stream.encoding? > 2. stream.write don't do anything like encoding, just write it > (because it might be binary data?) > > So the problem is : the StreamHandler of standardlogginglibrary use > stream.write to log message, if there is unicode error, unicode string > will be encode to utf8. This behavior mess my unicode up. > > Here I modify the code of StreamHandler: > > try: > print >> self.stream, msg > #self.stream.write(fs % msg) > except UnicodeError: > self.stream.write(fs % msg.encode("UTF-8")) > > I replace stream.write with print statement, so that it will try to > use stream.encoding to encode msg. Now everything works fine. > > My question is : > Could the behavior of StreamHandler be considered as a bug? > If it is, how to report this bug? > Is my solution correct? > Are there any side effect will caused by doing so? > If the code I write is fine, and solve that problem, how to report it > to Python's project? > I think this could be helpful for people who also encountered this > problem. > > Thanks. > Victor Lin. Hi Victor, Can you try modifying your patch to use the following logic instead of the print statement? if hasattr(self.stream, 'encoding'): self.stream.write(fs % msg.encode(self.stream.encoding)) else: self.stream.write(fs % msg) Does this work in your scenario? Regards, Vinay Sajip From support.desk.ipg at gmail.com Tue Aug 26 18:03:48 2008 From: support.desk.ipg at gmail.com (Support Desk) Date: Tue, 26 Aug 2008 17:03:48 -0500 Subject: Adding Icons to my Programs In-Reply-To: <801533.35218.qm@web83916.mail.sp1.yahoo.com> References: <801533.35218.qm@web83916.mail.sp1.yahoo.com> Message-ID: <016401c907c7$a120d6a0$a601a8c0@office.ipglobal.net> Take a look at this: http://www.velocityreviews.com/forums/t332696-setting-icon-using-py2exe.html -----Original Message----- From: Kevin McKinley [mailto:kem1723 at yahoo.com] Sent: Tuesday, August 26, 2008 4:37 PM To: python-list at python.org Subject: Adding Icons to my Programs I've been turn my script into executible programs with Py2exe. Is there a way to change the icon for the main exe file? Thank you, Kevin McKinley From lists at cheimes.de Thu Aug 28 18:11:17 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 29 Aug 2008 00:11:17 +0200 Subject: Checking if the file is a symlink fails In-Reply-To: <803e077e-c0c9-43d3-b40a-99511c2e55f3@25g2000prz.googlegroups.com> References: <803e077e-c0c9-43d3-b40a-99511c2e55f3@25g2000prz.googlegroups.com> Message-ID: saswat at gmail.com wrote: > File symLinkTest is a symbolic link. > > Why S_ISLNK(mode) returns False and S_ISREG(mode) returns True ? Because you are using os.stat() instead of os.lstat(). http://docs.python.org/lib/os-file-dir.html Christian From rafesacks at gmail.com Tue Aug 19 13:39:44 2008 From: rafesacks at gmail.com (Rafe) Date: Tue, 19 Aug 2008 10:39:44 -0700 (PDT) Subject: cathing uncaught exceptions References: <497a32e3-a14d-469c-b331-e7a32d40ed80@a3g2000prm.googlegroups.com> Message-ID: <75ac3305-7d0f-455b-89df-cbe7a4268ae0@w39g2000prb.googlegroups.com> On Aug 18, 10:02 pm, Alexandru Mosoi wrote: > how can I catch (globally) exception that were not caught in a try/ > catch block in any running thread? i had this weird case that an > exception was raised in one thread, but nothing was displayed/logged. Any chance you might have missed the word "raise", e.g. except Exception, err: Exception(err) vs. except Exception, err: raise Exception(err) This is from the list of stupid things I have done myself, - Rafe From sunp1028 at gmail.com Sun Aug 17 20:57:46 2008 From: sunp1028 at gmail.com (Patrol Sun) Date: Mon, 18 Aug 2008 08:57:46 +0800 Subject: how many nested for can we utilize? In-Reply-To: References: <27cbc0fa0808152200l4be2ca5gc24d8b01458b6e62@mail.gmail.com> Message-ID: <27cbc0fa0808171757h79c7fd10ibc4884040ebc3472@mail.gmail.com> Of course We needn't 100 levels,but I use the exec function can concise the code. See the attachment. 2008/8/17 Fredrik Lundh > Nick Dumas wrote: > > A good quote I read (I can't remember who it was from, though) is "If >> you need more than three levels of indentation, then something is >> seriously wrong with your code." Possibly Guido himself? Anyway. If >> you've got 100 levels of for, you're probably making things way harder >> than they need to be. >> > > assuming 100 levels of for and 2 items in each sequence, you'll end up with > 1267650600228229401496703205376 iterations through the inner loop. assuming > each iteration takes a picosecond, it'll take approx 40 billion years to run > the program. > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: 052.py URL: From Lie.1296 at gmail.com Mon Aug 18 11:04:18 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 18 Aug 2008 08:04:18 -0700 (PDT) Subject: how many nested for can we utilize? References: <27cbc0fa0808152200l4be2ca5gc24d8b01458b6e62@mail.gmail.com> Message-ID: On Aug 17, 4:23?pm, Fredrik Lundh wrote: > Patrol Sun wrote: > > when I use 20 for ,"SystemError: too many statically nested blocks" > > When I use 100 for ,"IndentationError: too many levels of indentation" > > How to handle these errors? > > so why exactly are you trying to nest 20 or 100 for-in loops? > > I think most (all?) algorithm that might use 20+ levels of for-in loops could almost always be replaced with a recursive function. Or at least they could be broken into smaller functions. From martin at see.sig.for.address.invalid Mon Aug 18 05:33:44 2008 From: martin at see.sig.for.address.invalid (Martin Gregorie) Date: Mon, 18 Aug 2008 09:33:44 +0000 (UTC) Subject: The Importance of Terminology's Quality References: <48617847$0$5021$607ed4bc@cv.net> <486ae06b$0$5011$607ed4bc@cv.net> <4883bc90$0$7327$607ed4bc@cv.net> <48a4b2ba$0$20923$607ed4bc@cv.net> <48a782e9$0$20913$607ed4bc@cv.net> <48a8df27$0$7362$607ed4bc@cv.net> Message-ID: On Sun, 17 Aug 2008 22:30:35 -0400, John W Kennedy wrote: > I said "machine language" and I meant it. > OK - I haven't touched that since typing ALTER commands into the console of a 1903 running the UDAS executive or, even better, patching the executive on the hand switches. I was fascinated, though by the designs of early assemblers: I first learnt Elliott assembler, which required the op codes to be typed on octal but used symbolic labels and variable names. Meanwhile a colleague had started on a KDF6 which was the opposite - op codes were mnemonics but all addresses were absolute and entered in octal. I always wondered about the rationale of the KDF6 assembler writers in tackling only the easy part of the job. > Even shops that used assembler nevertheless frequently did bug fixes as > machine-language patches, rather than take the time to run the assembler > again. (SPS, the non-macro basic assembler, ran at about 70 lines a > minute, tops.) > Even a steam powered 1901 (3.6 uS for a half-word add IIRC) running a tape based assembler was faster than that. It could just about keep up with a 300 cpm card reader. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From gh at ghaering.de Mon Aug 25 10:48:49 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 25 Aug 2008 16:48:49 +0200 Subject: newbie question In-Reply-To: References: Message-ID: sharon k wrote: > hi all, > > i am new to python. > > i fetch a webpage with urllib, extract a few numbers in a format as follow; > > 10,884 > 24,068 > > my question is how to remove the comma between the number, since i have > to add them up later. Strings have a replace method. Calling replace(",", "") on the string will do the trick here. -- Gerhard From fredrik at pythonware.com Wed Aug 13 18:31:00 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 00:31:00 +0200 Subject: Replace Several Items In-Reply-To: References: <513926b0-64fe-4fdc-bb33-bc4b8ad3ab10@a70g2000hsh.googlegroups.com> Message-ID: Wojtek Walczak wrote: >> suggested exercise: benchmark re.sub with literal replacement, re.sub >> with callback (lambda m: ""), repeated replace, and repeated use of the form >> >> if ch in my_string: >> my_string = my_string.replace(ch, "") >> >> on representative data. > > I don't have to, I can anticipate the results. Chances are that you're wrong. From cjames at callone.net Tue Aug 26 13:34:50 2008 From: cjames at callone.net (c james) Date: Tue, 26 Aug 2008 12:34:50 -0500 Subject: sum up numbers in a list In-Reply-To: References: Message-ID: >>> L=['10','15','20'] >>> sum(int(x) for x in L) 45 or >>> sum(map(int,L)) 45 sharon kim wrote: > hi all, > > i have a list, for example; > > >>> L=[] > >>> L.append('10') > >>> L.append('15') > >>> L.append('20') > >>> len(L) > 3 > >>> print L > ['10', '15', '20'] > > is there a way to sum up all the numbers in a list? the number of > objects in the list is vary, around 50 to 60. all objects are 1 to 3 > digit positive numbers. > > all i can think of is check the length of the list (in the above > example, 3), then L[0]+L[1]+L[2] ...... > > is there a better way to do the job? thanks. From benjamin.michiels at gmail.com Tue Aug 12 10:41:23 2008 From: benjamin.michiels at gmail.com (Benjamin Michiels) Date: Tue, 12 Aug 2008 16:41:23 +0200 Subject: Thesaurus / ontology / taxonomy Python library Message-ID: Hi, I am curently looking for a library allowing the creation and management of a thesaurus. Our requirements are the following: - creation of our own thesaurus (that is, terms AND relations between terms), and indexing (and retrieving) documents with terms defined in our thesaurus, - "thesauraus management facilities", such as batch editing of content items (e.g. for all documents indexed by keyword "A" and "B", replace keywords "A" and "B" by keyword "C"). - user-friendly interface. This could a be tree-like structure (with - ideally - several levels of indexing), such as: Shape - TS: Square + TS: Triangle - TS: Scalene triangle + TS: Equilateral triangle - [...] Ideally, this library would be ready-for-Plone3.x-Zope2.10; but after some - basic - searches, it appeared that such thesaurus management tools are rather rare, so I was wondering whether there would even exist such a library in Python... What do you think of it and/or is there already a discussion on this topic? Thank you in advance, Benjamin Michiels -------------- next part -------------- An HTML attachment was scrubbed... URL: From info at thegrantinstitute.com Wed Aug 13 05:14:46 2008 From: info at thegrantinstitute.com (Anthony Jones) Date: 13 Aug 2008 02:14:46 -0700 Subject: Professional Grant Proposal Writing Workshop (September 2008: British Columbia Institute of Technology - Vancouver Campus) Message-ID: <20080813021446.8C98E6D340E4553A@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Aug 22 12:53:05 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 22 Aug 2008 09:53:05 -0700 (PDT) Subject: Should Python raise a warning for mutable default arguments? References: <00becb2d$0$20312$c3e8da3@news.astraweb.com> Message-ID: On Aug 22, 9:42?am, Steven D'Aprano wrote: > Sometimes it seems that barely a day goes by without some newbie, or not- > so-newbie, getting confused by the behaviour of functions with mutable > default arguments. No sooner does one thread finally, and painfully, fade > away than another one starts up. > > I suggest that Python should raise warnings.RuntimeWarning (or similar?) > when a function is defined with a default argument consisting of a list, > dict or set. (This is not meant as an exhaustive list of all possible > mutable types, but as the most common ones that I expect will trip up > newbies.) The warning should refer to the relevant FAQ or section in the > docs. > > What do people think? > > -- > Steven I like the idea of calling it to your attention. +1. If a warning, you should be able to silence it with an annotation, decorator, or a module-level flag. Or perhaps, require it be declared explicit, and make it an error. def test(x, a=defmut([])): Python raises an actual error unless default arguments are known immutable or instances of 'defmut'. From gminick at nie.ma.takiego.adresu.w.sieci.pl Wed Aug 13 18:39:58 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Wed, 13 Aug 2008 22:39:58 +0000 (UTC) Subject: Suggestion for improved ImportError message References: Message-ID: Dnia Wed, 13 Aug 2008 22:15:48 +0000 (UTC), Wojtek Walczak napisa?(a): > Then go for it :-) You can prepare a patch and ask on python-dev > if the developers are interested. > > I was never hacking the import things on C level before, > but a hint: you have to modify import_from function from > Python/ceval.c > > My quick attempt: > http://www.stud.umk.pl/~wojtekwa/patches/from-import-py2.5.1.patch Uh, and an example: Python 2.5.1 (r251:54863, Aug 14 2008, 00:04:00) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from os import qweasd Traceback (most recent call last): File "", line 1, in ImportError: cannot import name qweasd (/home/gminick/Python-2.5.1/Lib/os.pyc) >>> -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From jparker104 at gmail.com Tue Aug 19 10:37:20 2008 From: jparker104 at gmail.com (jparker104 at gmail.com) Date: Tue, 19 Aug 2008 07:37:20 -0700 (PDT) Subject: How to access an Array and a struct within a struct wrapped by Swig ? References: <6c21cc96-eab4-4823-97c6-c94e1d3da1ec@d1g2000hsg.googlegroups.com> Message-ID: On Aug 17, 11:30?pm, emmanuel.rivo... at gmail.com wrote: > Anish Chapagain, I already know how to use structure, as my example > shown it. > I had trouble only with the nested structures, and it was coz of > missing typedef (ie: Swig need C struct declaration, not C++). > > And I still cannot find how to get my arrays... :-S I was having the same problem with arrays and found a workaround here: http://www.swig.org/papers/PyTutorial97/PyTutorial97.pdf slide 39, "Helper Functions" I got it to work, hope this helps From hubaghdadi at gmail.com Thu Aug 14 05:43:16 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Thu, 14 Aug 2008 02:43:16 -0700 (PDT) Subject: You advice please References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> Message-ID: <2a611c23-16a9-4a9d-8c93-3b24d7b404af@e39g2000hsf.googlegroups.com> On Aug 13, 11:14 am, Alia Khouri wrote: > Hussein B wrote: > > I'm a Java/Java EE developer and I'm playing with Python these days. > > I like the Python language so much and I like its communities and the > > Django framework. > > Sounds familiar... (-: > > > My friends are about to open a Ruby/Rails shop and they are asking me > > to join them. > > In this case, I think you have to make decision that is not technology- > centric but application-centric, and you should also consider closely > the opportunity set and capability set available to you and your > friends. > > > I don't know what, sure I'm not leaving Java, but they are asking me > > to stop learning Python and concentrate on Ruby/Rails. > > I don't think you should stop learning anything that rings your bell.. > I love learning other languages (e.g. Haskell, Lua, Ruby, C#, Java, > boo, etc..) and I will code projects as per the requirements at the > time, but I tend to Python because, like you, I like the language and > the community. > > In _addition_ to your love for Python and Django, why not learn Ruby/ > Rails? It's not a bad framework at all, and Ruby is quite fun to > program in as well...? > > > The sad fact (at least to me), Ruby is getting a lot of attention > > these days. > > Not a sad fact, What's good for ruby is good for python and vice > versa... Friendly competition is always positive and usually good > ideas cross-pollinate across the languages... > > > Why Python isn't getting this attention although is a much more mature > > language and it is used by many big, big names? > > Who says Python is not getting attention? Last time I checked, > Python's popularity was at all time high, and the big guns in the > industry favor (witness Google AppEngine, Microsoft Ironpython > preceding Ironruby, etc..) > > > And do I dare to say it is much more charming? > > That is an aesthetic judgement... (-: > > > What do you think of Ruby/Rails? do they worth learning and working > > with? > > (see above) > > > Any way, I'm not leaving Python and I will try to study it every time > > I get a chance... > > Good for you (-: > > > Thanks. But this critisim looks so serious: http://en.wikipedia.org/wiki/Ruby_programming_language#Criticism From hubaghdadi at gmail.com Wed Aug 20 06:08:59 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Wed, 20 Aug 2008 03:08:59 -0700 (PDT) Subject: Basic importing question Message-ID: Hey, Suppose I have a Python application consists of many modules (lets say it is a Django application). If all the modules files are importing sys module, how many times the sys module will be compiled and executed? Only once (the first time the PVM locates, compiles and executes the sys module)? or once for each module importing sys? Thanks. From b-cousson at ti.com Tue Aug 12 05:29:18 2008 From: b-cousson at ti.com (Cousson, Benoit) Date: Tue, 12 Aug 2008 11:29:18 +0200 Subject: Why nested scope rules do not apply to inner Class? Message-ID: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> Hi, I'd like to be able to use a nested class (C1) from another sibling nested class (C3). This looks very similar to the nested scopes of functions except that it does not work. class A(object): pass class B(object): class C1(object): pass class C2(C1): foo = A class C3(object): foo = C1 The funny thing is that C2 can inherit from C1 but C3 cannot reference C1. B.C1 does not work either, but in that case it makes sense since B is still being defined. Is this a language limitation or something that does not make sense at all? I'm wondering as well if the new nonlocal statement will fix that in py3k? Thanks in advance, Benoit From castironpi at gmail.com Thu Aug 7 17:29:13 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 7 Aug 2008 14:29:13 -0700 (PDT) Subject: Limits of Metaprogramming References: <0c56829a-7ad2-4ff2-b225-7981538e7c7a@j22g2000hsf.googlegroups.com> <07c3d5f8-563c-43bc-8772-5eb60de52c82@8g2000hse.googlegroups.com> <95cebacd-6221-478f-81ae-1040b1711b40@k13g2000hse.googlegroups.com> <5306b80e-81ff-43a5-a472-4f9f05764e4a@e39g2000hsf.googlegroups.com> <4fbbc028-9649-4de4-86e5-af6887b5bc67@z72g2000hsb.googlegroups.com> Message-ID: On Aug 7, 2:01?pm, Wilson wrote: > On Aug 6, 6:04?pm, castironpi wrote: > > > > > On Aug 6, 7:24?am, Wilson wrote: > > > > On Aug 4, 9:23?pm, castironpi wrote: > > > > > On Aug 4, 1:57?pm, Wilson wrote: > > > > > > On Aug 4, 6:49?pm, castironpi wrote: > > > > > > > Two, if all your methods will have uniform signatures and closures, > > > > > > you can store class methods as only their co_code objects: > > > > > > > >>> C.g.im_func.func_code.co_code > > > > > > > 'd\x00\x00S' > > > > > > > And fabricate them dynamically into full live types as needed. > > > > > > Thanks for your comments and advice. This second option intrigues me; > > > > > could you elaborate further, I don't follow you... > > > > > > Thanks Paul > > > > > Depending on the complexity of the functions, a code string could be > > > > all you need to store to determine (redetermine) a function's > > > > behavior. ?For something moderately simple, > > > > > def trans1( self, prev, trans ): > > > > ? ? ? ? if prev== 0 and trans== 'a': > > > > ? ? ? ? ? ? ? ? return 1 > > > > ? ? ? ? if prev== 1 and trans== 'b': > > > > ? ? ? ? ? ? ? ? return 0 > > > > ? ? ? ? return prev > > > > > I found you need to store code.co_nlocals, code.co_code, and > > > > code.co_consts, to distinguish from a blank stub. ?With extra > > > > variables, I needed code.co_names and code.co_varnames too. ?To > > > > recreate a code object completely, you need 12 variables (14 to > > > > include closures), some of which are composite objects and would need > > > > to be pickled to be stored. > > > > Still don't really understand this so I'm going to admit defeat. > > > Thanks all for your advice... Very much appreciated! > > > I was describing an alternative to storing functions in a way that > > wasn't in serial in plain text. ?It was off-topic from state-machine > > transitions. > > > Can you start with this? > > > # state, input, next state > > transitions= [ > > ? ( 0, 'a', 1 ), > > ? ( 1, 'a', 2 ), > > ? ( 2, 'a', 0 ), > > ? ( 0, 'b', 0 ), > > ? ( 1, 'b', 0 ), > > ? ( 2, 'b', 2 ) > > ] > > > What further? > > My problem relates to the states really. I'd like to import a file > containing the state classes into a "state editor" that is just a > class editor really. Then, at *runtime* I'd like to add and remove > methods from this class and change its attributes (__dict__). I'd also > like to be able to add and remove classes from the module. When done, > I was hoping to do introspection upon which classes were associated > with this module and write back the modified class definitions to the > same module. Next time the module is imported, the changes would > remain intact. Unfortunately, inspect.getsource() reads the original > file and does not magically return source from the runtime objects. > > Hope that makes sense! > Paul I see. You want: import states def funa( ): something( ) states.funa= funa And have those changes appear in the actual text of 'states.py'. Are you certain that classes are your best choice for representing states? I am interpreting that you want one class per state, and one method per transition out of that state. How close is that? If you are seeking to generate a .py file from a data structure, why not just edit the data structure directly? If you do need a .py file, can you just regenerate it? From larry.bates at websafe.com` Sat Aug 9 10:41:07 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 09 Aug 2008 09:41:07 -0500 Subject: Large production environments using ZODB/ZOE? In-Reply-To: References: Message-ID: Phillip B Oldham wrote: > I've been reading a lot recently on ZODB/ZOE, but I've not seen any > reference to its use in large-scale production envrironments. > > Are there any real-world examples of ZODB/ZOE in use for a large > system? By large, I'm thinking in terms of both horizontally-scaled > systems and in terms of data storage size. I have been told (by one of the developers) that Viacom uses it for their video streaming website which is quite large. There is also a list of organizations on Zope's webside that is pretty impressive. -Larry From geraint.williams at gmail.com Thu Aug 28 06:20:29 2008 From: geraint.williams at gmail.com (GHZ) Date: Thu, 28 Aug 2008 03:20:29 -0700 (PDT) Subject: filter in for loop Message-ID: <2b50828b-14e4-48a2-884c-220b70216568@d77g2000hsb.googlegroups.com> I would like to say something like: for x in l if : e.g. for filename in os.listdir(DIR) if filename[-4:] == '.xml': instead of having to say: for filename in os.listdir(DIR): if filename[-4:] == '.xml': or for filename in (f for f in os.listdir(DIR) if f[-4] == '.xml'): is there a shortcut I'm missing? From castironpi at gmail.com Sun Aug 17 15:29:30 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 17 Aug 2008 12:29:30 -0700 (PDT) Subject: dynamic attribute syntax Message-ID: Hi all, Thinking of a syntax for 'getattr' and 'setattr' dynamic access. 'obj.prop' has an easy access, but att= 'prop' getattr( obj, att ) is much clumsier, while no less useful, maybe more. What are the changes, pros and cons, involved in something like: obj:att for a dynamic access, and obj.att for static? Snice readability is a factor, I'm open to other markings than ':'. '$' and '?' are available, and I note that a~b, a:b, and, a!b for identifiers 'a' and 'b' are unambiguous. From ironfroggy at gmail.com Wed Aug 13 19:59:30 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Wed, 13 Aug 2008 19:59:30 -0400 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: <200808140141.38909.maric@aristote.info> References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> <200808122240.22517.maric@aristote.info> <76fd5acf0808121415h41cc580bj85d96e648c54ab4b@mail.gmail.com> <200808140141.38909.maric@aristote.info> Message-ID: <76fd5acf0808131659i361d7fbdo595bebf57aeab317@mail.gmail.com> On Wed, Aug 13, 2008 at 7:41 PM, Maric Michaud wrote: > I was not aware of any "nested classes are unsupported" before and didn't > consider nested classes as bad practice till now, even with the pickle > limitation (not every class are intended to be pickled), more you didn't give > any evidence or any pertinent quote of this and at least one of Guido in the > above threads seems contradict you : > http://mail.python.org/pipermail/python-dev/2002-November/029906.html Of course, I don't have to agree with Guido, but I don't really think his comment there counts as some encouragement of the practice. It also isn't an example that actually demonstrates the things people misuse about nesting classes, although its definitely an example that I think could be done much better without them, at all. The use of nested classes to define some hierarchical structure is subject, at best. And, the examples I see aren't even hierarchical. The nesting doesn't seem to gain them anything. As a matter of fact, wouldn't that example be a lot more clear with one class and some "Attribute" properties describing the structure? What rubs me the wrong way about nested classes is that they aren't even "real" classes. That is, they aren't being used to instantiate instances, but just as dummy scopes to hold some attributes. They are abusing classes as property bags. > BTW my concern was not really about nested classes but the asymetry between > function scope and classes scope, there are at least two examples that come > to my mind and for which I don't see good argument to keep the situation as > it is. First is the very odd behavior of genexp, second is the dynamic type > factory, I know it's not a big deal to in each case and can live with this, > but these pieces of code fail unexpectedly while even a experimented python > programmer would have thought they work at first glance, and the explanation > of why they fail to a newcomer is not easy (specially for the first) > > (1) this fail only on the last line while it would have work well with > listcomp and works well in a function definition > class A(object) : > l = range(5) > m = list(a+b for a in l for b in range(5)) > n = list(a+b for a in range(5) for b in l) I can admit that this behavior can be surprising, but it isn't something I really see cropping up as a problem. How often do you see that you need to have any kind of procedural behavior in a class body? In other words, in all but rare cases, the order of the class body lines shouldn't change the resulting class, but this example breaks that expectation. > (2) This won't work as it would with nested functions, you need to build the > new calss directly with type('dynamic', (object,), {"type_": type_}) > > def create_type(type_) : > class dynamic(object) : > type_ = type_ > return dynamic This is simply completely invalid. That code at the beginning of any body will _always_ raise either an UnboundLocalError or a NameError, because you are assigning to the same name you are dereferencing. That line will always be either an error or a no-op, anywhere it appears. It has nothing to do with nesting of any sort. > > -- > _____________ > > Maric Michaud > -- > http://mail.python.org/mailman/listinfo/python-list -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy From mensanator at aol.com Mon Aug 4 16:18:11 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 4 Aug 2008 13:18:11 -0700 (PDT) Subject: What Python looks like References: Message-ID: On Aug 4, 2:06?pm, iu2 wrote: > Hi, > > This is a little bit strange post, but I'm curious... > > I learned Python from its tutorial step by step, and practicing > writing small scripts. > I haven't seen a Python program before knowing Python. > > I'm curious, what did Python code look like to those of you who have > seen a bunch of Python code for the first time before knowing Python? To me, when I started transitioning from perl to Python, Python Python from 2002 -------------------------------------------------------------- import sys import string # Python Collatz tester j = string.atol(sys.argv[1]) i = 2**(6*j-1)-1 print i,"\n" r1 = 0 r2 = 0 count = 0 while i>1: z = divmod(i,2) if z[1]==0: i = z[0] r1 = r1 + 1 if z[1]>0: i = i*3 + 1 r2 = r2 + 1 print "[1]",r1 print "[2]",r2,"\n" -------------------------------------------------------------- looked just like perl, but without the braces (which seemed a lot more important than the $s). Perl from 2002 -------------------------------------------------------------- use Math::BigInt ':constant'; $j = @ARGV[0]; $i = 2**(6*$j-1)-1; print "$i\n"; $r1 = 0; $r2 = 0; while ($i>1) { if ($i =~ /.*?[0,2,4,6,8]$/) { $i = $i/2; $r1++; } else { $i = $i*3 + 1; $r2++; } } print "[1] ",$r1; print " [2] ",$r2,"\n"; -------------------------------------------------------------- > > (I can tell, for example, that seeing perl for the first time looked > like C with many $$$, I wouldn't say that, the $s are minor, big thing is the declarations and pointers. C from 2005 (not complete program) -------------------------------------------------------------- long collatz (mpz_ptr r) { mpz_t result, twee, twoo, cee; mpz_init (result); mpz_init_set_ui (cee, 1); mpz_init_set_ui (twee, 3); mpz_init_set_ui (twoo, 2); long rule1 = 0; long rule2 = 0; long f; while (mpz_cmp (r, cee) > 0) { f = mpz_scan1 (r, 0); if (f>0) /* even */ { mpz_tdiv_q_2exp (result, r, f); rule1 = rule1 + f; } else /* odd */ { mpz_set (result, cee); mpz_addmul (result, r, twee); rule2++; } mpz_swap (r, result); } printf ("\nRule1: %8d Rule2: %8d\n\n", rule1, rule2); return rule1 + rule2; } -------------------------------------------------------------- > I could see "if" and "for" and "while" but they > were meaningless. Maybe you looked at a crappy example. > Or Lisp for the first time looked like many words, > no operators, Aren't some of the words operators? I never used used Lisp, but I did dabble in Scheme and have no trouble identifying the operators (although not the overall program). Scheme from 2004 -------------------------------------------------------------- (define n 1) (define collatz (lambda (n) (if (even? n) (/ n 2) (+ 1 (* n 3)) ))) (define sequence (lambda (n) (do ((count 0 (+ count 1))) ((= n 1) (display "stopping: ") (display count)) (set! n (collatz n)) (display n) (display " ") ))) -------------------------------------------------------------- > how could that make a program???) You have to think differently with functional languages. The functional snobs say you'll never "get" it once your mind has been poisoned by imperative languages. > > Thanks From Edwin.Madari at VerizonWireless.com Sat Aug 9 11:22:48 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Sat, 9 Aug 2008 11:22:48 -0400 Subject: Extract string from log file In-Reply-To: Message-ID: <20080809152259.22E341E4002@bag.python.org> from each line separate out url and request parts. split the request into key-value pairs, use urllib to unquote key-value pairs......as show below... import urllib line = "GET /stat.gif?stat=v&c=F-Secure&v=1.1%20Build%2014231&s=av%7BNorton%20360%20%28Symantec%20Corporation%29+69%3B%7Dsw%7BNorton%20360%20%28Symantec%20Corporation%29+69%3B%7Dfw%7BNorton%20360%20%28Symantec%20Corporation%29+5%3B%7Dv%7BMicrosoft%20Windows%20XP+insecure%3BMicrosoft%20Windows%20XP%20Professional+f%3B26027%3B26447%3B26003%3B22452%3B%7D&r=0.9496 HTTP/1.1" words = line.split() for word in words: if word.find('?') >= 0: req = word[word.find('?') + 1:] kwds = req.split('&') for kv in kwds: print urllib.unquote(kv) stat=v c=F-Secure v=1.1 Build 14231 s=av{Norton 360 (Symantec Corporation)+69;}sw{Norton 360 (Symantec Corporation)+69;}fw{Norton 360 (Symantec Corporation)+5;}v{Microsoft Windows XP+insecure;Microsoft Windows XP Professional+f;26027;26447;26003;22452;} r=0.9496 good luck Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of josephtys86 at googlemail.com Sent: Saturday, August 09, 2008 10:48 AM To: python-list at python.org Subject: Extract string from log file 203.114.10.66 - - [01/Aug/2008:05:41:21 +0300] "GET /stat.gif? stat=v&c=F-Secure&v=1.1%20Build%2014231&s=av%7BNorton %20360%20%28Symantec%20Corporation%29+69%3B%7Dsw%7BNorton %20360%20%28Symantec%20Corporation%29+69%3B%7Dfw%7BNorton %20360%20%28Symantec%20Corporation%29+5%3B%7Dv%7BMicrosoft%20Windows %20XP+insecure%3BMicrosoft%20Windows%20XP%20Professional+f %3B26027%3B26447%3B26003%3B22452%3B%7D&r=0.9496 HTTP/1.1" 200 43 "http://dfstage1.f-secure.com/fshc/1.1/release/devbw/1.1.14231/ card.html" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)" does anyone know how can i extract certain string from this log file using regular expression in python or using XML. can teach me. -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From jwkenne at attglobal.net Sat Aug 23 21:22:05 2008 From: jwkenne at attglobal.net (John W Kennedy) Date: Sat, 23 Aug 2008 21:22:05 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> <48af8cc4$0$20919$607ed4bc@cv.net> Message-ID: <48b0b81f$0$7353$607ed4bc@cv.net> Martin Gregorie wrote: > On Sat, 23 Aug 2008 00:06:28 -0400, John W Kennedy wrote: > >> Martin Gregorie wrote: >>> Not necessarily. An awful lot of CPU cycles were used before microcode >>> was introduced. Mainframes and minis designed before about 1970 didn't >>> use or need it >> No, most S/360s used microcode. > > I never used an S/360. > > I thought microcode came into the IBM world with S/370 and Future Series > (which later reappeared as the AS/400, which I did use). Didn't the S/370 > load its microcode off an 8 inch floppy? Some did, but not all. The 370/145 was the first, and made a big splash thereby. As to the 360s: 20 (Incompatible subset) I don't know 22 (Recycled end-of-life 30) CROS 25 Loaded from punched cards 30 CROS 40 TROS 44 (Subset) None 50 CROS 60, 62, 65 ROS 64, 66, 67 ROS 70, 75 None 85 I don't know 91, 95 I don't know -- probably none 195 I don't know CROS used plastic-coated foil punched cards as the dielectrics of 960 capacitors each. TROS used little transformer coils that might or might not be severed. ROS means it was there, but I don't know the technology. -- John W. Kennedy "Those in the seat of power oft forget their failings and seek only the obeisance of others! Thus is bad government born! Hold in your heart that you and the people are one, human beings all, and good government shall arise of its own accord! Such is the path of virtue!" -- Kazuo Koike. "Lone Wolf and Cub: Thirteen Strings" (tr. Dana Lewis) From metaperl at gmail.com Thu Aug 28 15:27:41 2008 From: metaperl at gmail.com (Terrence Brannon) Date: Thu, 28 Aug 2008 12:27:41 -0700 (PDT) Subject: re.compile versus r'' References: <0bf4b8de-e11e-451c-8d18-58c1a4138375@e53g2000hsa.googlegroups.com> Message-ID: <69661017-f461-4ab5-a798-268e9180c2f6@c58g2000hsc.googlegroups.com> Oh my god, how embarrassing. the r'' notation is to create raw string I thought it was some form of blessing a string into a regular expression class. From kem1723 at yahoo.com Fri Aug 29 13:37:21 2008 From: kem1723 at yahoo.com (Kevin McKinley) Date: Fri, 29 Aug 2008 10:37:21 -0700 (PDT) Subject: Memory Leek, critique me. Thanks!!! Message-ID: <333736.18680.qm@web83911.mail.sp1.yahoo.com> # I posted a few days ago about a memory leak that I think i'm having with my first Tkinter program. # I've had trouble pinpointing what is wrong so i thought i would submit the code and see if anyone would # like to critique it. # I have one more problem that i can't figure out either. There are a bunch of Entry widgets that require number values. # My problem is if someone inputs a letter or space the program will have error that makes part of the # Program nonfunctional. # Description Of The Program: I made this program to help me with common calculations that i do on a day-to-day # basis. I'm a outside sales rep and this program figures out Gross profit and price increase. Oh, and where it # said to enter COG that stands for Cost of Goods. I know it doesn't really matter but figure i would let you guys # in on the use of the program. # Thank you, # Kevin McKinley from Tkinter import * class MyApp: def __tini__(self, parent): self.myParent = parent self.myFunctionContainer = Frame(parent) self.myFunctionContainer.grid(row=0, column=0) self.COG1 = DoubleVar() self.COG2 = DoubleVar() self.COG3 = DoubleVar() self.COG4 = DoubleVar() self.GP = DoubleVar() self.increase = DoubleVar() self.markup = DoubleVar() self.gpRange(1) # This Function is for the Markup Tab for a range of GP% def gpRange(self, event): self.clearScreen() self.gpRangeTab = Button(self.myFunctionContainer, width=14, relief=FLAT, text="Multi-Markup") self.gpRangeTab.bind("", self.gpRange) self.gpRangeTab.grid(row=0, column=0) self.gpExactTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Single Markup") self.gpExactTab.bind("", self.gpExact) self.gpExactTab.grid(row=0, column=1) self.priceIncreaseTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Product Increase") self.priceIncreaseTab.bind("", self.priceIncrease) self.priceIncreaseTab.grid(row=0, column=2) self.gpFinderTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Calculate GP") self.gpFinderTab.bind("", self.gpFinder) self.gpFinderTab.grid(row=0, column=3) self.markup1(1) self.myContainer2 = Frame(self.myFunctionContainer, borderwidth=2, relief=GROOVE) self.myContainer2.grid(padx=0, pady=2, row=4, column=0, columnspan=4, sticky=W+E) self.title1 = Label(self.myFunctionContainer, font="bold", relief=GROOVE, text="Multi-Markup Calculator") self.title1.grid(padx=0, pady=2, row=1, column=0, columnspan=4, sticky=W+E) self.entry1 = Entry(self.myFunctionContainer, textvariable=self.COG1) self.entry1.select_range(0, END) self.entry1.bind("", self.markup1) self.entry1.focus_force() self.entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.entryTitle = Label(self.myFunctionContainer, text="Enter COG:") self.entryTitle.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.title2 = Label(self.myContainer2, text="Gross Profit % ") self.title2.grid(padx=2, pady=2, row=1, column=1, sticky=W) self.title3 = Label(self.myContainer2, text=" Markup Price") self.title3.grid(padx=2, pady=2, row=1, column=2, sticky=E) self.button1 = Button(self.myFunctionContainer, text="Calculate") self.button1.bind("", self.markup1) self.button1.grid(padx=2, pady=2, row=3, column=1, columnspan=2, sticky=W+E) def gpExact(self, event): self.clearScreen() self.gpRangeTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Multi-Markup") self.gpRangeTab.bind("", self.gpRange) self.gpRangeTab.grid(row=0, column=0) self.gpExactTab = Button(self.myFunctionContainer, width=14, relief=FLAT, text="Single Markup") self.gpExactTab.bind("", self.gpExact) self.gpExactTab.grid(row=0, column=1) self.priceIncreaseTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Product Increase") self.priceIncreaseTab.bind("", self.priceIncrease) self.priceIncreaseTab.grid(row=0, column=2) self.gpFinderTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Calculate GP") self.gpFinderTab.bind("", self.gpFinder) self.gpFinderTab.grid(row=0, column=3) self.markup2(1) self.title1 = Label(self.myFunctionContainer, font="bold", relief=GROOVE, text="Single Markup Calculator") self.title1.grid(padx=0, pady=2, row=1, column=0, columnspan=4, sticky=W+E) self.entry1 = Entry(self.myFunctionContainer, textvariable=self.COG2) self.entry1.select_range(0, END) self.entry1.focus_force() self.entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.entry2 = Entry(self.myFunctionContainer, textvariable=self.GP) self.entry2.select_range(0, END) self.entry2.bind("",self.markup2) self.entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) self.entryTitle = Label(self.myFunctionContainer, text="Enter COG:") self.entryTitle.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.entryTitle2 = Label(self.myFunctionContainer, text="Enter GP%:") self.entryTitle2.grid(padx=2, pady=2, row=3, column=1, sticky=E) self.button = Button(self.myFunctionContainer, text="Calculate") self.button.bind("", self.markup2) self.button.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) def priceIncrease(self, event): self.clearScreen() self.gpRangeTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Multi-Markup") self.gpRangeTab.bind("", self.gpRange) self.gpRangeTab.grid(row=0, column=0) self.gpExactTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Single Markup") self.gpExactTab.bind("", self.gpExact) self.gpExactTab.grid(row=0, column=1) self.priceIncreaseTab = Button(self.myFunctionContainer, width=14, relief=FLAT, text="Product Increase") self.priceIncreaseTab.bind("", self.priceIncrease) self.priceIncreaseTab.grid(row=0, column=2) self.gpFinderTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Calculate GP") self.gpFinderTab.bind("", self.gpFinder) self.gpFinderTab.grid(row=0, column=3) self.increase1(1) self.title1 = Label(self.myFunctionContainer, font="bold", relief=GROOVE, text="Product Price Increase") self.title1.grid(padx=0, pady=2, row=1, column=0, columnspan=4, sticky=W+E) self.entry1 = Entry(self.myFunctionContainer, textvariable=self.COG3) self.entry1.select_range(0, END) self.entry1.focus_force() self.entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.entry2 = Entry(self.myFunctionContainer, textvariable=self.increase) self.entry2.select_range(0, END) self.entry2.bind("", self.increase1) self.entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) self.entryTitle = Label(self.myFunctionContainer, text="Enter COG:") self.entryTitle.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.entryTitle2 = Label(self.myFunctionContainer, text="Enter Increase %:") self.entryTitle2.grid(padx=2, pady=2, row=3, column=1, sticky=E) self.button = Button(self.myFunctionContainer, text="Calculate") self.button.bind("", self.increase1) self.button.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) def gpFinder(self, event): self.clearScreen() self.gpRangeTab = Button(self.myFunctionContainer, width=14, bg="dark grey",relief=SUNKEN, text="Multi-Markup") self.gpRangeTab.bind("", self.gpRange) self.gpRangeTab.grid(row=0, column=0) self.gpExactTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Single Markup") self.gpExactTab.bind("", self.gpExact) self.gpExactTab.grid(row=0, column=1) self.priceIncreaseTab = Button(self.myFunctionContainer, width=14, bg="dark grey", relief=SUNKEN, text="Product Increase") self.priceIncreaseTab.bind("", self.priceIncrease) self.priceIncreaseTab.grid(row=0, column=2) self.gpFinderTab = Button(self.myFunctionContainer, width=14, relief=FLAT, text="Calculate GP") self.gpFinderTab.bind("", self.gpFinder) self.gpFinderTab.grid(row=0, column=3) self.gpCalc1(1) self.title1 = Label(self.myFunctionContainer, font="bold", relief=GROOVE, text="GP Finder") self.title1.grid(padx=0, pady=2, row=1, column=0, columnspan=4, sticky=W+E) self.entry1 = Entry(self.myFunctionContainer, textvariable=self.COG4) self.entry1.select_range(0, END) self.entry1.focus_force() self.entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.entry2 = Entry(self.myFunctionContainer, textvariable=self.markup) self.entry2.select_range(0, END) self.entry2.bind("", self.gpCalc1) self.entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) self.entryTitle = Label(self.myFunctionContainer, text="Enter COG:") self.entryTitle.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.entryTitle2 = Label(self.myFunctionContainer, text="Enter Markup $:") self.entryTitle2.grid(padx=2, pady=2, row=3, column=1, sticky=E) self.button = Button(self.myFunctionContainer, text="Calculate") self.button.bind("", self.gpCalc1) self.button.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) def markup1(self, event): a = [5,10,15,17,18,19,20,21,22,23,24,25,26,27,28,29,30,32,35,40,45,50,55] colors = ['#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF', '#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF', '#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF','#DCDCDC','#FFFFFF'] b = 1 row = 4 while b < len(a): gp = 1-((a[b-1]/100.0)) color = colors[b-1] row = row + 1 markup = round((self.COG1.get()/gp),2) self.gp1 = Label(self.myFunctionContainer, bg=color, width=6, relief=RIDGE, text=(((1-gp)*100),"%")) self.gp1.grid(padx=2, pady=1, row=row ,column=1) self.price1 = Label(self.myFunctionContainer, bg=color, relief=RIDGE, width=10, text=("$",markup)) self.price1.grid(padx=2, pady=1, row=row ,column=2) b = b + 1 def markup2(self, event): GP = 1 - (round((self.GP.get()/100),2)) self.price1 = Label(self.myFunctionContainer, relief=GROOVE, bg="white", width=10, font="bold", text=("$",round((self.COG2.get()/GP),2))) self.price1.grid(pady=1, row=5 ,column=1, columnspan=2) def increase1(self, event): increase = 1+(self.increase.get()/100) self.price1 = Label(self.myFunctionContainer, relief=GROOVE, bg="white", width=10, font="bold", text=("$",round((self.COG3.get()*increase),2))) self.price1.grid(pady=1, row=5 ,column=1, columnspan=2) def gpCalc1(self, event): COG4 = self.COG4.get() markup = self.markup.get() if COG4==0.0 or markup==0.0: self.price1 = Label(self.myFunctionContainer, relief=GROOVE, bg="white", width=10, font="bold", text="") self.price1.grid(pady=1, row=5 ,column=1, columnspan=2) else: GP = 100*(1-(self.COG4.get()/self.markup.get())) self.price1 = Label(self.myFunctionContainer, relief=GROOVE, bg="white", width=10, font="bold", text=(round(GP,2),"%")) self.price1.grid(pady=1, row=5 ,column=1, columnspan=2) def clearScreen(self): self.clear = Label(self.myFunctionContainer) self.clear.grid(row=1, column=0, rowspan=30, columnspan=6, sticky=N+E+S+W) return root = Tk() myapp = MyApp(root) root.mainloop() From bedouglas at earthlink.net Tue Aug 26 11:28:10 2008 From: bedouglas at earthlink.net (bruce) Date: Tue, 26 Aug 2008 08:28:10 -0700 Subject: libxml2dom - parsing maligned html Message-ID: <121101c90790$5966bc80$0301a8c0@tmesa.com> Hi... I'm using quick test with libxml2dom =============== import libxml2dom aa=libxml2dom.parseString(foo) ff=libxml2dom.toString(aa) print ff =============== ---------------------------------- when i start, foo is: . . . ------------------------------- when i print ff it's: ------------------------------- so it's as if the parseString only reads the initial "html" tree. i've reviewed as much as i can find regarding libxml2dom to try to figure out how i can get it to read/parse/handle both html trees/nodes. i know, the html is maligned/screwed-up, but i can't seem to find any app (tidy/beautifulsoup) that can "know" which one of the html trees to throw out/remove!! technically, both html trees are valid, it's just that they both shouldn't be in the file!!! thoughts/comments appreciated thanks From gagsl-py2 at yahoo.com.ar Wed Aug 27 00:25:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 27 Aug 2008 01:25:49 -0300 Subject: Setting my Locale References: <9611.72753382034$1219748098@news.gmane.org> Message-ID: En Tue, 26 Aug 2008 07:52:21 -0300, Robert Rawlins escribi?: > I'm running python 2.5 on a Debian based system and I'm looking for your > advice on how to set the locale for my application. I've read through the > locale module documentation http://docs.python.org/lib/module-locale.html > and tried a couple of the examples but can't seem to get it working. > > > For instance, when I attempt to run the following code: > > > import locale > > locale.setlocale(locale.LC_ALL, 'de_DE') > > > I get an exception raised by the application which says: > > > Traceback (most recent call last): > > File "locale_test.py", line 2, in > > locale.setlocale(locale.LC_ALL, 'de_DE') > > File "/usr/lib/python2.5/locale.py", line 478, in setlocale > > return _setlocale(category, locale) > > locale.Error: unsupported locale setting > > > My questions are; what would be causing this error? Do I need any > additional > packages installed on the system for this locale support to work > properly? Probably you don't have support for 'de_DE' locale. Try using locale.setlocale(locale.LC_ALL, '') and see what you get in response. > How can I get a list of available locales? I'd like to know how to retrieve that too... -- Gabriel Genellina From fredrik at pythonware.com Sat Aug 30 07:15:26 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 30 Aug 2008 13:15:26 +0200 Subject: Which is faster? In-Reply-To: References: Message-ID: cnb wrote: > how does doing something twice not change complexity? yes it maybe > belongs to the same complexity-class but is still twice as slow no? doing two things quickly can still be faster than doing one thing slowly. From larry.bates at websafe.com` Thu Aug 14 12:18:06 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 14 Aug 2008 11:18:06 -0500 Subject: ActiveState Python v2.5 doesn't come with Tkinter or Tk installed. In-Reply-To: References: Message-ID: <5IWdnVWSR6FWxznVnZ2dnUVZ_uqdnZ2d@comcast.com> Dudeja, Rajat wrote: > Hi, > > So, now I've finally started using Eclipse and PyDev as an IDE for my > GUI Application. I just wrote some sample programs as an hands on. > > Now I would like to take up Tkinter. I'm using Active State Python > version 2.5 and found that there is not Tkinter and Tk module in it. > > To use Tkinter do I actually require Tk installed on my machine? Please > suggest and where can I find both these modules? > > Also, please direct me to a good and short document on using Tkinter or > Tk in Python. > > Cheers, > Rajat > > > > Notice: This e-mail is intended solely for use of the individual or entity to which it is addressed and may contain information that is proprietary, privileged, company confidential and/or exempt from disclosure under applicable law. If the reader is not the intended recipient or agent responsible for delivering the message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If this communication has been transmitted from a U.S. location it may also contain data subject to the International Traffic in Arms Regulations or U.S. Export Administration Regulations and cannot be disseminated, distributed or copied to foreign nationals, residing in the U.S. or abroad, without the prior approval of the U.S. Department of State or appropriate export licensing authority. If you have received this communication in error, please notify the sender by reply e-mail or collect telephone call and delete or destroy all copies of this e-mail message, any physical copies made of this e-mail message and/or any file attachment(s). > > NOTE: Please begin your posts with what platform (Linux/Mac/Windows) you are running on so we can answer your questions better. From ActiveState's webpage: All platforms * Tcl/Tk 8.4.14 and Tix 8.4.2 upgrades. It is certainly on my machine which is Windows ActiveState install. You better check again. If you are on Windows, you can use py2exe to package up your program and you won't have to have Python/Tk installation. First hit on Google is: http://wiki.python.org/moin/TkInter -Larry -Larry From michele.simionato at gmail.com Sat Aug 16 10:11:16 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 16 Aug 2008 07:11:16 -0700 (PDT) Subject: Dynamically defined functions via exec in imported module References: <036d8731-5984-4c23-a15d-efe7e01b5d07@x35g2000hsb.googlegroups.com> <979a8a16-0930-4838-9625-0a03784e590b@w7g2000hsa.googlegroups.com> Message-ID: On Aug 16, 4:02?pm, Maric Michaud wrote: > I'd say that everywhere exec/eval are used in a application/function/lib that > doesn't mean to interpret arbitrary and user provided python code, it is a > bad usage Problem is, there are things you cannot do without exec/eval: for instance look at the implementation of my own decorator module, which uses eval to guarantee a good signature for the decorated function. Probably it could be done without exec, with bytecode hacks, but I regard fiddling with bytecodes as something worse than exec itself. I am not sure if in Python 3.0 the signature object is powerful enough to do the job, I never had to time to check how it works. Michele Simionato From cito at online.de Sun Aug 10 07:18:58 2008 From: cito at online.de (Christoph Zwerschke) Date: Sun, 10 Aug 2008 13:18:58 +0200 Subject: Missing exceptions in PEP 3107 In-Reply-To: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> References: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> Message-ID: Matimus schrieb: >> The expr in that "raises" clause should be a list of Exceptions. > > You are clearly confusing the annotation feature with a possible > application of the annotation feature. Annotation could be used for > many different applications besides type safety. Sorry, I wanted to say "*could* be a list of Exceptions". Though this is the most obvious application. In the end, the annotations need to be given a semantical meaning anyway. > Annotation simply creates a dictionary. The name `return` was chosen > for the return value because it _is_ a keyword and therefore could not > conflict with the name of any of the parameters. Using "raises" would > mean that we would have to introduce the name "raises" as a new > keyword. It would be better just to use they existing keyword "raise". Yes, it later also occured to me that it ought to be an existing keyword, i.e. "raise" (or maybe "except"). That's porbably the reason why it is "throw" in C++, and not "throws". > With all of that being said, a package or application that uses > annotation could simply use the data-structure associated with > "return" to also contain exception information. That might not seem > intuitive, but keep in mind that the value associated with "return" in > the associations dictionary is going to be a special case anyway. > > def foo(a: "a info", b: "b info") -> "return info", "exception info": > return "hello world" That would be possible. But I still think it makes sense to separate them, like so: def foo(a: "a info", b: "b info") -> "ret info" raise "exc info": return "hello world" And then the annotation dictionary would contain another key "raise" containing the exc info. This cannot conflict with the name of any other parameter either. Maybe the following syntax would be even more intuitive: def foo(a: "a info", b: "b info") return "ret info" raise "exc info": return "hello world" I don't know how determined the "->" syntax is already. -- Christoph From arne at vajhoej.dk Tue Aug 12 20:40:07 2008 From: arne at vajhoej.dk (=?ISO-8859-1?Q?Arne_Vajh=F8j?=) Date: Tue, 12 Aug 2008 20:40:07 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <48617847$0$5021$607ed4bc@cv.net> <486ae06b$0$5011$607ed4bc@cv.net> <4883bc90$0$7327$607ed4bc@cv.net> Message-ID: <48a22d60$0$90273$14726298@news.sunsite.dk> Robert Maas, http://tinyurl.com/uh3t wrote: > John W Kennedy wrote: > JWK> Into the 60s, indeed, there were still machines being made > JWK> that had no instruction comparable to the mainframe BASx/BALx > JWK> family, or to Intel's CALL. You had to do a subprogram call by > JWK> first overwriting the last instruction of what you were > JWK> calling with a branch instruction that would return back to > JWK> you. > > That's not true, that you needed to do that, that there was no > other way available. The subroutine linkage I invented for S.P.S. > (Symbolic Programming System, i.e. IBM 1620 assembly language) was > to reserve a 5-digit space immediately before the subroutine entry > point for storing the return address. So the caller needed to know > only one address, the entry point, and do both store-return-address > and jump relative to that address, rather than needing to know both > the entry point and the last-instruction-JUMP-needs-patch address > as independent items of information. CDC Cyber did something very similar. Not very recursion friendly. Arne From mblstreet at gmail.com Sat Aug 9 04:59:28 2008 From: mblstreet at gmail.com (Majestic_Mbl) Date: Sat, 9 Aug 2008 01:59:28 -0700 (PDT) Subject: Free Mobile Softwares Message-ID: <9ea26898-3f63-45e5-97d3-fe77dfcd1879@x35g2000hsb.googlegroups.com> Http://www.mobilestreet.net Mobilestreet Download Free Mobile Stuff From Mobile Street. Largest Collection of Mobile Stuff On Internet , Themes , Games , Islamic Section , Ringtones, Funny Movies and Naat Much More Avaliable, Nokia , Sony Ericsson, Motorola, Smart Phones, Pocket Pc and Much More..... http://www.mobilestreet.net From circularfunc at yahoo.se Wed Aug 27 19:50:03 2008 From: circularfunc at yahoo.se (cnb) Date: Wed, 27 Aug 2008 16:50:03 -0700 (PDT) Subject: How come Python software, tools and libraries is so good? A hug to Gvr and the Python community! Message-ID: I have been testing different tools for cvs, math etc and I am constantly amazed how many great tools and libraries there are for Python. SAGE, Mercurial as 2 outstanding tools and there a re excellent libraries fro anything you want, natural language processing, any kind of parsing, math, simulation, neural networks, genetic algorithms, data visualization etc. And everythign just works, download and go! Is this a consequense of the language being so intuitive and easy to use and superwell documented? This then affects how people write code and what programmers are attracted in the first place. Being a bit of a fanboy here but I have never experinced such a satisfaction with a language before. Sure it can get better(I won't take that up in this thread do) but in general I want to give a big hug to GvR and the Python community. From steve at REMOVE-THIS-cybersource.com.au Sun Aug 3 19:02:47 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 03 Aug 2008 23:02:47 GMT Subject: Decimals not equalling themselves (e.g. 0.2 = 0.2000000001) References: Message-ID: <00a6346b$0$20302$c3e8da3@news.astraweb.com> On Sun, 03 Aug 2008 17:30:29 -0500, Larry Bates wrote: >> As you can see, the last two decimals are very slightly inaccurate. >> However, it appears that when n in 1/n is a power of two, the decimal >> does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2 >> and not 0.20000000000000001? >> >> This discrepancy is very minor, but it makes the whole n-th root >> calculator inaccurate. :\ > > What are they teaching in computer science classes these days? I don't know about these days, but 20-odd years ago there was no discussion of floating point accuracy in the Comp Sci classes I did at Melbourne Uni. I did a class in computational mathematics, run by the maths department, and it discussed a lot of issues about accuracy in float calculations. However, if they mentioned anything about e.g. 0.2 not being exactly representable in binary, I slept through it. Maybe that's why I failed that class. *wry grin* -- Steven From sjmachin at lexicon.net Wed Aug 20 18:32:23 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 20 Aug 2008 15:32:23 -0700 (PDT) Subject: Negative integers References: Message-ID: <1e54ed85-7f63-4749-a711-3c571e851f83@r15g2000prh.googlegroups.com> On Aug 21, 7:46 am, Fredrik Lundh wrote: > johnewing wrote: > > I am trying to figure out how to test if two numbers are of the same > > sign (both positive or both negative). I have tried > > > abs(x) / x == abs(y) / y > > > but that fails when one of the numbers is 0. I'm sure that there is > > an easy way to do this. Any suggestions? > > (a < 0) == (b < 0) > That supposes that the OP understands "sign" to mean "the sign bit". Another possibility is the sgn/sign/signum function (http:// en.wikipedia.org/wiki/Sign_function). In that case the answer would be cmp(a, 0) == cmp(b, 0) -- with one big caveat: Although cmp appears to return only -1, 0, or +1, it is documented to return "negative", "zero" or "positive". >>> help(cmp) Help on built-in function cmp in module __builtin__: cmp(...) cmp(x, y) -> integer Return negative if xy. >>> cmp(10, 90) -1 Perhaps safer and better documentation to define your own sign and samesign: sign = lambda x: x < 0 or sign = lambda x: -1 if x < 0 else 0 if x == 0 else 1 samesign = lambda a, b: sign(a) == sign(b) Cheers, John From notvalid2 at sbcglobal.net Fri Aug 22 21:01:04 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Fri, 22 Aug 2008 18:01:04 -0700 Subject: Filling in Degrees in a Circle (Astronomy) In-Reply-To: <511395ff-e823-4d59-ad57-cd6b1ad01d8a@w7g2000hsa.googlegroups.com> References: <511395ff-e823-4d59-ad57-cd6b1ad01d8a@w7g2000hsa.googlegroups.com> Message-ID: Mensanator wrote: > On Aug 22, 6:12 pm, "W. eWatson" wrote: >> The other night I surveyed a site for astronomical use by measuring the >> altitude (0-90 degrees above the horizon) and az (azimuth, 0 degrees north >> clockwise around the site to 360 degrees, almost north again) of obstacles, >> trees. My purpose was to feed this profile of obstacles (trees) to an >> astronomy program that would then account for not sighting objects below the >> trees. >> >> When I got around to entering them into the program by a file, I found it >> required the alt at 360 azimuth points in order from 0 to 360 (same as 0). >> Instead I have about 25 points, and expected the program to be able to do >> simple linear interpolation between those. >> >> Is there some simple operational device in Python that would allow me to >> create an array (vector) of 360 points from my data by interpolating between >> azimuth points when necessary? All my data I rounded to the nearest integer. >> Maybe there's an interpolation operator? >> >> As an example, supposed I had made 3 observations: (0,0) (180,45) and >> (360,0). I would want some thing like (note the slope of the line from 0 to >> 179 is 45/180 or 0.25): >> alt: 0, 0.25, 0.50, 0.75, ... 44.75, 45.0 >> az : 0, 1, 2, 3, 180 >> >> Of course, I don't need the az. > > On Aug 22, 6:12 pm, "W. eWatson" wrote: >> The other night I surveyed a site for astronomical use by measuring the >> altitude (0-90 degrees above the horizon) and az (azimuth, 0 degrees north >> clockwise around the site to 360 degrees, almost north again) of obstacles, >> trees. My purpose was to feed this profile of obstacles (trees) to an >> astronomy program that would then account for not sighting objects below the >> trees. >> >> When I got around to entering them into the program by a file, I found it >> required the alt at 360 azimuth points in order from 0 to 360 (same as 0). >> Instead I have about 25 points, and expected the program to be able to do >> simple linear interpolation between those. >> >> Is there some simple operational device in Python that would allow me to >> create an array (vector) of 360 points from my data by interpolating between >> azimuth points when necessary? All my data I rounded to the nearest integer. >> Maybe there's an interpolation operator? >> >> As an example, supposed I had made 3 observations: (0,0) (180,45) and >> (360,0). I would want some thing like (note the slope of the line from 0 to >> 179 is 45/180 or 0.25): >> alt: 0, 0.25, 0.50, 0.75, ... 44.75, 45.0 >> az : 0, 1, 2, 3, 180 >> >> Of course, I don't need the az. > >>>> for az in xrange(181): > print (az,az*0.25), > > (0, 0.0) (1, 0.25) (2, 0.5) (3, 0.75) > (4, 1.0) (5, 1.25) (6, 1.5) (7, 1.75) > (8, 2.0) (9, 2.25) (10, 2.5) (11, 2.75) > (12, 3.0) (13, 3.25) (14, 3.5) (15, 3.75) > (16, 4.0) (17, 4.25) (18, 4.5) (19, 4.75) > (20, 5.0) (21, 5.25) (22, 5.5) (23, 5.75) > etc. Yes, that works, but that was only a simple illustration. My data looks in fact looks like this (only a few values given: Az Alt 0 18 18 18 27 16 34 20 48 20 ... 268 28 290 32 ... So the python software should generate 0 18 1 18 2 18 3 18 ... the trees are all about 18 degrees high 18 18 19 17.9 we have a slight slope. I'm using values that might be close 20 27.75 21 ... 27 16 28 16.4 now the trees are starting to get a little higher 29 16.9 ... 359 18 (most likely. I didn't have the patience to make a measure at 359) That should pretty well illustrate it. In actuality, as I swept around the circle, the tree line becomes much more abrupt than those first few data points. The tallest tree is at 36 degrees and is among some other equally tall trees. > > But are you saying if you have two readings of tree tops > > * > * > x * > x * > * x * > * x * > ____*_x_*______ > > > And you linearly interpret between them exactly. I put a value there -- x > > / > /* > / * > / * > / * > /* * > * * > ____*___*______ > > that the area below the dashed line is assumed to be hidden? Yes, the telescope software will see that it cannot move the telescope into that area. Surprisingly, they use interpolation. For example, suppose the two trees in your illustration are at an az of 100 and 101, and the two altitudes are 3 and 7. Suppose the telescope wants to go below the line into 100.622 az and an alt of 2.42. The software will say no you don't. > > That wouldn't necessarily be true, as the tree profile could > dip below the line. > > / > /* > / * > / ** > / *** > /* **** > ** **** > ___***_****____ > > Of course, if you take enough points, the open areas may be small > enough not to be practical to worry about. From rweir at ertius.org Wed Aug 13 02:07:57 2008 From: rweir at ertius.org (Rob Weir) Date: Wed, 13 Aug 2008 16:07:57 +1000 Subject: Downloading and Installing gasp References: Message-ID: <87k5eltpky.fsf@hypercube.ertius.org> On 13 Aug 2008, Cyprian Kumwaka wrote: > I am a beginner in Python. Please tell me how to go about in > downloading and installing the module gasp.I am using Python 2.5.2. What OS are you using? Do you have PyGame installed already? -- -rob From dlenski at gmail.com Mon Aug 18 11:28:53 2008 From: dlenski at gmail.com (Dan Lenski) Date: Mon, 18 Aug 2008 08:28:53 -0700 (PDT) Subject: Factory for Struct-like classes References: Message-ID: On Aug 13, 1:30?pm, Christian Heimes wrote: > Trynamedtuplehttp://code.activestate.com/recipes/500261/ > > Anamedtupleimplementation is part of Python 2.6 and 3.0. For older > versions of Python use the recipe from activestate. > > Christian This named tuple recipe is pretty cool... I think there may be a slight bug in the Python docs, though. The ActiveState page explains that it avoids the overhead of a per-instance __dict__ by using the __slots__ variable. However, according to the most-recent Python docs, __slots__ does *NOT* work with subclasses of list, str, or tuple. From http://docs.python.org/ref/slots.html#l2h-222: # __slots__ do not work for classes derived from ``variable-length'' built-in types such as long, str and tuple. On the other hand, nametuple does appear to work as advertised. >>> Person=namedtuple.namedtuple('Person', ('name', 'age', 'height')) >>> p=Person('Bob', 24, 1.86) >>> p.name 'Bob' >>> p.shoe_size AttributeError: 'Person' object has no attribute 'shoe_size' >>> p.__dict__ AttributeError: 'Person' object has no attribute '__dict__' So is there a bug in the Python docs? Does __slots__ in fact work with subclasses of tuple? Dan From __peter__ at web.de Mon Aug 18 12:27:53 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 18 Aug 2008 18:27:53 +0200 Subject: Weird expression result References: <83803185-725e-45bb-b2fe-1add2868bd34@c58g2000hsc.googlegroups.com> Message-ID: Dan Lenski wrote: > On Mon, 18 Aug 2008 18:04:32 +0200, Peter Otten wrote: >> This works just like a < b < c: >> >>>>> 3 in [3] and [3] == True >> False > Interesting. I agree with the OP that it is confusing! > > Does this expansion really get invoked every time there is an expression > of the form?? > > expr1 binary_op1 expr2 binary_op2 expr3 ... > > Seemingly, the answer is yes: > > >>> 3 in [3] in [[3],[4]] in [[[3],[4]],5] == [[[3],[2+2]],5] > True > > How does this play with standard precedence rules? Simple, all comparisons have the same priority: http://docs.python.org/ref/comparisons.html Peter From ewertman at gmail.com Tue Aug 19 21:44:04 2008 From: ewertman at gmail.com (Eric Wertman) Date: Tue, 19 Aug 2008 21:44:04 -0400 Subject: Storing Passwords Message-ID: <92da89760808191844p1c05cd30qad208fe4b28ba8b2@mail.gmail.com> I've a number of scripts set up that require a username/password combination to log in elsewhere. It's gotten to the point where I need to keep them in a more secure location, instead of just in the scripts themselves. I did a bit of searching, and haven't come up with a great way to store passwords using 2-way encryption (I have to send them as plain text). Has anyone seen anything that fits this need? I whipped up something using base64 and pickle, to keep them in a dictionary and at least prevent them from being plain text, but it seems a bit insecure all the same. Any ideas, much appreciated. Thanks! Eric From nodrogbrown at gmail.com Wed Aug 27 13:10:57 2008 From: nodrogbrown at gmail.com (gordon) Date: Wed, 27 Aug 2008 10:10:57 -0700 (PDT) Subject: Tkinter event loop question Message-ID: <9eaef6c3-c913-497f-8ca2-0466eb178c7a@z6g2000pre.googlegroups.com> is it possible to send a message to the gui instance while the Tk event loop is running?I mean after i create a gui object like root=Tk() mygui=SomeUI(root) and call root.mainloop() can i send message to mygui without quitting the ui or closing the window?i tried some code like mygui.someMethod() but it only gets executed after i close the the ui window.Is there a way to get this message passing while gui is running ? (forgive me ,it is a repeat question..but i am a bit desperate) thanks gordon From dullrich at sprynet.com Tue Aug 12 12:27:26 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 12 Aug 2008 11:27:26 -0500 Subject: How to best explain a "subtle" difference between Python and Perl ? References: <4290ea3f-43b9-455d-bd60-587369842c5b@s50g2000hsb.googlegroups.com> Message-ID: In article <4290ea3f-43b9-455d-bd60-587369842c5b at s50g2000hsb.googlegroups.com>, Palindrom wrote: > Hi everyone ! > > I'd like to apologize in advance for my bad english, it's not my > mother tongue... > > My girlfriend (who is a newbie in Python, but knows Perl quite well) > asked me this morning why the following code snippets didn't give the > same result : > > ### Python ### > > liste = [1,2,3] > > def foo( my_list ): Right now my_list is a local variable - since you called foo(liste), the name my_list is bound to the object liste > my_list = [] But this line doesn't modify liste, instead it binds the name my_list to a different object. If you want to modify the list that my_List points to you could do it in either of two ways: def foo1(my_liste): del my_liste[:] def foo2(my_liste): my_liste[:] = [] > foo(liste) > > print liste# she expected liste to be an empty list > > ### Perl ### > > @lst =(1,2,3); > $liste =\@lst; > foo($liste); > print "@lst\n"; > > sub foo { > my($my_list)=@_; > @{$my_list}=() > } > > I have to admit that I don't know how to clearly explain to her the > differences between these results. > Could someone please help us understand these difference between > Python and Perl ? > > Thanks in advance, > P4|1ndr0m -- David C. Ullrich From avinashvora at gmail.com Mon Aug 4 03:25:20 2008 From: avinashvora at gmail.com (Avinash Vora) Date: Mon, 4 Aug 2008 12:55:20 +0530 Subject: Teething troubles with Python on a Mac In-Reply-To: <4896725F.20806@cosc.canterbury.ac.nz> References: <6651edd6-d47f-4e10-bf0b-0875190b9bc2@a1g2000hsb.googlegroups.com> <489546F1.9050102@cosc.canterbury.ac.nz> <3dcf39de-3c3c-4e47-abb4-508d1601a9e2@z11g2000prl.googlegroups.com> <4896725F.20806@cosc.canterbury.ac.nz> Message-ID: (Greg: You only sent the email to me: you probably wanted to add the mailing list to the recipients.) On Aug 4, 2008, at 8:37 AM, greg wrote: > Avi wrote: > >> On that: how would I go about updating the system Python, then? > > The usual advice is not to try to do that at all. > Generally it's best to treat anything in /System > as off-limits. Right, but I meant if there is an Apple-sanctioned way. I guess not? >> (I used to do so, but it >> caused so many issues with installing new packages that I gave up on >> it) > > I've very rarely had any problem with maintaining my > own Python installation, but as I said, I always install > packages using "python setup.py". I guess I'll give it a shot, then. Alias in bash to MacPython, I assume? > Python itself copes very well with having multiple > versions installed, on all platforms, but you have to > do things the Python way. My point was that it seems to be a bit of a hack. Thanks for the advice from everyone, though. -- Avi From rocksportrocker at googlemail.com Sat Aug 2 07:07:35 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Sat, 2 Aug 2008 04:07:35 -0700 (PDT) Subject: Interconvert a ctypes.Structure to/from a binary string? References: Message-ID: On 2 Aug., 08:35, Andrew Lentvorski wrote: > Basically, I'd like to use the ctypes module as a much more descriptive > "struct" module. > > Is there a way to take a ctypes.Structure-based class and convert it > to/from a binary string? > > Thanks, > -a My first idea was : from ctypes import * from pickle import * class T(Structure): pass print dumps(T()) which raises an TypeError, "abstract class". And then I found http://osdir.com/ml/python.ctypes/2006-03/msg00009.html Greetings, Uwe From michael.pearmain at tangozebra.com Wed Aug 13 06:56:43 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Wed, 13 Aug 2008 03:56:43 -0700 (PDT) Subject: Perl to Python using MqSQLdb References: Message-ID: <25143519-21fd-4b2e-962d-b20c34331435@z66g2000hsc.googlegroups.com> Thanks for that Daniel, I've been able to apply the logic to the rest of the script i'm converting. There are only two bits that i don't understand in the Perl script that i need to convert, my $sql = shift; and my @row = $sth->fetchrow_array; $$StartDate = $row[0]; $$EndDate = $row[1]; $sth->finish() can you offer any advise? Mike From deets at nospam.web.de Mon Aug 25 18:38:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Aug 2008 00:38:57 +0200 Subject: Replace reduce with listcomprehension? In-Reply-To: <3a99c7ea-4cc9-4b9f-b6f8-60856cbd8837@c58g2000hsc.googlegroups.com> References: <3a99c7ea-4cc9-4b9f-b6f8-60856cbd8837@c58g2000hsc.googlegroups.com> Message-ID: <6hgqk1Flobm0U1@mid.uni-berlin.de> ssecorp schrieb: > GvR wants to eliminate all the functional stuff (lambda map reduce > filter) which kind of makes sense for Python, listcomprehensions are > more efficient(at least as implemented inpython) from what i have > gathered and they can express everything map/reduce/filter with > crippled lambdas can. > > but what about this: > reduce(lambda x,y:x*y+x,[1,2,3,4,5,6]) > > how would I express that in a listcomprehension? You can't. And AFAIK your are wrong - GvR doesn't wan to eliminate the functional stuff. http://www.artima.com/weblogs/viewpost.jsp?thread=98196 http://www.python.org/dev/peps/pep-3099/ Diez From martin at v.loewis.de Mon Aug 11 17:28:02 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 11 Aug 2008 23:28:02 +0200 Subject: dict.update() useful or not? In-Reply-To: References: <00b06f78$0$14351$c3e8da3@news.astraweb.com> Message-ID: <48a0aee2$0$24005$9b622d9e@news.freenet.de> >> def create_request(url, headers): >> headers.update(DEFAULT_HEADERS) >> req = urllib2.Request(url, None, headers) >> # ... >> return req >> >> but of course this second example does the Wrong Thing, replacing >> explicit headers with default values. > > There's a second code smell with that: even if it did what you want it > isn't nice to mutate the parameter passed in as headers. What if the caller > wants to reuse the headers again for another call? Just in case it isn't clear what the problem with that code is: create_request is a function, ie. it returns a value. As such, it shouldn't have any side effects. If it has side effects, it should be considered a procedure, and return None. Regards, Martin From max at alcyone.com Tue Aug 26 02:52:59 2008 From: max at alcyone.com (Erik Max Francis) Date: Mon, 25 Aug 2008 23:52:59 -0700 Subject: why in returns values for array and keys for dictionary In-Reply-To: <3e4f4d98-3255-4916-9337-e926aaeb6a20@p10g2000prf.googlegroups.com> References: <3e4f4d98-3255-4916-9337-e926aaeb6a20@p10g2000prf.googlegroups.com> Message-ID: ++imanshu wrote: > Wouldn't it be nicer to have 'in' return values (or keys) for both > arrays and dictionaries. Arrays and Dictionaries looked so similar in > Python until I learned this difference. It's because dealing with keys makes far more sense, since that's how the dictionary data structure works. If you're doing this an awful lot -- whether testing for inclusion or iterating -- then you're probably using the wrong data structure. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Well I have been puppetized / Oh how I have compromised -- Lamya From cniall at icedcerulean.com Sun Aug 3 10:02:31 2008 From: cniall at icedcerulean.com (CNiall) Date: Sun, 03 Aug 2008 15:02:31 +0100 Subject: Decimals not equalling themselves (e.g. 0.2 = 0.2000000001) Message-ID: <4895BA77.2030508@icedcerulean.com> I am very new to Python (I started learning it just yesterday), but I have encountered a problem. I want to make a simple script that calculates the n-th root of a given number (e.g. 4th root of 625--obviously five, but it's just an example :P), and because there is no nth-root function in Python I will do this with something like x**(1/n). However, with some, but not all, decimals, they do not seem to 'equal themselves'. This is probably a bad way of expressing what I mean, so I'll give an example: >>> 0.5 0.5 >>> 0.25 0.25 >>> 0.125 0.125 >>> 0.2 0.20000000000000001 >>> 0.33 0.33000000000000002 As you can see, the last two decimals are very slightly inaccurate. However, it appears that when n in 1/n is a power of two, the decimal does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2 and not 0.20000000000000001? This discrepancy is very minor, but it makes the whole n-th root calculator inaccurate. :\ From fredrik at pythonware.com Fri Aug 15 10:55:17 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 15 Aug 2008 16:55:17 +0200 Subject: Early halt for iterating a_list and iter(a_list) In-Reply-To: References: Message-ID: Lie wrote: > When you've got a nested loop a StopIteration in the Inner Loop would > break the loop for the outer loop too: > > a, b, c = [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5] > > def looper(a, b, c): > for a_ in a: > for b_ in b: > for c_ in c: > print a_, b_, c_ > > looper(a, b, c) # Intended behavior [1] > a, b, c = iter(a), b, iter(c) # b is intentionally not iter()-ed > looper(a, b, c) # Inner StopIteration prematurely halt outer loop [2] iterators are once-only objects. there's nothing left in "c" when you enter the inner loop the second time, so nothing is printed. >>> a = range(10) >>> a = range(5) >>> a = iter(a) >>> for i in a: ... print i ... 0 1 2 3 4 >>> for i in a: ... print i ... >>> > This is a potential problem since it is possible that a function that > takes an iterable and utilizes multi-level looping could be > prematurely halted and possibly left in intermediate state just by > passing an iterator. it's a problem only if you confuse iterators with sequences. From robert2821 at verizon.net Thu Aug 21 22:22:15 2008 From: robert2821 at verizon.net (robert2821) Date: Thu, 21 Aug 2008 22:22:15 -0400 Subject: Decorators using instance variables Message-ID: <48AE22D7.2070803@verizon.net> Hi, I'm new; greetings all! I'm wondering if the following program should work. I think it should print 'Hello, World', but instead it produces a TypeError. Is this a bug in decorators, a feature of them, or a mistake or misunderstanding on my part? TIA, Bob def getdec (f): dec = decorator (f) return dec. docall class decorator: def __init__ (self, f): self. f = f def docall (self, *a): return self. f (*a) class test: @ getdec def doit (self, message): print message if __name__ == '__main__': foo = test () foo. doit ('Hello, world') -------------- next part -------------- A non-text attachment was scrubbed... Name: Dec.py Type: text/x-python Size: 327 bytes Desc: not available URL: From rafesacks at gmail.com Fri Aug 15 14:02:36 2008 From: rafesacks at gmail.com (Rafe) Date: Fri, 15 Aug 2008 11:02:36 -0700 (PDT) Subject: Handling Property and internal ('__') attribute inheritance and creation Message-ID: Hi, I've been thinking in circles about these aspects of Pythonic design and I'm curious what everyone else is doing and thinks. There are 3 issues here: 1) 'Declaring' attributes - I always felt it was good code practice to declare attributes in a section of the class namespace. I set anything that is constant but anything variable is set again in __init__(): Class A(object): name = "a name" type = "a typee" childobject = None def __init__(self, obj): self.childobject = object This makes it easy to remember and figure out what is in the class. Granted there is nothing to enforce this, but that is why I called it 'code practice'. Do you agree or is this just extra work? 2) Internal attributes (starting with 2x'_') aren't inherited. Do you just switch to a single '_' when you want an "internal" attribute inherited? These are attributes I want the classes to use but not the user of these classes. Of course, like anything else in Python, these aren't really private. It is just a convention, right? (The example for #3 shows this.) 3) It isn't possible to override a piece of a Property Descriptor. To get around this, I define the necessary functions in the class but I define the descriptor in the __new__() method so the inherting class can override the methods. Am I overlooking some basic design principle here? This seems like a lot of work for a simple behavior. Example: class Base(object): def __new__(cls): setattr(cls, "state", property(fget = cls._Get_state, fset = cls._Set_state, fdel = None, doc = cls._doc_state)) obj = super(Base, cls).__new__(cls) return obj state = None # Set in __new__() _state = True _doc_state = "The state of this object" def _Get_state(self): return self._state def _Set_state(self, value): self._state = value class Child(Base): def _Get_state(self): # Do some work before getting the state. print "Getting the state using the child's method" return self._state print Child().state Please share your thoughts, - Rafe From dudeja.rajat at gmail.com Fri Aug 29 12:16:06 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Fri, 29 Aug 2008 17:16:06 +0100 Subject: How to check is something is a list or a dictionary or a string? Message-ID: Hi, How to check if something is a list or a dictionary or just a string? Eg: for item in self.__libVerDict.itervalues(): self.cbAnalysisLibVersion(END, item) where __libVerDict is a dictionary that holds values as strings or lists. So now, when I iterate this dictionary I want to check whether the item is a list or just a string? Thanks, Rajat From jake at vapourforge.com Wed Aug 6 20:37:23 2008 From: jake at vapourforge.com (Jake Anderson) Date: Thu, 07 Aug 2008 10:37:23 +1000 Subject: benchmark In-Reply-To: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> Message-ID: <489A43C3.8050207@vapourforge.com> Jack wrote: > I know one benchmark doesn't mean much but it's still disappointing to see > Python as one of the slowest languages in the test: > > http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy/ > > > -- > http://mail.python.org/mailman/listinfo/python-list > Something to note though, The python version is ~ half the length of the rest of them ;-> From poojaangali at gmail.com Fri Aug 15 05:59:50 2008 From: poojaangali at gmail.com (pooja) Date: Fri, 15 Aug 2008 02:59:50 -0700 (PDT) Subject: EARN MONEY $1500-$5000 PER MONTH Message-ID: <8d4fba5d-21c2-424a-982e-707afc3dfa64@u6g2000prc.googlegroups.com> EARN MONEY $1500-$5000 PER MONTH SIMPLE ONLINE SURVEY CREATE UR ACCOUNT AND EARN IMMEDIATLY ************************************************************************* http://www.AWSurveys.com/HomeMain.cfm?RefID=kingraja666 ************************************************************************* From woodygar at sky.com Thu Aug 7 13:55:46 2008 From: woodygar at sky.com (garywood) Date: Thu, 7 Aug 2008 18:55:46 +0100 Subject: very newbie question Message-ID: <5F1D8E1D20CE4B7D9E874FED0AFFD677@Home> stuck on python for absolute beginners chapter 6 i actually done what i was supposed to do use the function ask_number for guess a number but for some reason it does not count correctly the number of tries # Guess My Number # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money import random print "\tWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 100." print "Try to guess it in as few attempts as possible.\n" # set the initial values def ask_number(): the_number = random.randrange(100) + 1 guess = int(raw_input("Take a guess: ")) tries = 1 while (guess != the_number): if (guess > the_number): print "Lower..." else: print "Higher..." tries += 1 guess = int(raw_input("Take a guess: ")) tries += 1 ask_number() print "You guessed it! The number was", the_number print "And it only took you", tries, "tries!\n" raw_input("\n\nPress the enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: From gjhames at gmail.com Thu Aug 14 11:25:55 2008 From: gjhames at gmail.com (Gewton Jhames) Date: Thu, 14 Aug 2008 12:25:55 -0300 Subject: Replace Several Items In-Reply-To: <48A40A6C.3030509@egenix.com> References: <513926b0-64fe-4fdc-bb33-bc4b8ad3ab10@a70g2000hsh.googlegroups.com> <1218664455.5179.20.camel@jmk> <48A40A6C.3030509@egenix.com> Message-ID: <23bdbe700808140825na62bbbby7b957e630fe69ff8@mail.gmail.com> thanks, guys. On Thu, Aug 14, 2008 at 7:35 AM, M.-A. Lemburg wrote: > On 2008-08-13 23:54, John Krukoff wrote: > >> On Wed, 2008-08-13 at 09:39 -0700, gjhames wrote: >> >>> I wish to replace several characters in my string to only one. >>> Example, "-", "." and "/" to nothing "" >>> I did like that: >>> my_string = my_string.replace("-", "").replace(".", "").replace("/", >>> "").replace(")", "").replace("(", "") >>> >>> But I think it's a ugly way. >>> >>> What's the better way to do it? >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> >> The maketrans interface is a bit clunky, but this is what >> string.translate is best at: >> >> ?>>> import string >> >>> '-./other'.translate( string.maketrans( '', '' ), '-./' ) >>>>> >>>> 'other' >> >> It'd be interesting to see where it falls in the benchmarks, though. >> >> It's worth noting that the interface for translate is quite different >> for unicode strings. >> > > Right. Unicode .translate() uses a dictionary for defining the > mapping. > > Another approach is to use the re module: > > >>> import re > >>> re.sub('[-./()]', '', '-./other') > 'other' > > -- > Marc-Andre Lemburg > eGenix.com > > Professional Python Services directly from the Source (#1, Aug 14 2008) > >>> Python/Zope Consulting and Support ... http://www.egenix.com/ > >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ > >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ > ________________________________________________________________________ > > :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: > > > eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 > D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg > Registered at Amtsgericht Duesseldorf: HRB 46611 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From duane.kaufman at gmail.com Thu Aug 7 10:13:05 2008 From: duane.kaufman at gmail.com (TheSeeker) Date: Thu, 7 Aug 2008 07:13:05 -0700 (PDT) Subject: Adding Microsoft objects in Boa Constuctor Palette References: <26b16796-f717-40bb-b6e9-a918598b44e2@d77g2000hsb.googlegroups.com> Message-ID: <92cc447d-e3b4-4092-b755-529bbcc07a22@x41g2000hsb.googlegroups.com> On Aug 6, 5:59 pm, Sid K wrote: > This is what I wanted to do: > > Add Microsoft Active objects like Excel sheets and Word files to the > Palette in Boa Constructor. There is a User tab in the GUI builder > menu, but I'm not sure how to use/enable it. > > 1. Does anyone know how to do this? > 2. Is anyone aware of any work that is currently going on to support > adding Microsoft objects in Boa. > 3. Does any other Python GUI creator/editor exist out there that can > do this? > 4. How would one add an excel sheet to a wx.Panel in general w/ or w/o > Boa? > > Looking forward to replies... > > -SK Hi, You might get a response by trying the wxPython list: wxPython- users at lists.wxwidgets.org or the Boa list: boa-constructor- users at lists.sourceforge.net Duane From google at mrabarnett.plus.com Thu Aug 21 21:29:44 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 21 Aug 2008 18:29:44 -0700 (PDT) Subject: Unexpected regex result Message-ID: <1ea54287-7228-448c-a9f9-ad67e05a4663@r66g2000hsg.googlegroups.com> I'm working on the sources for the regex module (_sre.c) but I've come across some behaviour that I wasn't aware of before: >>> re.match('((a)|b)*', 'abc').groups() ('b', 'a') The regex module was modified to return this instead of the previous ('b', '') in issue #725106 because both Perl and sed returned this. My version of the module returns ('b', None), which was what I thought/ expected was the correct answer. Could someone explain to me what the rationale for returning ('b', 'a') is? Is it just because Perl and sed do this? (And if so, why has it been decided that it shouldn't be possible to split a string on a zero-width match even though Perl does? :-() From castironpi at gmail.com Mon Aug 25 16:03:09 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 25 Aug 2008 13:03:09 -0700 (PDT) Subject: Struct class random access Message-ID: <7986a90f-bf53-47f9-a327-f6249680594c@z66g2000hsc.googlegroups.com> struct.Struct lets you encode Python objects into structured memory. It accepts a format string, and optionally a buffer and offset to/from which to read/write the structure. What do you think of random access for the results? (unproduced) >>> packer= struct.Struct( 'IIIf255p' ) >>> packer.pack_into( buf, off, 10, 20, 30, 0.5, 'abc' ) >>> packer.unpack_from( buf, off, 2 ) #reads field 2 30 Does this take a PEP, or just a patch submission? From larry.bates at websafe.com` Mon Aug 4 08:25:35 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 04 Aug 2008 07:25:35 -0500 Subject: Using two pythons in an application In-Reply-To: References: Message-ID: Allen wrote: > Larry Bates wrote: >> Allen wrote: >>> I'm in the process of developing an application that will use Python >>> for a scripting support. In light of the upcoming changes to Python, >>> I was wondering if it is possible to link to and use two different >>> versions of Python so that in the future, scripts could be migrated >>> to the new version, and older scripts would still work as well. If >>> so are there any code examples of this. >>> >>> Brian Vanderburg II >> >> Unlike languages you pay for, Python has on real motivation to >> "obsolete" old versions of Python (e.g. to force you to pay of an >> upgrade). You can still get version 1.5.2 of Python and it is MANY >> years old and most could consider quite obsolete. I just would not >> worry about it and stick with 2.5/2.6 for development and begin >> looking at Python 3.0 so I can learn what's new and exciting. >> >> -Larry > > I agree. I had wanted for scripts of the program to be able to use the > new string format method that is only in py3k, but I'm currently looking > into other template solutions. > > Brian Vanderburg II There are many good ones around that you can look at: http://www.webwareforpython.org/Papers/Templates/ -Larry From pavlovevidence at gmail.com Tue Aug 26 23:50:42 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 26 Aug 2008 20:50:42 -0700 (PDT) Subject: What's your first choice if you have to write a C module for python? References: Message-ID: <15154823-51ea-4b4b-8401-a33e71964710@p25g2000hsf.googlegroups.com> On Aug 26, 8:19 am, ??? wrote: > What's your first choice when you have write a C/C++ module for Python? 1. Plain C code 2. Implement my own C extension code generator in Python 3. ctypes ... ... Infinity. SWIG Carl Banks From steven at REMOVE.THIS.cybersource.com.au Fri Aug 8 06:25:43 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 08 Aug 2008 10:25:43 GMT Subject: Best practise implementation for equal by value objects References: <135eb396-6daa-4ff4-a722-253ba149889c@27g2000hsf.googlegroups.com> <573362d6-5356-4029-8ee4-f43248263976@p25g2000hsf.googlegroups.com> <71daf8cf-024c-4ab1-b050-7f1f626e89c0@r66g2000hsg.googlegroups.com> Message-ID: On Fri, 08 Aug 2008 00:28:02 -0700, Slaunger wrote: > OK, i am encouraged to carry on my quest with the eval(repr)) for my > 'nice' classes. > I just revisited the documentation for eval and noticed that there are > optional globals > and locals name space variables, that one could specify: > > http://docs.python.org/lib/built-in-funcs.html > > Quite frankly I do not understand how to make use of these parameters, > but it is my feeling > that if I enforce a convention of always specifying the globals/locals > parameter in a specific > manner: > assert eval(repr(x), globals, locals) == x would work independent of how > I have imported the module under test. > > Now, I just need to figure out if this is right and how to specify the > globals and locals if that is not too cumbersome... or maybe I am just > over-engineering... I think it is infeasible for the repr() of an object to know where it was imported from. Including the globals and locals in the call to eval() won't help you, because they can have changed between the time you created the instance and the time you call repr(). Consider: >>> import datetime >>> x = datetime.time(20, 21, 22) >>> x datetime.time(20, 21, 22) >>> eval(repr(x)) == x True So far so good! But now watch this, starting in a fresh session: >>> import datetime as timedate >>> t = timedate.time >>> timedate.tttime = timedate.time >>> del timedate.time >>> assert t is timedate.tttime >>> >>> x1 = t(20, 21, 22) >>> x2 = timedate.tttime(20, 21, 22) >>> assert x1 == x2 What should repr(x1) and repr(x2) be, for your invariant eval(repr(x))==x to hold? It gets better (or worse): >>> alist = [None, t, None] >>> del t, timedate >>> x3 = alist[1](20, 21, 22) >>> assert x1 == x2 == x3 What should the repr() of x1, x2, x3 be now? Bringing this back to the unittests... as I see it, there's an easy way to solve your problem. In the unittest, just do something like the following: # repr(x) looks like "module.class(arg)", # but we actually import it as package.module.submodule.class module = package.module.submodule assert eval(repr(x)) == x I think that is all you need to do. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 15 09:14:08 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2008 13:14:08 GMT Subject: negative numbers are not equal... References: <48A4932F.4010302@gmail.com> <2e66b313-d2b1-4ca1-804f-6af79b252739@j22g2000hsf.googlegroups.com> Message-ID: <00b57c1d$0$14351$c3e8da3@news.astraweb.com> On Thu, 14 Aug 2008 20:44:32 -0700, castironpi wrote: > For > > a= 6 > b= a > > the test > > a is b > > should clearly return true. Since Python promises not to make a copy of a when you execute "b = a", then I think that such behaviour is guaranteed by the language. > Python distinguishes what mathematics does > not, between identity and equality. Clearly 5+4 and 6+3 - evaluate- to > the same, but math doesn't define whether they are the same, and in some > sense the question isn't asked ordinarily, or isn't debated. I want to > infer that math doesn't define the 'is' relation as Python knows it. Mathematicians often *define* equality as identity. That certainly makes sense when dealing with numbers -- what would it mean to say that there are (say) three different instances of the abstract integer 42, all equal yet not identical? I suggest that this simply doesn't make sense -- it is "not even wrong". Equality-as-identity may not hold in all areas of mathematics, but I think it is safe to say it holds for ideal (abstract) numbers, as opposed to implementations of numbers as bit patterns or objects in memory. http://en.wikipedia.org/wiki/Equality_(mathematics) -- Steven From straton at lampsacos.demon.co.uk Fri Aug 29 07:04:20 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 29 Aug 2008 12:04:20 +0100 Subject: class definition syntax In-Reply-To: <41b9bc43-8b48-40d6-bd2d-4578371bb8dc@i24g2000prf.googlegroups.com> References: <41b9bc43-8b48-40d6-bd2d-4578371bb8dc@i24g2000prf.googlegroups.com> Message-ID: harryos wrote: > hi > i have seen some class definitions like > > class MyClass(object): > def __init__(self): > .... > > what does the object keyword inside the braces in MyClass() mean? > Has it got any significance? > > thanks in advance > harry It is a syntax used for 'new type' classes, not so new any more. If you google that phrase, you get many references. Here is a tutorial dating back to 2005. http://www.geocities.com/foetsch/python/new_style_classes.htm From bearophileHUGS at lycos.com Thu Aug 28 14:13:06 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 28 Aug 2008 11:13:06 -0700 (PDT) Subject: Problem with list.insert References: Message-ID: Subhabrata, it's very difficult for me to understand what your short program has to do, or what you say. I think that formatting and code style are important. So I suggest you to give meaningful names to all your variable names, to remove unused variables (like n), to add blank likes here and there to separate logically separated parts of your program, or even better to split it into functions. You can remove some intermediate function, coalescing few logically related operations into a line, you can put spaces around operators like = and after a commas, you can show an usage example in English, so people can understand what the program is supposed to to, you can avoid joining and then splitting strings again, remove useless () around certain things. This is a possible re-write of the first part of your code, it's not exactly equal... def input_words(): input_message = "Print one English sentence for dictionary check: " return raw_input(input_message).lower().split() def load_dictionary(): return set(line.rstrip() for line in open("words.txt")) def dictionary_search(dictionary, words): found = [] not_found = [] for word in words: if word in dictionary: found.append(word) else: not_found.append(word) return found + not_found inwords = input_words() dictionary = load_dictionary() print dictionary_search(dictionary, inwords) It's far from perfect, but you can use it as starting point for a rewrite of your whole program. Bye, bearophile From hubaghdadi at gmail.com Wed Aug 20 06:53:33 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Wed, 20 Aug 2008 03:53:33 -0700 (PDT) Subject: Basic importing question References: Message-ID: On Aug 20, 5:43 am, John Machin wrote: > On Aug 20, 8:08 pm, Hussein B wrote: > > > Hey, > > Suppose I have a Python application consists of many modules (lets say > > it is a Django application). > > If all the modules files are importing sys module, how many times the > > sys module will be compiled and executed? > > Only once (the first time the PVM locates, compiles and executes the > > sys module)? or once for each module importing sys? > > Thanks. > > sys is a built-in module, so the answer is zero times. > > For a non-builtin module foo where there exists: > (1) only a foo.py, it will be compiled into foo.pyc > (2) only a foo.pyc, it will be used > (3) both a foo.py and a foo.pyc, Python compiles the foo.py if the pyc > is out of date or (so I believe [*]) was created by a different > version of Python. > > Subsequent imports will use the in-memory copy (in sys.modules, IIRC > [*]) ... > > [*] == Please save me the bother of checking this in the manual :-) > > HTH, > John Thank you both for your kind help and patience :) Built-in modules are compiled but even if they are so, when importing them (sys for example), Python will run their code in order to create bindings and objects, right? I'm learning Python and I want to learn it well, so that I'm asking a lot :) From ironfroggy at gmail.com Tue Aug 12 12:40:38 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Tue, 12 Aug 2008 12:40:38 -0400 Subject: Thesaurus / ontology / taxonomy Python library In-Reply-To: References: Message-ID: <76fd5acf0808120940y2bbea628we056ec989af341@mail.gmail.com> Sounds like you might want to read up on RDF On Tue, Aug 12, 2008 at 10:41 AM, Benjamin Michiels wrote: > Hi, > > I am curently looking for a library allowing the creation and management of > a thesaurus. Our requirements are the following: > > - creation of our own thesaurus (that is, terms AND relations between > terms), and indexing (and retrieving) documents with terms defined in our > thesaurus, > - "thesauraus management facilities", such as batch editing of content items > (e.g. for all documents indexed by keyword "A" and "B", replace keywords "A" > and "B" by keyword "C"). > - user-friendly interface. This could a be tree-like structure (with - > ideally - several levels of indexing), such as: > Shape - TS: Square > + TS: Triangle - TS: Scalene triangle > > + TS: Equilateral triangle - [...] > > Ideally, this library would be ready-for-Plone3.x-Zope2.10; but after some - > basic - searches, it appeared that such thesaurus management tools are > rather rare, so I was wondering whether there would even exist such a > library in Python... > > What do you think of it and/or is there already a discussion on this topic? > > Thank you in advance, > > Benjamin Michiels > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy From afriere at yahoo.co.uk Mon Aug 18 22:47:10 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 18 Aug 2008 19:47:10 -0700 (PDT) Subject: Python does not get environment variable when using cron. References: <20080818122747.F1BCE1E4003@bag.python.org> Message-ID: <6601e03d-cb45-49f8-a075-2f3960cad1d5@v16g2000prc.googlegroups.com> On Aug 18, 11:17 pm, "Shawn Milochik" wrote: > > The easiest solution (in my opinion) is to write a bash script to > execute your Python script, and use that bash script to add those > environment variables. Agreed. Wrap it in a shell script, easier to read and grow than a oneliner on the crontab. > The most likely file you'll want to run is > .bashrc in your home directory. If you're on a Mac, it's .bash_login > instead. > > Example: > > #/usr/bin/env bash > > source ~/.bashrc > path/my_script.py > I for one don't have $HOSTNAME defined in my .bashrc file. I doubt this is likely to give him much joy. > Something like that should take care of it. If not, get creative -- > add the "env" command to your bash script and have it send the output > to a file: env > cron_env.txt > Again no. The reason os.environ can't find HOSTNAME is that it is NOT defined in the environment, if env can find it os.environ should be able to as well. From bdesth.quelquechose at free.quelquepart.fr Thu Aug 21 16:54:43 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 21 Aug 2008 22:54:43 +0200 Subject: exception handling in complex Python programs In-Reply-To: <48adaa7e$0$4245$6e1ede2f@read.cnntp.org> References: <48ad8a47$0$30999$426a34cc@news.free.fr> <48adaa7e$0$4245$6e1ede2f@read.cnntp.org> Message-ID: <48add647$0$15607$426a74cc@news.free.fr> magloca a ?crit : > Bruno Desthuilliers @ Thursday 21 August 2008 17:31: > >>>> If you mean "the exceptions *explicitely raised* by your code", then >>>> I agree. But with any generic enough code, documenting any possible >>>> exception that could be raised by lower layers, objects passed in as >>>> arguments etc is just plain impossible. Like, if you have a function >>>> that takes a file-like object as arg, you just cannot know in >>>> advance what exceptions this object might raise. >>>> >>> This is one of the main concerns with which I started this c.l.py >>> thread ! I think it's a pity that we have no way of anticipating and >>> constraining the exceptions thrown by our code, >> Java's "checked exception" system has proven to be a total disaster. > > Could you elaborate on that? I'm not disagreeing with you (or agreeing, > for that matter); I'd just really like to know what you mean by > a "total disaster." One of the most (in)famous Java coding pattern is the empty catchall clause. Read Chris Mellon and Richard Levasseur posts in this thread for more details - they already covered the whole point. From wuwei23 at gmail.com Fri Aug 29 02:25:49 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 28 Aug 2008 23:25:49 -0700 (PDT) Subject: Tough Guy Competition References: Message-ID: On Aug 29, 3:45?pm, "W. eWatson" wrote: > Something to do on your weekends. [non-related link clipped] Another thing to do with your weekends would be to -not spam-. From gagsl-py2 at yahoo.com.ar Tue Aug 19 18:40:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 19 Aug 2008 19:40:31 -0300 Subject: Factory for Struct-like classes References: <62fe8607-af85-45ee-9392-c6f046b5941c@r66g2000hsg.googlegroups.com> Message-ID: En Tue, 19 Aug 2008 12:43:27 -0300, eliben escribi?: > On Aug 18, 11:16?am, Gabriel Genellina wrote: >> On 13 ago, 14:46, eliben wrote: >> >> > On Aug 13, 7:30?pm, Christian Heimes wrote: >> > > Try named tuplehttp://code.activestate.com/recipes/500261/ >> >> > 1) I see this is done with exec anyway, so there's no more pythonic >> > way. >> >> It doesn't *have* to be done with exec - I think there are other >> variants using metaclasses instead. >Can you suggest an alternative, without exec ? See these recipes: http://code.activestate.com/recipes/303439/ and 303770 and 303481; read the comments section too. -- Gabriel Genellina From anishchapagain at gmail.com Sat Aug 16 14:05:52 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Sat, 16 Aug 2008 11:05:52 -0700 (PDT) Subject: How to access an Array and a struct within a struct wrapped by Swig ? References: Message-ID: <6c21cc96-eab4-4823-97c6-c94e1d3da1ec@d1g2000hsg.googlegroups.com> Hi, If you have struct defined in .h file then it's ok or can dea easyily with struct written with .i file, in .h file, struct def { int a; char name[10]; }; can be referenced as >>strvar=new_def() //now strvar is your object for struct def and can access a and name as, get and set for individual member see, >>def_a_set(strvar,10) >>def_a_get(strvar) will return 10. or you can define struct as, typedef struct { int sage; }coll; within .h file and access similarly. regard's Anish Chapagain www.mysticnepal.com On Aug 16, 11:38?am, emmanuel.rivo... at gmail.com wrote: > Hello, > > I spent almost a week to be able to embed Python within my C++ game > engine. > I wrote a mini-tutorial of what I was able to do so far here :http://forums.indiegamer.com/showpost.php?p=169352&postcount=9 > > At the end of my tutorial, I wrote : "You can do the same with C++ > classes, and with structures within structures. Swig can parse & wrap > most C/C++ declarations." > > Gloups, I was so wrong..! :-S > > It seems that I can read a struct within my struct, but I cannot write > values to it. > Also, I cannot access the array from within my struct. > > Any help to achieve this would be very welcome. > > Here the problem in detail : > I'm using Python 2.5.2 & Swig 1.3.36. > > The structures : > struct SIn > { > ? ? ? ? int in1, in2; > > }; > > struct SPythoned > { > ? ? ? ? SIn Inner; > ? ? ? ? float Skill[16]; > > }; > > The python code : > ======================= > def TestObject(o): > ? ? ? ? print(type(o)) > ? ? ? ? print(type(o.Skill)) > ? ? ? ? print(o.Skill) > ? ? ? ? print(type(o.Inner)) > ? ? ? ? print(type(o.Inner.in1)) > ? ? ? ? print(o.Inner.in1) > ? ? ? ? print(o.Inner.in2) > > ? ? ? ? o.Inner.in1 = 12 > ? ? ? ? o.Inner.in2 = 17 > > ? ? ? ? print(o.Inner.in1) > ? ? ? ? print(o.Inner.in2) > ======================= > > It gives me this output : > ======================= > > > _20fd1300_p_float > > > 2 > 22 > 2 > 22 > ======================= > > So althought I can read the value, the "o.Inner.inX = Y" are without > effect..! (and checking the value in the object in the C part confirms > this). > > Moreover, if I add these lines : > ? ? ? ? for i in range(16) : > ? ? ? ? ? ? ? ? print(o.Skill[i]) > > I get this error : > Traceback (most recent call last): > ? File "d:\TE 2008\PyTest.py", line 32, in TestObject > ? ? print(o.Skill[i]) > TypeError: 'PySwigObject' object is unsubscriptable > > Any idea how to make this work ..? --------------- From Edwin.Madari at VerizonWireless.com Tue Aug 19 10:53:49 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Tue, 19 Aug 2008 10:53:49 -0400 Subject: who to call a list of method inside the class itself In-Reply-To: Message-ID: <20080819145403.207A71E4006@bag.python.org> maduma at pt.lu wrote: > Hi, > > Is the following code is ok. who to call all method. > It is working but the call to m() without a reference to self seems > strange > > Thanks for your help > > class CustomMethod: > def method1(self): > .... > def method2(self): > .... > def method3(self): > .... > > def getAllMethod(self): > return [self.method1, self.method2, self.method3] > > def applyAll(self): > for m in self.getAllMethod(): > # how to call all methods ? > # is it correct > m() 1. return string names of required methods in getAllMethod return ['method1', 'method2', 'method3'] 2. use gettattr on self and then exetute methods in applyAll def applyAll(self): for method_name in self.getAllMethod(): method = gettattr(self,method_name) method() #execute method now regards. Edwin The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From ramen at lackingtalent.com Wed Aug 20 22:51:09 2008 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 20 Aug 2008 19:51:09 -0700 Subject: Factory for Struct-like classes In-Reply-To: References: Message-ID: <1N4rk.167$_s1.91@newsfe07.iad> Christian Heimes wrote: > eliben wrote: >> Ruby's 'Scruct' class (http://ruby-doc.org/core/classes/Struct.html) >> does this. I suppose it can be done with 'exec', but is there a more >> Pythonic way ? > > Try named tuple http://code.activestate.com/recipes/500261/ > > A named tuple implementation is part of Python 2.6 and 3.0. For older > versions of Python use the recipe from activestate. Whaaa? Named tuples are being added to Python? Neat! Is there any documentation on this? I can't seem to find anything on the web... Thanks, Dave From kem1723 at yahoo.com Tue Aug 26 17:37:03 2008 From: kem1723 at yahoo.com (Kevin McKinley) Date: Tue, 26 Aug 2008 14:37:03 -0700 (PDT) Subject: Adding Icons to my Programs Message-ID: <801533.35218.qm@web83916.mail.sp1.yahoo.com> I've been turn my script into executible programs with Py2exe. Is there a way to change the icon for the main exe file? Thank you, Kevin McKinley From leon.domingo at gmail.com Mon Aug 11 04:49:43 2008 From: leon.domingo at gmail.com (leon.domingo at gmail.com) Date: Mon, 11 Aug 2008 01:49:43 -0700 (PDT) Subject: Eclipse, Python, wxPython and code completion References: <94acefa8-f3ec-4d5a-a7cb-a3bf769d35e9@79g2000hsk.googlegroups.com> Message-ID: <9d29ac73-dbe0-44fc-b3a9-b9f74a6aa38c@34g2000hsh.googlegroups.com> On 11 ago, 04:34, "SPE - Stani's Python Editor" wrote: > On 10 aug, 20:42, leon.domi... at gmail.com wrote: > > > > > Hello, > > > I've installed Eclipse, Python 2.5 and wxPython on Ubuntu 8.04. The > > problem is that I can't get code completion for wx module. I don't > > know if it occurs the same with other libraries outside the python > > "core". > > > If I compile/run my code containing the wx library, I get an > > application running correctly, so it looks that definition works fine. > > Obviously, the obstacle is that I don't know (I don't want to either) > > the name of every method of every wxPython class so it's difficult to > > develop anything within this environment. > > > Thanks a lot > > > Note: I'm a newbie-coming-from-"Billy's"-WindowsXP > > You can try SPE which is written in wxPython itself and has very good > code completion for wxPython. It also includes some wxPython GUI > builders such as wxGlade and XRCed. I improved it a lot for Hardy, > which I use myself: > sudo apt-get install spe > > Stani Thanks, Stani I will check this out From socyl at 987jk.com.invalid Tue Aug 5 13:38:20 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 5 Aug 2008 17:38:20 +0000 (UTC) Subject: How to troubleshoot hanging script? Message-ID: Hi! I have a Pythonoob question. I have a script that hangs indefinitely at random times; the only thing to do at this point is to kill it. I'm looking for suggestions on how to troubleshoot and debug the problem. I'm not even sure of where exactly the script is hanging, though I suspect it is right around when it tries to read from a pipe (generated by popen). (I arrived at this guess by putting print statements all over the place, but I'm not sure this is a very reliable way to pinpoint the error.) So the first thing I'd like to do is find out exactly where the script is hanging. It would be nice if I could just hit Ctrl-C (which sends SIGINT from the terminal) when the script is hanging, to kill it and get a backtrace, but when this script hangs it becomes unresponsive to Ctrl-C! The only way to kill it is with something like % pkill -KILL my_script.py or even % pkill -TERM my_script.py ...or -ABRT or -QUIT. I tried to exploit this by adding this to the script: import signal def term_handler(signum, frame): raise KeyboardInterrupt signal.signal(signal.SIGTERM, term_handler) ...but this did not help at all; in fact, after this addition, the script no longer responded to pkill -TERM. TIA! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From gh at ghaering.de Tue Aug 26 02:20:53 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 26 Aug 2008 08:20:53 +0200 Subject: Non-evil multithreaded WSGI server? Message-ID: In a recent experiment I've done this: from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from wsgiref.simple_server import make_server, demo_app from SocketServer import ThreadingMixIn # Let's make a WSGI server that can use multiple threads. class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Handle requests in a separate thread.""" # Evil! ;-) from wsgiref.simple_server import WSGIServer as MyWSGIServer MyWSGIServer.__bases__ = (ThreadedHTTPServer,) Now I wonder if there's a less evil way that does not involve copy & paste of the WSGIServer code (only couple of lines, but I hate duplication)?! -- Gerhard From gagsl-py2 at yahoo.com.ar Tue Aug 12 19:50:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Aug 2008 20:50:11 -0300 Subject: Problems returning data from embedded Python References: <2008081116580016807-cromulent@justextrememetalcom> <2008081223485416807-cromulent@justextrememetalcom> Message-ID: En Tue, 12 Aug 2008 19:48:54 -0300, Cromulent escribi?: > On 2008-08-12 05:37:53 +0100, "Gabriel Genellina" > said: > >> En Mon, 11 Aug 2008 12:58:00 -0300, Cromulent >> escribi?: >> >>> >> Uh? You have a complete API for working with list objects, the >> functions named PyList_* >> See http://docs.python.org/api/listObjects.html >> There is also an abstract layer that works both with lists and tuples: >> http://docs.python.org/api/sequence.html >> If that's not what you are after, please provide more details... > > Spoke too soon. > > Right, I've rewritten the Python program and it returns a tuple of lists > and one integer. Basically as you saw before, the python program reads a > file in, splits it into elements that were separated by a comma. > > The new program just puts each element into its own list. Here is a line > from the file I am reading in: > > 15-Jul-08,37.70,37.70,36.43,36.88,102600 > > so basically I have 6 lists and one int (which is the total number of > lines read by the program) I then return that tuple to the C program. You don't need the integer - it's the list length, and you can easily ask that value using PyList_Size. So you are now returning *columns* from the file, ok? > After that I call the following: > > error = PyArg_ParseTuple(value, "isffffi", &totalLines, &finopen, > &finclose, &finhigh, &finlow, &finvolume); > > but that will only give me the first element of the list. What I would > like to do is return the total number of lines read separately, then use > that to allocate a C99 style variable sized array and then loop through > the call to PyArg_ParseTuple to populate the array. The problem with > that is that I don't think PyArg_ParseTuple is designed in that way. It > will put the contents of the list in the variable and not split it up so > that I can populate an array. Yes, forget about PyArg_ParseTuple. It's intended to parse function arguments. Use the appropiate convert function for each object type. For integers, use PyInt_AsLong; for floats, PyFloat_AsDouble, and so on. Something like this (untested): // for a column containing float values: Py_ssize_t nitems = PyList_Size(the_python_list_of_floats) // ...allocate the C array... for (Py_ssize_t i=0; i References: Message-ID: Am 03.08.2008, 12:51 Uhr, schrieb Equand : > how about changing the precious self. to . > imagine > > self.update() > > .update() > > simple right? What about: class x: def x(self,ob): ob.doSomethingWith(self) ? Not so simple anymore, isn't it? If you're not trolling, there's hundreds of reasons why the explicit self is as it is, and it's not going to go away, just as a thread that produced immense amounts of response demonstrated around a week ago. Read that, and rethink. --- Heiko. From pierre.dagenais at ncf.ca Sun Aug 3 18:33:26 2008 From: pierre.dagenais at ncf.ca (Pierre Dagenais) Date: Sun, 03 Aug 2008 18:33:26 -0400 Subject: from Tkinter import *,win = Tk() "from Tkinter import *" Message-ID: from Tkinter import * win = Tk() If I type those two lines at the command prompt (in WindowsXP) I get a new window on my screen. Yet if I copy those lines in a file called test.py and then run "python test.py" at the command prompt I am returned to the command prompt and nothing shows up on the screen. Is this normal behavior or is it a bug? Thanks to all who responded to my previous post, it was quite helpfull. From M8R-n7vorv at mailinator.com Mon Aug 11 06:21:53 2008 From: M8R-n7vorv at mailinator.com (M8R-n7vorv at mailinator.com) Date: Mon, 11 Aug 2008 03:21:53 -0700 (PDT) Subject: benchmark References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> <5dc1189d-79c9-40a7-8024-924ba9a889b4@k13g2000hse.googlegroups.com> Message-ID: <89492d6b-0448-4a51-9a38-f6c4f2ef9422@w24g2000prd.googlegroups.com> On Aug 11, 2:09?pm, cokofree... at gmail.com wrote: > On Aug 11, 10:55 am, M8R-n7v... at mailinator.com wrote: > > > > > On Aug 10, 10:10 pm, Kris Kennaway wrote: > > > > jlist wrote: > > > > I think what makes more sense is to compare the code one most > > > > typically writes. In my case, I always use range() and never use psyco. > > > > But I guess for most of my work with Python performance hasn't been > > > > a issue. I haven't got to write any large systems with Python yet, where > > > > performance starts to matter. > > > > Hopefully when you do you will improve your programming practices to not > > > make poor choices - there are few excuses for not using xrange ;) > > > > Kris > > > And can you shed some light on how that relates with one of the zens > > of python ? > > > There should be one-- and preferably only one --obvious way to do it. > > > Dhananjay > > And that is xrange, but if you need a list range is better :P Interesting to read from PEP-3000 : "Python 2.6 will support forward compatibility in the following two ways: * It will support a "Py3k warnings mode" which will warn dynamically (i.e. at runtime) about features that will stop working in Python 3.0, e.g. assuming that range() returns a list." From adrian_p_smith at yahoo.com Tue Aug 26 01:11:20 2008 From: adrian_p_smith at yahoo.com (Adrian Smith) Date: Mon, 25 Aug 2008 22:11:20 -0700 (PDT) Subject: smart quotes Message-ID: <4188c027-3c64-429b-a1e6-a1f3a79060e8@a3g2000prm.googlegroups.com> Can anyone tell me how to get rid of smart quotes in html using Python? I've tried variations on stuff = string.replace(stuff, "\?", "\""), but to no avail, presumably because they're not standard ASCII. From dudeja.rajat at gmail.com Mon Aug 25 07:57:14 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 25 Aug 2008 12:57:14 +0100 Subject: Tkinter - How to create combo box using Tix with the existing Tkinter widgets/ Message-ID: Hi, I'm using Tkinter module to create a GUI application. I found that the combo box is not present in Tkinter module. It comes with Tix module. Could some one give me an example to create a combo box whilst using Tix and Tkinter? I've been using the following to create my tkinter widgets: myRoot = Tk() and in my Gui code, I've been using self.lbAnalysisLib = Listbox(master, \ yscrollcommand = self.vsbAnalysisLib.set,\ height = 1, width = 30) Please suggest how could I call the Tix's combo box from my existing GUI application that heavily uses the Tkinter widgets? Kindly provide me some code examples. Thanks and regards, Rajat From dullrich at sprynet.com Mon Aug 4 16:28:56 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 04 Aug 2008 15:28:56 -0500 Subject: PIL (etc etc etc) on OS X References: <489379A7.5060009@codebykevin.com> <48948BBA.9050706@codebykevin.com> Message-ID: Just as well that the message sent earlier today seems to have been lost... Ok. Read your instructions on libjpeg. Read some of the install.doc. ./configure, fine. make, fine. "make test", fine. So I said "sudo make install" and this happened: 0-1d-4f-fc-28-d:jpeg-6b dullric$ sudo make install Password: /usr/bin/install -c cjpeg /usr/local/bin/cjpeg /usr/bin/install -c djpeg /usr/local/bin/djpeg /usr/bin/install -c jpegtran /usr/local/bin/jpegtran /usr/bin/install -c rdjpgcom /usr/local/bin/rdjpgcom /usr/bin/install -c wrjpgcom /usr/local/bin/wrjpgcom /usr/bin/install -c -m 644 ./cjpeg.1 /usr/local/man/man1/cjpeg.1 /usr/bin/install -c -m 644 ./djpeg.1 /usr/local/man/man1/djpeg.1 /usr/bin/install -c -m 644 ./jpegtran.1 /usr/local/man/man1/jpegtran.1 /usr/bin/install -c -m 644 ./rdjpgcom.1 /usr/local/man/man1/rdjpgcom.1 /usr/bin/install -c -m 644 ./wrjpgcom.1 /usr/local/man/man1/wrjpgcom.1 Surely that means it was installed in /usr/local/bin, right? So I start over with PIL. It says I should "python setup.py build_ext -i". So I do: 0-1d-4f-fc-28-d:Imaging-1.1.6 dullric$ python setup.py build_ext -i running build_ext --- using frameworks at /System/Library/Frameworks -------------------------------------------------------------------- PIL 1.1.6 BUILD SUMMARY -------------------------------------------------------------------- version 1.1.6 platform darwin 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] -------------------------------------------------------------------- --- TKINTER support ok *** JPEG support not available --- ZLIB (PNG/ZIP) support ok --- FREETYPE2 support ok -------------------------------------------------------------------- To add a missing option, make sure you have the required library, and set the corresponding ROOT variable in the setup.py script. So I look in setup.py and I find this: # Library pointers. # # Use None to look for the libraries in well-known library locations. # Use a string to specify a single directory, for both the library and # the include files. Use a tuple to specify separate directories: # (libpath, includepath). Examples: # # JPEG_ROOT = "/home/libraries/jpeg-6b" # TIFF_ROOT = "/opt/tiff/lib", "/opt/tiff/include" # # If you have "lib" and "include" directories under a common parent, # you can use the "libinclude" helper: # # TIFF_ROOT = libinclude("/opt/tiff") FREETYPE_ROOT = None JPEG_ROOT = None #JPEG_ROOT = "/usr/local/bin" I try it both ways, with JPEG_ROOT=None and JPEG_ROOT = "/usr/local/bin" - same result both times, "JPEG support not available". Any thoughts? Later in setup.py it says if find_library_file(self, "jpeg"): feature.jpeg = "jpeg" elif sys.platform == "win32" and find_library_file(self, "libjpeg"): feature.jpeg = "libjpeg" # alternative name Not knowing exactly what "find_library_file" does I couldn't say, but it almost sounds like it's looking for a file named "jpeg". The summary from the jpeg install looks like it didn't install any such file. Maybe "jpeg" should be the name of one of those files that did get installed? This _is_ fun. Eech. DU. -- David C. Ullrich From davidreynon at gmail.com Thu Aug 14 10:54:30 2008 From: davidreynon at gmail.com (korean_dave) Date: Thu, 14 Aug 2008 07:54:30 -0700 (PDT) Subject: for y in range (0,iNumItems)--> not in order? Message-ID: <8514d915-95bf-4e57-a16a-68866e0ad789@l42g2000hsc.googlegroups.com> for y in range(0,iNumItems): print(str(y)) How do i make the output go IN ORDER 0 1 2 3 4 5 6 etc. instead of 0 1 10 11 12 13 14 2 3 4 5 6 7 8 9 From emmanuel.rivoire at gmail.com Sat Aug 16 07:13:31 2008 From: emmanuel.rivoire at gmail.com (emmanuel.rivoire at gmail.com) Date: Sat, 16 Aug 2008 04:13:31 -0700 (PDT) Subject: How to access an Array and a struct within a struct wrapped by Swig ? References: Message-ID: Ok, Swig needs the structure to be declared like this : typedef struct SIn { int in1, in2; } SIn; Else, it doesn't understand it's a structure... :-S Now, I can write to it. I also found out that Swig didn't allow to write to the array : http://www.swig.org/Doc1.3/SWIG.html#SWIG_nn34 ... :-S So I just have to find out how to read the array, and I'll be all good..! From steve at REMOVE-THIS-cybersource.com.au Mon Aug 18 19:01:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2008 23:01:26 GMT Subject: searching through a string and pulling characters References: Message-ID: <00b9fa2b$0$20315$c3e8da3@news.astraweb.com> On Mon, 18 Aug 2008 13:40:13 -0700, Alexnb wrote: > Lets say I have a text file. The contents look like this, only there is > A LOT of the same thing. > > () A registry mark given by underwriters (as at Lloyd's) to ships in > first-class condition. Inferior grades are indicated by A 2 and A 3. () > The first three letters of the alphabet, used for the whole alphabet. () > In church or chapel style; -- said of compositions sung in the old > church style, without instrumental accompaniment; as, a mass a capella, > i. e., a mass purely vocal. > () Astride; with a part on each side; -- used specif. in designating the > position of an army with the wings separated by some line of > demarcation, as a river or road. > > Now, I am talking 1000's of these. I need to do something like this. I > will have a number, and what I want to do is go through this text file, > just like the example. The trick is this, those "()'s" are what I need > to match, so if the number is 245 I need to find the 245th () and then > get the all the text from after it until the next (). If you have an > idea about the best way to do this I would love your help. If you made > it all the way through thanks! ;) If I take your description of the problem literally, then the solution is: text = "() A registry mark given ..." # lots and lots of text blocks = text.split( "()" ) # use a literal "()" as a delimiter answer = blocks[n] # whichever number you want, starting counting at 0 I suspect that the problem is more complicated than you are saying. I guess that in your actual data, the brackets () probably have something inside them. It looks like you are quoting definitions from a dictionary. Alex, a word of advice for you: we really don't like playing guessing games. If you get a reputation for describing your problem inaccurately, incompletely or cryptically, you will find fewer and fewer people willing to answer your questions. I recommend that you spend a few minutes now reading this page and save yourself a lot of grief later: http://www.catb.org/~esr/faqs/smart-questions.html Now, back to your problem. If my guess is right, and the brackets actually have text inside them, then my simple solution above will not work. You will need a more complicated solution using a regular expression or a parser. That solution will depend on whether or not you can get nested brackets "(ab (123 (fee fi fum) 456) cd ef)" or arbitrary single brackets without the matching pair. Your question also sounds suspiciously like homework. I don't do people's homework, but here's something to get you started. It's not a solution, but it can be used as the first step towards a solution. text = "() A registry mark given ..." # lots and lots of text level = 0 blocks = [] for c in text: # process text one character at a time if c == '(': print "Found an opening bracket" level += 1 # one deeper in brackets elif c == ')': level -= 1 if level < 0: print "Found a close bracket without matching open bracket" else: print "Found a closing bracket" else: # any other character # here's where you do the real work if level == 0: print "Not inside a bracket" blocks.append(c) else: print "Inside a bracket" if level > 0: print "Missing close bracket" text_minus_bracketed_words = ''.join(blocks) -- Steven From mal at egenix.com Thu Aug 7 15:27:01 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 07 Aug 2008 21:27:01 +0200 Subject: Fastest way to store ints and floats on disk In-Reply-To: <489B41CE.8080909@shopzeus.com> References: <489B41CE.8080909@shopzeus.com> Message-ID: <489B4C85.5000308@egenix.com> On 2008-08-07 20:41, Laszlo Nagy wrote: > > Hi, > > I'm working on a pivot table. I would like to write it in Python. I > know, I should be doing that in C, but I would like to create a cross > platform version which can deal with smaller databases (not more than a > million facts). > > The data is first imported from a csv file: the user selects which > columns contain dimension and measure data (and which columns to > ignore). In the next step I would like to build up a database that is > efficient enough to be used for making pivot tables. Here is my idea for > the database: > > Original CSV file with column header and values: > > "Color","Year","Make","Price","VMax" > Yellow,2000,Ferrari,100000,254 > Blue,2003,Volvo,50000,210 > > Using the GUI, it is converted to this: > > dimensions = [ > { 'name':'Color', 'colindex:0, 'values':[ 'Red', 'Blue', 'Green', > 'Yellow' ], }, > { 'name':'Year', colindex:1, 'values':[ > 1995,1999,2000,2001,2002,2003,2007 ], }, > { 'name':'Make', colindex:2, 'value':[ 'Ferrari', 'Volvo', 'Ford', > 'Lamborgini' ], }, > ] > measures = [ > { 'name', 'Price', 'colindex':3 }, > { 'name', 'Vmax', 'colindex':4 }, > ] > facts = [ > ( (3,2,0),(100000.0,254.0) ), # ( dimension_value_indexes, > measure_values ) > ( (1,5,1),(50000.0,210.0) ), > .... # Some million rows or less > ] > > > The core of the idea is that, when using a relatively small number of > possible values for each dimension, the facts table becomes > significantly smaller and easier to process. (Processing the facts would > be: iterate over facts, filter out some of them, create statistical > values of the measures, grouped by dimensions.) > > The facts table cannot be kept in memory because it is too big. I need > to store it on disk, be able to read incrementally, and make statistics. > In most cases, the "statistic" will be simple sum of the measures, and > counting the number of facts affected. To be effective, reading the > facts from disk should not involve complex conversions. For this reason, > storing in CSV or XML or any textual format would be bad. I'm thinking > about a binary format, but how can I interface that with Python? > > I already looked at: > > - xdrlib, which throws me DeprecationWarning when I store some integers > - struct which uses format string for each read operation, I'm concerned > about its speed > > What else can I use? >>> import marshal >>> marshal.dump(1, open('test.db', 'wb')) >>> marshal.load(open('test.db', 'rb')) 1 It also very fast at dumping/loading lists, tuples, dictionaries, floats, etc. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Aug 07 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From kyosohma at gmail.com Fri Aug 29 14:41:45 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 29 Aug 2008 11:41:45 -0700 (PDT) Subject: How to delete a last character from a string References: Message-ID: <8c59017c-7e21-41d6-8f27-58c519b38dec@l64g2000hse.googlegroups.com> On Aug 29, 1:28?pm, dudeja.ra... at gmail.com wrote: > Sorry : Earlier mail had a typo in Subject line which might look > in-appropriate to my friends > > Hi, > > I've a list some of whose elements with character \. > I want to delete this last character from the elements that have this > character set at their end, > > I have written a small program, unfortunately this does not work: > > dirListFinal = [] > for item in dirList: > ? ? ? ? ? ?print item > ? ? ? ? ? ?if item.endswith('\\') == True: > ? ? ? ? ? ? ? ?item = item[0:-1] ? ? ? ? # This one I googled and > found to remove the last character / > ? ? ? ? ? ? ? ?dirListFinal.append(item) > ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ?dirListFinal.append(item) > > item.endswith() does not seem to be working. > > Please help > -- > Regrads, > Rajat Try something like this: >>> x = 'test\\' >>> if x.endswith('\\'): x = x[:-1] This works with Python 2.5.2 on Windows XP. Mike From annumiya at yahoo.com Thu Aug 14 12:11:24 2008 From: annumiya at yahoo.com (annu miya) Date: Thu, 14 Aug 2008 09:11:24 -0700 (PDT) Subject: SOAPpy and ArrayOfString Message-ID: <304340.97330.qm@web53409.mail.re2.yahoo.com> Hi, ? In the article below you mention that you were succesful at doing this through perl. Would it be possible to send me the perl code? ? http://mail.python.org/pipermail/python-list/2007-January/423311.html ? Thank You ? Regards ? Sid -------------- next part -------------- An HTML attachment was scrubbed... URL: From mmanns at gmx.net Fri Aug 1 20:35:01 2008 From: mmanns at gmx.net (mmanns at gmx.net) Date: Sat, 2 Aug 2008 02:35:01 +0200 Subject: ANN: pyspread 0.0.8 Message-ID: pyspread 0.0.8 has been released. About: pyspread is a spreadsheet that accepts a pure python expression in each cell. New features: New macro dialog that allows defining python functions, which can be used in the grid. Bug fixes within the copy paste and print code. Highlights: + Numpy high performance arrays for spreadsheet calculation + Full access to python batteries from each cell + No non-python syntax add-ons + 3D grid + Cell access via slicing of numpy array S + X, Y, and Z yield current cell location for relative reference Requires: Python >=2.4, Numpy 1.0.4, and wxPython 2.8.7.1. License: GPL Project page: http://pyspread.sourceforge.net As always, feedback is appreciated. Please also test with wxPython 2.8.8.0. Enjoy Martin From kyosohma at gmail.com Fri Aug 8 09:15:20 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 8 Aug 2008 06:15:20 -0700 (PDT) Subject: Threading and wx..... References: Message-ID: <8ae10033-50e6-4527-a157-09ae206c8954@e39g2000hsf.googlegroups.com> On Aug 8, 2:19?am, SamG wrote: > On Aug 8, 12:01 pm, SamG wrote: > > > > > Hi, > > > Im trying my hand at threading with wx applications. I have written > > the following code... > > > import wx > > from threading import Thread, Lock > > > class createWindow(Thread): > > ? ? def __init__(self): > > ? ? ? ? Thread.__init__(self) > > ? ? ? ? self.lock = Lock() > > ? ? ? ? self.app=None > > > ? ? def run(self): > > ? ? ? ? #self.lock.acquire() > > ? ? ? ? self.app = wx.PySimpleApp() > > ? ? ? ? frame = wx.Frame(None, title="Hello wx") > > ? ? ? ? frame.Show() > > ? ? ? ? #self.lock.release() > > ? ? ? ? self.app.MainLoop() > > > if __name__=='__main__': > > ? ? c = createWindow() > > ? ? c.start() > > ? ? c.join() > > > Now when i run this program i get a window but the application just > > does not respond. Is there something that im missing here. Pls let me > > know. Thanks in advance. > > Oops! Murphy's law works again! And the above code is working fine. You'll probably also find the following wiki article helpful: http://wiki.wxpython.org/LongRunningTasks And there's at least one demo in the wxPython Demo that's a good example of threading. Mike From pmaupin at gmail.com Sun Aug 24 22:41:50 2008 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 24 Aug 2008 19:41:50 -0700 (PDT) Subject: Python String Immutability Broken! References: Message-ID: On Aug 24, 8:49?pm, "Hendrik van Rooyen" wrote: > (a lot of stuff related to using a string with a C library via ctypes) Very entertaining. But let me get this straight: Are you just complaining that if you pass a string to an arbitrary C function using ctypes, that that arbitrary function can modify the string? Because if you are, then I think you share a great deal of responsibility for the death of that string -- sending the poor thing to its grave through some unknown C function. What would you have ctypes do instead? From geekmoth at gmail.com Sat Aug 9 07:31:38 2008 From: geekmoth at gmail.com (Will Rocisky) Date: Sat, 9 Aug 2008 04:31:38 -0700 (PDT) Subject: How to round a floating point to nearest 10? Message-ID: I want my 76.1 to be rounded to decimal 80 and 74.9 to decimal 70. How can I achieve that? From fred.sells at adventistcare.org Sun Aug 24 23:25:03 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Sun, 24 Aug 2008 23:25:03 -0400 Subject: swig double[], under the gun and need help In-Reply-To: <48a5b125$0$21248$426a34cc@news.free.fr> Message-ID: <0A53725C4A497848A7B3A0874B259831011B0A10@acesxch01.ADVENTISTCORP.NET> I'm using python 2.4 under linux (centos 5.1). I need to pass an array of doubles to a c function but am getting an error, shown near the bottom of this post. ---------------------------------------------------- my swig interface file looks like this * File: rug520.i */ %module rug520 %include "typemaps.i" %include "carrays.i" %array_class(double, doubleArray); %{ #define SWIG_FILE_WITH_INIT #include "rug520.h" extern double[] nCmiArray; %} %apply int *OUTPUT { char *sRugHier, char * sRugMax, int * iRugHier, int * iRugMax, double * nCmiValueHier, double * nCmiValueMax, int * iAdlSum, int * iCpsCode, char * sRugsVersion, char * sDllVersion, int * iError }; int RugCalc( char * sMdsRecord, char * sRehabType, char * sModel, int iQuarterlyFlag, double nCmiArray[], char * sRugHier, char * sRugMax, int * iRugHier, int * iRugMax, double * nCmiValueHier, double * nCmiValueMax, int * iAdlSum, int * iCpsCode, char * sRugsVersion, char * sDllVersion, int * iError ); ------------------------------------------------------------------ my test code looks like this: import sys, os, rug520 cmi=[0.0] *59 def getrug(mds): results = rug520.RugCalc(mds, 'mcare', '34', 0, cmi) print 'results', results datafile = open('mdsdata.txt') for d in datafile: if d[0]=='B': getrug(d) ------------------------------------------------------------------------ I get this error message File "testrug520.py", line 11, in ? getrug(d) File "testrug520.py", line 5, in getrug results = rug520.RugCalc(mds, 'mcare', '34', 0, cmi) TypeError: in method 'RugCalc', argument 5 of type 'double []' -------------------------------------------------------------------------- I'm guessing that I am not passing a double array to the c code. I cannot change the c code due to politics. I could write a c "wrapper" if I had to, but would rather stay within python or the swig interface definitions if possible/practical. I'm not much of a c programmer; mostly java and python with a little c++. I've looked in the swig docs and tried google, but either have not found it or just don't understand what they are telling me here. --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From cito at online.de Sun Aug 17 09:34:29 2008 From: cito at online.de (Christoph Zwerschke) Date: Sun, 17 Aug 2008 15:34:29 +0200 Subject: Missing exceptions in PEP 3107 In-Reply-To: <3fb64d27-b128-43c8-8e8d-71eea257d328@m44g2000hsc.googlegroups.com> References: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> <8800beb6-c07b-44af-b9ac-fcb00f35dc3a@f36g2000hsa.googlegroups.com> <3fb64d27-b128-43c8-8e8d-71eea257d328@m44g2000hsc.googlegroups.com> Message-ID: Carl Banks schrieb: > You are free to use it for other things. For example, the following > usage is obvious and sensible (insofar as listing exceptions is > sensible): > > def f(x : int) -> int, raises(TypeError) > > Think of the return value annotation as more of a function outcome > annotation. That's fine, but then this should be mentioned in the PEP3107. Instead it says explicitly that the "->" syntax is for "the type of a function's return value". If it's intended to be used in a more general way like you suggested, then the wording used in the PEP is misleading. (The wording "*the* type is problematic anyway, since a Python function can return different types in different situations.) It's still unclear for me whether annotations on thrown exceptions are included in PEP3107 (as per your suggestion), or are not covered by PEP3107 at all (as Duncan suggests), or whether this question has just not yet been settled. -- Christoph From fredrik at pythonware.com Wed Aug 13 18:49:08 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 00:49:08 +0200 Subject: Can't use DB name with dashes using pymssql ??? In-Reply-To: References: <65c3648d0808131354x333a7e0cica29217a26f4ce42@mail.gmail.com> <65c3648d0808131530w29728a78ib646dde89481e656@mail.gmail.com> Message-ID: Fredrik Lundh wrote: > reading the documentation might help: > > http://pymssql.sourceforge.net/troubleshooting.html#dbid also see the SQL server reference documentation (the section "Rules for Regular Identifiers" describes the valid syntax): http://msdn.microsoft.com/en-us/library/ms175874.aspx From nobody at yahoo.com Mon Aug 25 21:20:41 2008 From: nobody at yahoo.com (Andrew) Date: Tue, 26 Aug 2008 01:20:41 GMT Subject: Return a string result with out breaking loop In-Reply-To: <116e4423-44c5-4f13-ab2d-d8040b550a8e@2g2000hsn.googlegroups.com> References: <116e4423-44c5-4f13-ab2d-d8040b550a8e@2g2000hsn.googlegroups.com> Message-ID: Yes I found many examples similiar to that but Yield still produces that error Sorry if I sound Novice but I have no formal education in programming so understanding something takes me a bit longer than most of you guys :-D Ive included a bit more of the function How ever unimportant it may be def watchos(self, path_to_watch="C:\\"): FILE_LIST_DIRECTORY = 0x0001 try: path_to_watch or "." except: path_to_watch = "." path_to_watch = os.path.abspath(path_to_watch) out1 = "Watching %s at %s" % (path_to_watch, time.asctime()) + "\n\n" while 1: #INSERT MORE CODE HERE results = change_handle for action, files in results: full_filename = os.path.join(path_to_watch, files) theact = ACTIONS.get(action, "Unknown") yield str(full_filename) + " " + str(theact) But I am having a hard time wrapping my head around yield... perhaps if it produced more than the same error no matter what I did. I could try and get a bit further Anyway once again I appreciate the help cheers :-) From emmanuel.rivoire at gmail.com Sat Aug 16 06:38:26 2008 From: emmanuel.rivoire at gmail.com (emmanuel.rivoire at gmail.com) Date: Sat, 16 Aug 2008 03:38:26 -0700 (PDT) Subject: How to access an Array and a struct within a struct wrapped by Swig ? Message-ID: Hello, I spent almost a week to be able to embed Python within my C++ game engine. I wrote a mini-tutorial of what I was able to do so far here : http://forums.indiegamer.com/showpost.php?p=169352&postcount=9 At the end of my tutorial, I wrote : "You can do the same with C++ classes, and with structures within structures. Swig can parse & wrap most C/C++ declarations." Gloups, I was so wrong..! :-S It seems that I can read a struct within my struct, but I cannot write values to it. Also, I cannot access the array from within my struct. Any help to achieve this would be very welcome. Here the problem in detail : I'm using Python 2.5.2 & Swig 1.3.36. The structures : struct SIn { int in1, in2; }; struct SPythoned { SIn Inner; float Skill[16]; }; The python code : ======================= def TestObject(o): print(type(o)) print(type(o.Skill)) print(o.Skill) print(type(o.Inner)) print(type(o.Inner.in1)) print(o.Inner.in1) print(o.Inner.in2) o.Inner.in1 = 12 o.Inner.in2 = 17 print(o.Inner.in1) print(o.Inner.in2) ======================= It gives me this output : ======================= _20fd1300_p_float 2 22 2 22 ======================= So althought I can read the value, the "o.Inner.inX = Y" are without effect..! (and checking the value in the object in the C part confirms this). Moreover, if I add these lines : for i in range(16) : print(o.Skill[i]) I get this error : Traceback (most recent call last): File "d:\TE 2008\PyTest.py", line 32, in TestObject print(o.Skill[i]) TypeError: 'PySwigObject' object is unsubscriptable Any idea how to make this work ..? From sjmachin at lexicon.net Tue Aug 5 19:30:04 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 5 Aug 2008 16:30:04 -0700 (PDT) Subject: Trying to fix Invalid CSV File References: <0427191c-d493-442d-ba26-94802bc6062b@v13g2000pro.googlegroups.com> <078f7aad-3bba-49b4-8978-18ac5bfaa6f7@r15g2000prd.googlegroups.com> <6bade254-5001-4ae2-a000-003b84437a76@w1g2000prk.googlegroups.com> <42134ad4-ae35-4d25-94fc-2504d29003e6@r15g2000prh.googlegroups.com> Message-ID: On Aug 5, 6:56 am, Larry Bates wrote: > Ryan Rosario wrote: > > On Aug 4, 8:30 am, Emile van Sebille wrote: > >> John Machin wrote: > >>> On Aug 4, 6:15 pm, Ryan Rosario wrote: > >>>> On Aug 4, 1:01 am, John Machin wrote: > >>>>> On Aug 4, 5:49 pm, Ryan Rosario wrote: > >>>>>> Thanks Emile! Works almost perfectly, but is there some way I can > >>>>>> adapt this to quote fields that contain a comma in them? > >> > > >>> Emile's snippet is pushing it through the csv reading process, to > >>> demonstrate that his series of replaces works (on your *sole* example, > >>> at least). > >> Exactly -- just print out the results of the passed argument: > > >> rec.replace(',"',",'''").replace('",',"''',").replace('"','""').replace("'''",'"') > > >> '123,"Here is some, text ""and some quoted text"" where the quotes > >> should have been doubled",321' > > >> Where it won't work is if any of the field embedded quotes are next to > >> commas. > > >> I'd run it against the file. Presumably, you've got a consistent field > >> count expectation per record. Any resulting record not matching is > >> suspect and will identify records this approach won't address. > > >> There's probably better ways, but sometimes it's fun to create > >> executable line noise. :) > > >> Emile > > > Thanks for your responses. I think John may be right that I am reading > > it a second time. I will take a look at the CSV reader documentation > > and see if that helps. Then once I run it I can see if I need to worry > > about the comma-next-to-quote issue. > > This is a perfect demonstration of why tab delimited files are so much better > than comma and quote delimited. No, it's a perfect demonstration of what happens when a protocol is not followed. > Virtually all software can handle table > delimited as well as comma and quote delimited, but you would have none of these > problems if you had used tab delimited. The chances of tabs being embedded in > most data is virtually nil. > There may be no tabs in *your* data. There is no guarantee that there are no tabs in a VARCHAR(n) column in somebody else's database. I've seen all of \x00, \t, \n, \r and \x1a (Ctrl-Z (EOF in CP/M, *DOS and Windows text files)). The possibilities include (1) Don't check (2) check if '\t' in field and raise an exception (3) silently remove tabs; what do you recommend? From frank at chagford.com Wed Aug 6 01:16:07 2008 From: frank at chagford.com (Frank Millman) Date: Tue, 5 Aug 2008 22:16:07 -0700 (PDT) Subject: Questions about asyncore References: <5d30aad5-cad7-4e47-aa83-277202c70ae2@z72g2000hsb.googlegroups.com> <85afa6f5-431b-42ee-bd31-de5321b0b0f9@l33g2000pri.googlegroups.com> Message-ID: <38da12d9-ccc8-46d4-9026-43bbaf0fd943@m36g2000hse.googlegroups.com> On Aug 5, 6:18 pm, Josiah Carlson wrote: > > Giampaolo already offered up some information, but I will offer these > two little tidbits: > In your first client, your handle_read doesn't handle the case where > you have received multiple packets at one time. That is, imagine that > in your one .read(8192), you received exactly two messages (the prefix > length and the pickle itself times two). The first pass will pick up > the message and handle the data. But unless the socket becomes > readable again, the second message will never be processed. And even > if the socket becomes readable immediately in the next select() call, > the message will be delayed depending on what other sockets are up > to. The asynchat module handles that case just fine. > > As for push() vs. send(); send() returns the number of bytes sent. If > it sends less than the total block of data (which can be the case with > large blocks of data, small TCP/IP windows over a slow connection, or > small TCP/IP buffers), you need to be aware of it and attempt to > resend the remaining. Again, the asynchat module handles that case > just fine with it's .push() method; when it returns, you know that the > data to be transferred will be transferred as long as the connection > stays alive. Without .push(), you need to implement that behavior > yourself (less boilerplate for every subclass = easier maintenance). > > (I normally don't hop on this list to comment, so please cc me on any > replies) > - Josiah > Valuable insights. Much appreciated. Frank From brenNOSPAMbarn at NObrenSPAMbarn.net Sun Aug 31 02:40:35 2008 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Sun, 31 Aug 2008 06:40:35 GMT Subject: Relative imports and "import X as Y" References: Message-ID: Terry Reedy wrote: > >> So, will relative imports in Python 3.0 allow things like >> "import >> ..relative.importing.path as prettyname"? If not, why not? > > Download the latest beta for your system and give it a try. Thanks for the advice, but I'd really rather not deal with installing the entire thing alongside my existing version, possibly causing conflicts in who knows what ways. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From python.leojay at gmail.com Tue Aug 19 08:08:02 2008 From: python.leojay at gmail.com (Leo Jay) Date: Tue, 19 Aug 2008 20:08:02 +0800 Subject: How to stop iteration with __iter__() ? In-Reply-To: <836a8d0a-ce00-40da-bc7c-f390ead0acfe@w7g2000hsa.googlegroups.com> References: <836a8d0a-ce00-40da-bc7c-f390ead0acfe@w7g2000hsa.googlegroups.com> Message-ID: <4e307e0f0808190508r419b7178j9c120eb196467069@mail.gmail.com> On Tue, Aug 19, 2008 at 7:39 PM, ssecorp wrote: > I want a parse a file of the format: > movieId > customerid, grade, date > customerid, grade, date > customerid, grade, date > etc. > > so I could do with open file as reviews and then for line in reviews. > > but first I want to take out the movie id so I use an iterator. > > then i want to iterate through all the rows, but how can I do: > while movie_iter != None: > > because that doesn't work, itraises an exception, StopItreation, which > according to the documentation it should. But catching an exception > can't be the standard way to stop iterating right? > you can use for loop: for line in movie_iter: ... -- Best Regards, Leo Jay From Edwin.Madari at VerizonWireless.com Thu Aug 14 14:55:01 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Thu, 14 Aug 2008 14:55:01 -0400 Subject: Fixed-length text file to database script In-Reply-To: Message-ID: <20080814185513.22BE91E4015@bag.python.org> #your thought is right. ======================================================= def sizes2fields(sizes): d = [] begin = 0 for i in sizes: if begin: end = begin + i else: end = i d.append((begin, end)) begin += i return tuple(d) def slicestring(s, fields): d = [] for i in fields: d.append(s[i[0]:i[1]]) return tuple(d) sizes = [16,4,8,8,8] s = '123456789012345678901234567890123456789012345678901234567890' print slicestring(s, sizes2fields(sizes)) ========================================================== prints out: ('1234567890123456', '7890', '12345678', '90123456', '78901234') hope it helps. thanks Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of Eric Wertman Sent: Thursday, August 14, 2008 1:59 PM To: python-list at python.org Subject: Re: Fixed-length text file to database script I have a machine (PLC) that is dumping its test results into a fixed- length text file. While it has nothing to do with python, I found that creating a MySQL table with the proper fixed length char() fields and using 'load data infile' was the easiest way to deal with that sort of scenario. The python script is the secondary part, that handles the normalization and proper typing of the first table to the second, permanent storage area. But in this case, the more advanced bits are the database and SQL details, and python is just a very convenient way to build the SQL statements and execute them. I'm really not sure what the best way to deal with fixed length data is in python. I might define a list with the field lengths and use a string slicing to get the items.. as a first thought: myfile = '/somewhere/somefile.txt' sizes = [16,4,8,8,8] fd = open(myfile,r) for line in fd.readlines() : idx1 = 0 for l in sizes : -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From gminick at bzt.bzt Mon Aug 18 05:12:16 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Mon, 18 Aug 2008 09:12:16 +0000 (UTC) Subject: online tutorials? References: <6013d717-7c4b-4f34-8f58-d9a1e7387f5c@k37g2000hsf.googlegroups.com> Message-ID: On Sun, 17 Aug 2008 15:53:38 -0700 (PDT), Gits wrote: > I want to learn how to program in python and would like to know if you > guys know of any free online tutorials. Or is it too complicated to > learn from a site or books? Try this: http://linkmingle.com/list/List-of-Free-Online-Python-Books-freebooksandarticles -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From vedrandekovic at yahoo.com Sat Aug 9 07:34:00 2008 From: vedrandekovic at yahoo.com (vedrandekovic at yahoo.com) Date: Sat, 9 Aug 2008 04:34:00 -0700 (PDT) Subject: .cpp to .pyd References: <8a2eea23-1d72-4653-8a8f-c2bb56bc47f6@l64g2000hse.googlegroups.com> <90512f4b-e000-4343-8d5d-4ab92974607b@d77g2000hsb.googlegroups.com> Message-ID: <9a423122-b979-4674-99cc-73623d7d07cd@m44g2000hsc.googlegroups.com> On 9 kol, 01:27, Carl Banks wrote: > On Aug 8, 1:11?pm, vedrandeko... at yahoo.com wrote: > > > Thanks for quick reply.Maybe I'm crazy but I did what you said and I > > stll get the same error :( ?:( ?:( :(.I have boost version 1.34.1 and > > I'm > > running it on Windows XP SP2. > > While you're at it, please post your setup.py > > Carl Banks Hi, Here is my setup.py script: setup(name="MyApp", ext_modules=[ Extension("hello", ["hellomodule.cpp"], libraries = ["boost_python"], include_dirs = ['D:\\Program Files\\boost\\boost_1_34_1\ \boost'], ) ]) Regards, Veki From gagsl-py2 at yahoo.com.ar Wed Aug 27 00:49:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 27 Aug 2008 01:49:11 -0300 Subject: floating point arithmetic References: <6k_sk.92243$6s4.59352@newsfe14.ams2> Message-ID: En Tue, 26 Aug 2008 18:11:30 -0300, fred8865 escribi?: > I understand that due to different arithmetic used in floating points > they are just approximations. Hence, 180/100=1 in my python interpreter. > How can I tackle this problem of inaccurate floating point numbers? > thank you In the current Python versions (2.2 and up), 180/100 means integer division (because both operands are integer). If you want a floating point result, use 180.0/100 or float(some_variable)/100 Starting with Python 3.0, the / operator will return a floating point result ("true division"). So in that Python version, 180/100 gives 1.8 To enable that behavior on Python 2.x, execute "from __future__ import division": >>> 180/100 1 >>> from __future__ import division >>> 180/100 1.8 In any Python version, 180//100 always means integer division: >>> 180//100 1 -- Gabriel Genellina From fauvoritename333 at gmail.com Fri Aug 15 03:54:22 2008 From: fauvoritename333 at gmail.com (fauvoritename333 at gmail.com) Date: Fri, 15 Aug 2008 00:54:22 -0700 (PDT) Subject: EARN MONEY $1500-$5000 PER MONTH Message-ID: EARN MONEY $1500-$5000 PER MONTH SIMPLE ONLINE SURVEY CREATE UR ACCOUNT AND EARN IMMEDIATLY ********************************************************************* http://www.AWSurveys.com/HomeMain.cfm?RefID=sangeetha777 ********************************************************************* From Edwin.Madari at VerizonWireless.com Mon Aug 18 08:50:30 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Mon, 18 Aug 2008 08:50:30 -0400 Subject: Vmware api In-Reply-To: Message-ID: <20080818125043.077F61E4018@bag.python.org> do the ESX server provide any api's or an interactive session may ? thx. Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of Eric Wertman Sent: Sunday, August 17, 2008 2:43 PM To: python-list at python.org Subject: Re: Vmware api I would also be interested in anything anyone can offer. I spend some time looking around, and took a fair stab at using the wsdl2py that comes with The ZSI package. Ultimately I couldn't get anything to work, and reverted to using perl (yuk). I'm interested mostly in interrogating the ESX servers to get configuration and performance data, from external hosts. Thanks! Eric -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From wuwei23 at gmail.com Thu Aug 7 09:12:04 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 7 Aug 2008 06:12:04 -0700 (PDT) Subject: benchmark References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> <489a8cf8$0$11738$9b4e6d93@newsspool1.arcor-online.net> <00aa8eeb$0$20317$c3e8da3@news.astraweb.com> <7d6b3d0d-deb7-4f4b-99a8-1a5b52c1cf1f@h17g2000prg.googlegroups.com> <66bb77c9-a14b-4722-8302-cfa8700656ba@i20g2000prf.googlegroups.com> Message-ID: <21c0d6dc-49a0-4917-b6ce-4773d41ae24f@n33g2000pri.googlegroups.com> On Aug 7, 8:08 pm, M8R-n7v... at mailinator.com wrote: > Really how silly can it be when you suggest someone is taking a > position and tweaking the benchmarks to prove a point [...] I certainly didn't intend to suggest that you had tweaked -anything- to prove your point. I do, however, think there is little value in slavishly implementing the same algorithm in different languages. To constrain a dynamic language by what can be achieved in a static language seemed like such an -amazingly- artificial constraint to me. That you're a fan of Python makes such a decision even more confusing. It's great that you saw value in Python enough to choose it for actual project work. It's a shame you didn't endeavour to understand it well enough before including it in your benchmark. As for it being "disappointing", the real question is: has it been disappointing for you in actual real-world code? Honestly, performance benchmarks seem to be the dick size comparison of programming languages. From fredrik at pythonware.com Thu Aug 14 02:29:26 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 08:29:26 +0200 Subject: Replace Several Items In-Reply-To: References: <513926b0-64fe-4fdc-bb33-bc4b8ad3ab10@a70g2000hsh.googlegroups.com> Message-ID: John Machin wrote: > Clue: The effbot was the original author of the modern (Python 1.6?) > version of the re module. And the author of the "in" and "replace" implementations in Python 2.5. From bearophileHUGS at lycos.com Fri Aug 1 06:25:00 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 1 Aug 2008 03:25:00 -0700 (PDT) Subject: very large dictionary References: <5c5e6d6e-04ef-4340-963f-d3825875b32c@e39g2000hsf.googlegroups.com> <6fftjvFb7ktoU2@mid.uni-berlin.de> Message-ID: Simon Strobl: > I had a file bigrams.py with a content like below: > bigrams = { > ", djy" : 75 , > ", djz" : 57 , > ", djzoom" : 165 , > ", dk" : 28893 , > ", dk.au" : 854 , > ", dk.b." : 3668 , > ... > } > In another file I said: > from bigrams import bigrams Probably there's a limit in the module size here. You can try to change your data format on disk, creating a text file like this: ", djy" 75 ", djz" 57 ", djzoom" 165 ... Then in a module you can create an empty dict, read the lines of the data with: for line in somefile: part, n = .rsplit(" ", 1) somedict[part.strip('"')] = int(n) Otherwise you may have to use a BigTable, a DB, etc. > If there is no other way to do it, I will have to learn how to use > databases in Python. I would prefer to be able to use the same type of > scripts with data of all sizes, though. I understand, I don't know if there are documented limits for the dicts of the 64-bit Python. Bye, bearophile From fredrik at pythonware.com Thu Aug 14 09:28:27 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 15:28:27 +0200 Subject: From Ruby to Python? In-Reply-To: <170543c70808140557h53711636q94c4e11e20367ace@mail.gmail.com> References: <23d7e1bb0808130545w28fb4c04s205c1de2a39dcb36@mail.gmail.com> <23d7e1bb0808140226r63fed22ev2ad83718b591f398@mail.gmail.com> <170543c70808140557h53711636q94c4e11e20367ace@mail.gmail.com> Message-ID: Michael Mabin wrote: > Ruby does have a little of the Perl spirit of 'There's More Than One Way > to Do It'. And you do need shift to Python's 'There's Only One Way To Do > It'. Careful. "import this" says: "There should be one-- and preferably only one --obvious way to do it." Note the use of "obvious". It's about the language getting out of the way so you can focus on your real problem, not restricting what you can do with it. (I mean, seriously, if you find your job so mind-numbingly boring that you need many ways to code trivial problems just to get some variation, maybe it's time to look for a better position?) From joncle at googlemail.com Wed Aug 27 07:56:22 2008 From: joncle at googlemail.com (Jon Clements) Date: Wed, 27 Aug 2008 04:56:22 -0700 (PDT) Subject: finding out the number of rows in a CSV file References: <3aaa109e-9a7e-4d02-8af5-0161251d7678@t54g2000hsg.googlegroups.com> Message-ID: <2a1792cd-64ae-4c41-8c3e-945ab39ffdb1@i76g2000hsf.googlegroups.com> On Aug 27, 12:48 pm, "Simon Brunning" wrote: > 2008/8/27 Jon Clements : > > >> len(list(csv.reader(open('my.csv')))) > > Not the best of ideas if the row size or number of rows is large! > > Manufacture a list, then discard to get its length -- ouch! > > I do try to avoid premature optimization. ;-) > > -- > Cheers, > Simon B. :) From gagsl-py2 at yahoo.com.ar Tue Aug 12 03:05:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Aug 2008 04:05:10 -0300 Subject: How to iterate a sequence, with skipping the first item? References: Message-ID: En Tue, 12 Aug 2008 03:51:17 -0300, ray escribi?: > A container object provides a method that returns an iterator object. > I need to iterate the sequence with that iterator, but need to skip > the first item. I can only iterate the whole sequence with: > for x in container.iterChildren(): > How to skip the first item? It seems that it's a simple question. > Could somebody help me? Thanks. it = container.iterChildren() it.next() # consume first item for x in it: # process remaining items -- Gabriel Genellina From waldemar.osuch at gmail.com Tue Aug 5 14:15:27 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Tue, 5 Aug 2008 11:15:27 -0700 (PDT) Subject: regex search loops instead of findall References: Message-ID: <78a5c121-9d8e-4f37-935c-4047aefc301d@q5g2000prf.googlegroups.com> On Aug 5, 12:06?pm, brad wrote: > Hi guys... I'm trying to make my Python regex code behave like my C++ > regex code. In order to search large strings for *all* occurrences of > the thing I'm searching for, I loop like this in C++: > > void number_search(const std::string& portion, const boost::regex& Numbers) > ? ?{ > > ? ? ?boost::smatch matches; > ? ? ?std::string::const_iterator Start = portion.begin(); > ? ? ?std::string::const_iterator End = portion.end(); > > ? ? ?while (boost::regex_search(Start, End, matches, Numbers)) > ? ? ? ?{ > ? ? ? ?std::cout << matches.str() << std::endl; > ? ? ? ?Start = matches[0].second; > ? ? ? ?} > ? ?} > > I cannot figure out how to do the same in Python. I've read several Py > regex docs, but none of them go into examples of this, although search > seems that it should be able to loop on position according to the docs. > I've resorted to using find_all in python, but that has limitations > (especially when searching for groups) and seems to be a lot less > efficient than search. Any suggestions or example code I can look at? > > I've read these:http://www.amk.ca/python/howto/regexhttp://docs.python.org/lib/module-re.html > > Thanks. re.finditer may help. http://docs.python.org/lib/node46.html From frankrentef at yahoo.com Tue Aug 26 14:33:17 2008 From: frankrentef at yahoo.com (frankrentef) Date: Tue, 26 Aug 2008 11:33:17 -0700 (PDT) Subject: Newbie needs help References: <077ddd87-e944-44e0-935f-2d5cf1368e14@w39g2000prb.googlegroups.com> Message-ID: <253bdfcd-7c15-4013-a6f5-6c886810fee7@q5g2000prf.googlegroups.com> On Aug 26, 11:46?am, frankrentef wrote: > Greetings all, > > I'm wanting to maintain what values in one file and call them in > another. ?The purpose being to keep a single location where url's, > login's and passwords can be maintained, then called as needed from > another file. > > In file #1 I have... > > import time > import os > import sys > > url = 'http://zoo/' > > adminlogin = 'Zebra' > adminpassword = 'Zebra12$' > > --------------------------------------------- > > In file #2 I have the following... > > from cPAMIE import PAMIE > > #Imports - used to setup / control finding files > import time > import os > import sys > import loginout ? ?#name of the file retaining all url/login info > from log import log > > #Create New Pamie Object > ie=PAMIE() > ie=Visible =1 > t=time > > adminlogin (ie,url) > if ie.findText ('Site Status: Active'): > ? ? log ('PASSED -- ADMIN Module - ADMIN Login & Admin Tab Navigation > Successful') > else: > ? ? log ('WARNING -- ADMIN Module Login & Admin Tab Navigation > FAILED') > time.sleep(2) > > What am I doing incorrectly to not have file two log in when > executed. ?All files are in the same directory. ? Keep it simple... > I'm new at this. > > THNX Yes, the first file is named loginout.py Would the second file need something akin to... loginout.admin (ie,url,adminlogin) From cvrebert at gmail.com Thu Aug 28 00:54:23 2008 From: cvrebert at gmail.com (Chris Rebert) Date: Wed, 27 Aug 2008 21:54:23 -0700 Subject: List of modules available for import inside Python? In-Reply-To: References: Message-ID: <47c890dc0808272154y3ac94bayc4652555ee8d8c61@mail.gmail.com> On Wed, Aug 27, 2008 at 9:21 PM, ssecorp wrote: > Is there a way to view all the modules I have available for import > from within Python? > Like writing in the interpreter: > import.modules > > > Also, is there anything like Cpan for Python? The closest thing would be PyPI (the Python Package Index) [http://pypi.python.org/pypi], and easy_install (a package manager for Python) [http://peak.telecommunity.com/DevCenter/EasyInstall]. - Chris ======== Follow the path of the Iguana... Rebertia: http://rebertia.com Blog: http://blog.rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > From rajanikanth at gmail.com Wed Aug 20 17:21:59 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Wed, 20 Aug 2008 14:21:59 -0700 Subject: Detect a sequence of keystrokes in an os independent way Message-ID: <84bdef3c0808201421tf88ef1dg5e828c00091c4ade@mail.gmail.com> Hi! Can somebody tell me if there is an os independent way to detect a sequence of key strokes. For example, I want to start some other program once the user presses a couple of keys: ex: key a and then key b Thanks, Raj -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From nagle at animats.com Mon Aug 18 00:25:11 2008 From: nagle at animats.com (John Nagle) Date: Sun, 17 Aug 2008 21:25:11 -0700 Subject: Python does not get environment variable when using cron. In-Reply-To: References: Message-ID: <48a8f4fe$0$17182$742ec2ed@news.sonic.net> Stephen Cattaneo wrote: > Hello all, > > I am attempting to execute an automated test (written in Python) via > cron. I have to check the HOSTNAME variable as part of the test, oddly > under cron the HOSTNAME environment variable is not in the os.environ > dictionary. I know that cron runs in a subshell that does not have all > of the normally set environment variables. HOSTNAME is not one of those > variables, it is set even in cron's subshell. Why doesn't python get > this variable? Is this a bug in python2.4? Cron doesn't normally use a shell at all. It just runs the requested program in a subprocess. So there's no shell involved, and you don't get a shell-type user environment. If you have a crontab line like 10 3 * * * /usr/bin/python someprogram.py there's no shell. You can try 10 3 * * * /bin/sh /usr/bin/python someprogram.py which will load a shell, which in turn will load Python. Or, in Python, you can use "socket.gethostname()", which will get you the host name used for networking purposes. John Nagle From cfarrell1980 at googlemail.com Tue Aug 26 04:08:31 2008 From: cfarrell1980 at googlemail.com (frankentux) Date: Tue, 26 Aug 2008 01:08:31 -0700 (PDT) Subject: extract text from ods TableCell using odfpy References: Message-ID: <9aa6930f-c680-41bc-8d6e-99ddd36c35a9@l64g2000hse.googlegroups.com> Ok. Sorted it out, but only after taking a round trip over xml.minidom. Here's the working code: #!/usr/bin/python from odf.opendocument import Spreadsheet from odf.opendocument import load from odf.table import TableRow,TableCell from odf.text import P doc = load("/tmp/match_data.ods") d = doc.spreadsheet rows = d.getElementsByType(TableRow) for row in rows[:2]: cells = row.getElementsByType(TableCell) for cell in cells: tps = cell.getElementsByType(P) if len(tps) > 0: for x in tps: print x.firstChild From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 26 06:33:19 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 26 Aug 2008 12:33:19 +0200 Subject: Overwriting property-> can't set attribute In-Reply-To: References: Message-ID: <48b3dbbe$0$17486$426a74cc@news.free.fr> norseman a ?crit : > Gregor Horvath wrote: >> Hi, >> >> why is this code failing? >> >> class B(object): >> pass >> >> B.testattr = property(lambda s:"hallo") >> b = B() >> b.testattr = "test" >> >> >> Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) >> >> /tmp/python-14202ViU.py in () >> 14 B.testattr = property(lambda s:"hallo") >> 15 b = B() >> ---> 16 b.testattr = "test" >> 17 >> 18 >> >> : can't set attribute >> >> -- >> Greg >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > ==================================== > > b = B() # synonyms Not exactly, no. You probably missed the call operator applied to B. (snip erroneous explanation). From half.italian at gmail.com Fri Aug 22 16:51:52 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Fri, 22 Aug 2008 13:51:52 -0700 (PDT) Subject: Seeking ideas for a cron implementation References: Message-ID: <8f607078-e8da-4438-8769-96d011f1544f@j1g2000prb.googlegroups.com> On Aug 22, 1:30?pm, Karthik Gurusamy wrote: > Hi, > > I'm working on a cron like functionality for my application. > The outer loops runs continuously waking every x seconds (say x=180, > 300, ..). > It needs to know what events in cron has expired and for each event do > the work needed. > > It's basically like unix cron or like a calendar application with some > restrictions. The outer loop may come back a lot later and many events > might have missed their schedule -- but this is okay.. We don't have > to worry about missed events (if there were n misses, we just need to > execute call back once). > > Let's take some examples [Let e denotes an event] > e1: hour=1 ?min=30 ? ? ? ? ? ? ? ? ? ? ? ? ? ? # Run every day once at > 1:30 AM > e2: wday=0, hour=1 ?min=0 ? ? ? ? ? ? ? ? ? # run every Monday at 1 AM > e3: month=10, day=10, hour=10 min=0 ?# run on October 10th, 10 AM > every year > > class Cron_Event (object): > ? ? def __init__ (year=None, month=None, day=None, hour=None ..etc) > ? ? ? # ?do init > > class Cron (object): > ? ? def __init__ (): > ? ? ? ? # do init > ? ? def event_add (e): > ? ? ? ? # add an event > ? ? def execute() > ? ? ? ? # see if any events has "expired" .. call it's callback > ? ? ? ? # I'm looking for ideas on how to manage the events here > > From outer loop > cron = Cron() > # create various events like > e1 = Cron_Event(hour=1) > cron.event_add(e1) > e2 = Cron_Event(wday=0, hour=1) > cron.event_add(e2) > > while True: > ? ? sleep x seconds (or wait until woken up) > ? ? cron.execute() > ? ? # do other work.. x may change here > > If I can restrict to hour and minute, it seems manageable as the > interval between two occurrences is a constant. But allowing days like > every Monday or 1st of every month makes things complicated. Moreover > I would like each constraint in e to take on multiple possibilities > (like every day at 1AM, ?2 AM and 4 AM do this). > > I'm looking for solutions that can leverage datetime.datetime > routines. > My current ideas include for each e, track the next time it will fire > (in seconds since epoch as given by time.time()). Once current time > has passed that time, we execute the event. e.g.>>> datetime.datetime.now() > > datetime.datetime(2008, 8, 22, 13, 19, 54, 5567)>>> time.time() > > 1219436401.741966 ? ?<--- compute event's next firing in a format like > this > > > > The problem seems to be how to compute that future point in time (in > seconds since epoch) ?for a generic Cron_Event. > > Say how do I know the exact time in future ?that will satisfy a > constraint like: > ?month=11, wday=1, hour=3, min=30 ? ?# At 3:30 AM on a Tuesday in > November > > Thanks for your thoughts. > > Karthik I only scanned your message, but maybe datetime.timedelta() will help.. >>> import datetime >>> now = datetime.datetime.now() >>> print now 2008-08-22 13:48:49.335225 >>> day = datetime.timedelta(1) >>> print day 1 day, 0:00:00 >>> print now + day 2008-08-23 13:48:49.335225 ~Sean From darcy at druid.net Wed Aug 13 11:04:44 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 13 Aug 2008 11:04:44 -0400 Subject: You advice please In-Reply-To: References: Message-ID: <20080813110444.7b48ddbc.darcy@druid.net> On Wed, 13 Aug 2008 13:47:58 +0200 "?lvaro G. Vicario" wrote: > But I've never came across a Ruby app. Sure, I know Ruby exists and > people are very enthusiastic about it (though they often mistake it with > Ruby on Rails), but that's all. > > Ruby is popular among bloggers but I'm not sure whether it's popular > among developers. Well, I just attended the Agile 2008 conference and sadly Ruby seemed to be much more popular than Python. I found people who had heard of Python and were thinking of trying it but developers were working in Java, C++ and Ruby. Of course, I didn't talk to every one of the 1500 delegates. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From castironpi at gmail.com Mon Aug 4 13:49:45 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 4 Aug 2008 10:49:45 -0700 (PDT) Subject: Limits of Metaprogramming References: <0c56829a-7ad2-4ff2-b225-7981538e7c7a@j22g2000hsf.googlegroups.com> Message-ID: <07c3d5f8-563c-43bc-8772-5eb60de52c82@8g2000hse.googlegroups.com> On Aug 4, 4:48?am, Wilson wrote: > Hi all, > > My problem is that I don't know if it's possible to edit these states > and then write them back to .py. Firstly, if my editing tool was to > create a new state, I would want to create the class (using type) and > attach it to the imported state module somehow. I can't find > > Thanks, > Paul Yes it's possible, using type, but you can't attach it to the module in any persistent way. The next time you load the module, it's back to the way it was. I think this may be the hang-up in your design: if you think about generating lines of code directly from the user's actions, you might stay on the right track. At that point, you can place them in the .py file. Then you can reimport it, or just execute the new lines directly. If this is your class, class Auto54701: def next( self, input ): if( something ): return value1 return value2 Here's how to work with it at the interactive prompt: >>> s= """class Auto54701: ... def next( self, input ): ... if( something ): ... return value1 ... return value2 ... """ >>> s 'class Auto54701:\n def next( self, input ):\n if( something ): \n ret urn value1\n return value2\n' >>> exec( s ) >>> Auto54701 >>> And by the way, you can't use pickle to store types. There needs to be some fleshed-out code to back them up. Two more alternatives, which I can discuss more later, one where you implement code as data, but it ends up being a lot like Python anyway. It only works if your classes' methods are going to be simple, probably sequential if-s and assignments at most. class Auto54701: def next( self, input ): if( something1 ): return value1 elif( something2 ): return value2 elif( something3 ): return value3 elif( something4 ): return value4 return value5 can be stored in data as [ ( something1, value1 ), ( something2, value2 ), ... ] , and just checked in a loop, that you only have in code once, rather than many times. class GenericAuto: def next( self, input ): for something, value in conditionpairs: if( something ): return value return valuen Two, if all your methods will have uniform signatures and closures, you can store class methods as only their co_code objects: >>> C.g.im_func.func_code.co_code 'd\x00\x00S' And fabricate them dynamically into full live types as needed. From martin at see.sig.for.address.invalid Fri Aug 22 19:23:57 2008 From: martin at see.sig.for.address.invalid (Martin Gregorie) Date: Fri, 22 Aug 2008 23:23:57 +0000 (UTC) Subject: The Importance of Terminology's Quality References: <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: On Fri, 22 Aug 2008 22:56:09 +0000, sln wrote: > On Thu, 21 Aug 2008 09:11:48 -0500, rpw3 at rpw3.org (Rob Warnock) wrote: > >>sln at netherlands.com> wrote: >>*IS* raw machine code, *NOT* assembler!! > [snip] > > I don't see the distinction. > Just dissasemble it and find out. > There's a 1:1 relationship between machine code and assembler. Unless its a macro-assembler, of course! > > Each op is a routine in microcode. > That is machine code. Those op routines use machine cycles. > Not necessarily. An awful lot of CPU cycles were used before microcode was introduced. Mainframes and minis designed before about 1970 didn't use or need it and I'm pretty sure that there was no microcode in the original 8/16 bit microprocessors either (6800, 6809, 6502, 8080, 8086, Z80 and friends). The number of clock cycles per instruction isn't a guide either. The only processors I know that got close to 1 cycle/instruction were all RISC, all used large lumps of microcode and were heavily pipelined. By contrast the ICL 1900 series (3rd generation mainframe, no microcode, no pipeline, 24 bit word) averaged 3 clock cycles per instruction. Motorola 6800 and 6809 (no microcode or pipelines either, 1 byte fetch) average 4 - 5 cycles/instruction. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From tjreedy at udel.edu Fri Aug 22 16:17:16 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 22 Aug 2008 16:17:16 -0400 Subject: How to search the Python manuals Message-ID: A number of questions asked here could easily be answered by a quick search of the Python Manuals. A prime example is about the behavior of default parameter values. A recent questioner ended the thread with "The problem with this particular question is that I found it hard to find a query that would give meaningful answers." The following is intended to show how he might have found an answer to this question and, by extension, how others might answer other questions using the 2.4 to 3.0 manuals. (I do not have 2.6 but presume its manual set works the same as the 3.0 set.) -------------------------------------- For WinXP (I have no idea of how the manuals works elsewhere): Open the Python Manuals shortcut. On the left, click [+] for Language Reference (3.0: The Python language reference). Scan the chapter list to find [+] Compound Statements [statements with a header line and indented suite]. Click [+], find Function definitions and click on that. (In 3.0, one can instead directly click Compound Statements since entire chapters rather than just sections are loaded into the right pane.) Click on the right frame/pane to shift 'focus'. Enter control-F and wait (at least a second, be patient) to open a Find box. Enter 'default' (but not too much, such as 'default argument') and click Next. This brings you to the discussion of default parameter values. Either read or continue clicking Next until you come to the boldfaced line that begins the next paragraph: "Default parameter values are evaluated when the function definition is executed." This is followed by an explanation of why one would usually want 'param = None' + body code rather than 'param = []'. ----------------------------------------- It helps if one reads all of the language reference and the first chapters of the library reference on built-ins at least once. They are constantly being improved as mistakes and ambiguities are found and reported. The global module index (top of the left pane) is useful when you know (or maybe just suspect) the name of a module. Terry Jan Reedy From PaulAlexWilson at gmail.com Mon Aug 4 14:57:04 2008 From: PaulAlexWilson at gmail.com (Wilson) Date: Mon, 4 Aug 2008 11:57:04 -0700 (PDT) Subject: Limits of Metaprogramming References: <0c56829a-7ad2-4ff2-b225-7981538e7c7a@j22g2000hsf.googlegroups.com> <07c3d5f8-563c-43bc-8772-5eb60de52c82@8g2000hse.googlegroups.com> Message-ID: On Aug 4, 6:49?pm, castironpi wrote: > On Aug 4, 4:48?am, Wilson wrote: > > > Hi all, > > > My problem is that I don't know if it's possible to edit these states > > and then write them back to .py. Firstly, if my editing tool was to > > create a new state, I would want to create the class (using type) and > > attach it to the imported state module somehow. I can't find > > > Thanks, > > Paul > > Yes it's possible, using type, but you can't attach it to the module > in any persistent way. ?The next time you load the module, it's back > to the way it was. > > I think this may be the hang-up in your design: if you think about > generating lines of code directly from the user's actions, you might > stay on the right track. ?At that point, you can place them in the .py > file. ?Then you can reimport it, or just execute the new lines > directly. > > If this is your class, > > class Auto54701: > ? def next( self, input ): > ? ? ?if( something ): > ? ? ? ?return value1 > ? ? ?return value2 > > Here's how to work with it at the interactive prompt: > > >>> s= """class Auto54701: > > ... ? def next( self, input ): > ... ? ? ?if( something ): > ... ? ? ? ?return value1 > ... ? ? ?return value2 > ... """>>> s > > 'class Auto54701:\n ?def next( self, input ):\n ? ? if( something ): > \n ? ? ? ret > urn value1\n ? ? return value2\n'>>> exec( s ) > >>> Auto54701 > > > > > > And by the way, you can't use pickle to store types. ?There needs to > be some fleshed-out code to back them up. > > Two more alternatives, which I can discuss more later, one where you > implement code as data, but it ends up being a lot like Python > anyway. ?It only works if your classes' methods are going to be > simple, probably sequential if-s and assignments at most. > > class Auto54701: > ? def next( self, input ): > ? ? ?if( something1 ): > ? ? ? ?return value1 > ? ? ?elif( something2 ): > ? ? ? ?return value2 > ? ? ?elif( something3 ): > ? ? ? ?return value3 > ? ? ?elif( something4 ): > ? ? ? ?return value4 > ? ? return value5 > > can be stored in data as > > ? [ ( something1, value1 ), ( something2, value2 ), ... ] > > , and just checked in a loop, that you only have in code once, rather > than many times. > > class GenericAuto: > ? def next( self, input ): > ? ? for something, value in conditionpairs: > ? ? ? if( something ): > ? ? ? ? return value > ? ? return valuen > > Two, if all your methods will have uniform signatures and closures, > you can store class methods as only their co_code objects: > > >>> C.g.im_func.func_code.co_code > > 'd\x00\x00S' > > And fabricate them dynamically into full live types as needed. Thanks for your comments and advice. This second option intrigues me; could you elaborate further, I don't follow you... Thanks Paul From joncle at googlemail.com Wed Aug 27 07:41:19 2008 From: joncle at googlemail.com (Jon Clements) Date: Wed, 27 Aug 2008 04:41:19 -0700 (PDT) Subject: finding out the number of rows in a CSV file References: Message-ID: <3aaa109e-9a7e-4d02-8af5-0161251d7678@t54g2000hsg.googlegroups.com> On Aug 27, 12:29 pm, "Simon Brunning" wrote: > 2008/8/27 SimonPalmer : > > > anyone know how I would find out how many rows are in a csv file? > > > I can't find a method which does this on csv.reader. > > len(list(csv.reader(open('my.csv')))) > > -- > Cheers, > Simon B. > si... at brunningonline.nethttp://www.brunningonline.net/simon/blog/ Not the best of ideas if the row size or number of rows is large! Manufacture a list, then discard to get its length -- ouch! From gh at gregor-horvath.com Fri Aug 22 04:46:14 2008 From: gh at gregor-horvath.com (Gregor Horvath) Date: Fri, 22 Aug 2008 10:46:14 +0200 Subject: Overwriting property-> can't set attribute In-Reply-To: References: Message-ID: Gregor Horvath schrieb: > > why is this code failing? OK I answer myself :-) Because there is not fset function definied in the property. I have to del the attr before rebinding the attributename to another object. -- Greg From george.sakkis at gmail.com Wed Aug 27 11:00:47 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 27 Aug 2008 08:00:47 -0700 (PDT) Subject: iterparse and unicode References: <75d92503-ae3a-4d62-8ed7-cbfd7e5c96c2@25g2000hsx.googlegroups.com> <48b0eda1$0$12942$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <86d6d90c-fa22-4442-a1d9-486d9dd9e69d@m44g2000hsc.googlegroups.com> On Aug 27, 5:42 am, Fredrik Lundh wrote: > George Sakkis wrote: > >> if you meant to write "encode", you can indeed safely do > >> [s.encode('utf8') for s in strings] as long as all strings are returned > >> by an ET implementation. > > > I was replying to the general assertion that "in 2.x ASCII byte > > strings and unicode strings are compatible", not specifically about > > the strings returned by ET. > > that assertion was made in the context of ET. having to unilaterially > change the topic to "win" an argument is pretty lame. I took Stefan's comment as a general statement, not in the context of ET. Feeling the need to keep "defending" ET at this point is, to borrow your words, pretty lame. > and if you really meant to write "decode", you picked a rather stupid > example to support your complaint about ET not returning Unicode -- your > example does work fine for byte strings (whether they contain pure ASCII > or not), but doesn't work at all for arbitrary Unicode strings, because > decoding things that are already decoded makes very little sense (which > explains why that method was removed in 3.0). The thing is, a user might be happily using ET and call "decode" on the returned byte strings as long as the files happen to be all ASCII, without knowing that ET may also return Unicode. Then after some weeks/ months/years a non-ASCII file comes in and the program breaks. As far as I am concerned, it's a documentation issue, nothing more. George From notnorwegian at yahoo.se Mon Aug 11 09:03:13 2008 From: notnorwegian at yahoo.se (maestro) Date: Mon, 11 Aug 2008 06:03:13 -0700 (PDT) Subject: if len(str(a)) == len(str(r)) and isMult(a, r): faster if isMult is slow? Message-ID: If isMult is slow then: if len(str(a)) == len(str(r)) and isMult(a, r): trues.append((a, r)) will be much faster than: if isMult(a, r) and len(str(a)) == len(str(r)): trues.append((a, r)) right? seems obvious but there is no magic going on that wouldn't make this true right? From george.sakkis at gmail.com Wed Aug 27 19:14:25 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 27 Aug 2008 16:14:25 -0700 (PDT) Subject: Identifying the start of good data in a list References: <94524253-b946-4ffa-ae2e-ae6a555d4e7c@a1g2000hsb.googlegroups.com> <9bf75f04-a4bb-42ec-a80c-66ae4d458fd5@e53g2000hsa.googlegroups.com> <605c4e58-51bd-467c-b69d-37abdf3f472f@25g2000hsx.googlegroups.com> Message-ID: <44641f51-eea2-4180-9651-f7b15a981e5b@z66g2000hsc.googlegroups.com> On Aug 27, 5:48 pm, castironpi wrote: > On Aug 27, 4:34 pm, bearophileH... at lycos.com wrote: > > > > > George Sakkis: > > > > This seems the most efficient so far for arbitrary iterables. > > > This one probably scores well with Psyco ;-) > > > def start_good3(seq, good_ones=4): > > n_good = 0 > > pos = 0 > > for el in seq: > > if el: > > if n_good == good_ones: > > return pos - good_ones > > else: > > n_good += 1 > > elif n_good: > > n_good = 0 > > pos += 1 > > if n_good == good_ones: > > return pos - good_ones > > else: > > return -1 > > > Bye, > > bearophile > > There, that's the regular machine for it. Too much thinking in > objects, and you can't even write a linked list anymore, right? And you're still wondering why do people killfile you or think you're a failed AI project... From sjmachin at lexicon.net Fri Aug 29 18:39:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 29 Aug 2008 15:39:02 -0700 (PDT) Subject: Problem with list.insert References: Message-ID: On Aug 29, 5:10 pm, SUBHABRATA wrote: > Dear group, > Thanx for your idea to use dictionary instead of a list. Your code is > more or less, OK, some problems are there, I'll debug them. Well, I > feel the insert problem is coming because of the Hindi thing. It's nothing to do with the Hindi thing. Quite simply, you are inserting into the list over which you are iterating; this is the "a16" in the first and last lines in the following snippet from your code. The result of doing such a thing (in general, mutating a container that is being iterated over) is not defined and can cause all sorts of problems. It can be avoided by iterating over a copy of the container that you want to change. However I suggest that you seriously look at what you are actually trying to achieve, and rewrite it. for word in a16: #MATCHING WITH GIVEN STRING a17=a2.find(word) if a17>-1: print "The word is found in the Source String" a18=a3.index(word) a19=a3[a18] print a19 #INSERTING IN THE LIST OF TARGET STRING a20=a16.insert(a18,a19) This code has several problems: if a8 in a5: a9=a5.index(a8) a10=a5[a9:] a11=re.search("\xe0.*?\n",a10) a12=a11.group() a13=a12[:-1] found.append(a13) elif a8 not in a5: a14=x not_found.append(a14) else: print "Error" found.extend(not_found) (1) If you ever execute that print statement, it means that the end of the universe is nigh -- throw away the else part and replace "elif a8 not in a5" with "else". (2) The statement "found.extend(not_found)" is emitting a very foul aroma. Your "found" list ends up with the translated words followed by the untranslated words -- this is not very useful and you then have to write some weird code to try to untangle it; just build your desired output as you step through the words to be translated. (3) Your "dictionary" is implemented as a string of the whole dictionary contents -- you are linearly searching a long string for each input word. You should load your dictionary file into a Python dictionary, and load it *once* at the start of your program, not once per input sentence. > And Python2.5 is supporting Hindi quite fluently. Python supports any 8-bit encoding to the extent that the platform's console can display the characters correctly. What is the '\xe0'? The PC-ISCII ATR character? Cheers, John From bearophileHUGS at lycos.com Thu Aug 7 15:33:21 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 7 Aug 2008 12:33:21 -0700 (PDT) Subject: benchmark References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> <489a8cf8$0$11738$9b4e6d93@newsspool1.arcor-online.net> <00aa8eeb$0$20317$c3e8da3@news.astraweb.com> <7d6b3d0d-deb7-4f4b-99a8-1a5b52c1cf1f@h17g2000prg.googlegroups.com> <66bb77c9-a14b-4722-8302-cfa8700656ba@i20g2000prf.googlegroups.com> <21c0d6dc-49a0-4917-b6ce-4773d41ae24f@n33g2000pri.googlegroups.com> Message-ID: <27a45001-7057-4994-bfd9-849bbb353775@k13g2000hse.googlegroups.com> alex23: > Honestly, performance benchmarks seem to be the dick size comparison > of programming languages. I don't agree: - benchmarks can show you what language use for your purpose (because there are many languages, and a scientist has to choose the right tool for the job); - it can show where a language implementation needs improvements (for example the Haskell community has improved one of their compilers several times thank to the Shootout, the D community has not yet done the same because the language is in a too much fast evolving phase still, so performance tunings is premature still); - making some code faster for a benchmark can teach you how to make the code faster in general, how CPUs work, or even a some bits of computer science; - if the benchmarks are well chosen and well used, they can show you what are the faster languages (you may say 'the faster implementations', and that's partially true, but some languages have a semantic that allows better or much better optimizations). A computer is a machine useful for many purposes, programming languages allow some users to make the machine act as they want. So computers and languages give some power, they allow you to do something that you can't do without a computer. A language can give you power because it gives you the ability to write less bug-prone code, or it can give you more pre-built modules that allow you to do more things in less time, or it can give you the power to perform computations in less time, to find a specific solution faster. So Python and C give you different kinds of power, and they are both useful. Other languages like D/Java try to become a compromise, they try to give you as much as possible of both "powers" (and they sometimes succeed, a D/Ocaml program may be almost as fast as C, while being on the whole much simpler/safer to write than C code). Bye, bearophile From roy at panix.com Fri Aug 29 10:15:06 2008 From: roy at panix.com (Roy Smith) Date: Fri, 29 Aug 2008 10:15:06 -0400 Subject: [1,2,3] exactly same as [1,2,3,] ? References: Message-ID: Terry Reedy wrote: > Yes, so you can write something like either your second example or > > l = [ > kjasldfjs, > kjsalfj, > ksjdflasj, > ] > > and insert items without worrying about leaving out the comma (less of a > problem with 'horizontal' list), or delete the last line and not have to > worry about deleting the comma on the line before. Exactly. This is one of those little pieces of syntactic sugar which makes python so nice to work with. The alternative is (in C, for example) abominations like this: const char* l[] = {"foo" , "bar" , "baz" }; and even those are not quite as good because you still have to special-case the first entry. From boblatest at yahoo.com Wed Aug 27 16:16:03 2008 From: boblatest at yahoo.com (Robert Latest) Date: 27 Aug 2008 20:16:03 GMT Subject: [SOLVED] How can this script fail? References: <4129c566-de92-433e-bc3f-f1dcbc255c46@m3g2000hsc.googlegroups.com> Message-ID: <6hlr03Fn28dnU1@mid.uni-berlin.de> Dennis Lee Bieber wrote: >> On 2008-08-27 12:37, boblatest at googlemail.com wrote: >> > Got file in dir >> > Found in path: >> > >> > >> >> This looks strange... the same module in two dirs that only >> differ by case ? >> > Even stranger when you take into account that under Windows, path > names are case-preserving/case-ignored -- so Lib and lib are the SAME > directory (I suspect some environment variable has the directory listed > twice with the change in spelling -- PythonPath perhaps?) Please note that one of the lines is the directory that was found in the "os.walk" loop and the other is the one in sys.path -- I just had them printed out on adjacent lines to point out the difference in case. Anyway, the thing was fixed when I put C:\Python25 into the DOS $PATH environment variable. Still strange though. robert From notvalid2 at sbcglobal.net Sat Aug 23 15:45:24 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Sat, 23 Aug 2008 12:45:24 -0700 Subject: Total No. of "Records" in a File? In-Reply-To: References: <1JXrk.20070$89.12375@nlpi069.nbdc.sbc.com> Message-ID: <2MZrk.11343$vn7.9349@flpi147.ffdc.sbc.com> Fredrik Lundh wrote: > W. eWatson wrote: > >> I have an ordinary text file with a CR at the end of a line, and two >> numbers in each line. Is there some way to determine the number of >> lines (records) in the file before I begin reading it? > > In the general case, no. A file is just a bunch of bytes. If you know > that all lines have exactly the same length, you can of course fetch the > file size and divide by the line size, but that doesn't work for > arbitrary files. > > Why do you need to know the number of lines before reading it, btw? > > > Actually, it was a matter of curiosity, and maybe absent mindedness. I was envisioning a program where I might want to run up and down a file a lot, sometimes deleting a record interactively at the request of the user. However, I wanted to keep him alert to the total number of records remaining. However, in retrospect, I more likely do this with files in a folder. I also want him to be able to skip around in the Win OS folder by saying something like go forward 3 files. I'd like not to have to read all the files between the two points. The whole idea needs some more thinking. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 13 08:50:08 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 13 Aug 2008 14:50:08 +0200 Subject: You advice please In-Reply-To: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> Message-ID: <48a2d874$0$4657$426a74cc@news.free.fr> Hussein B a ?crit : > Hey, > I'm a Java/Java EE developer and I'm playing with Python these days. > I like the Python language so much and I like its communities and the > Django framework. > My friends are about to open a Ruby/Rails shop and they are asking me > to join them. > I don't know what, sure I'm not leaving Java, but they are asking me > to stop learning Python and concentrate on Ruby/Rails. > The sad fact (at least to me), Ruby is getting a lot of attention > these days. > Why Python isn't getting this attention although is a much more mature > language and it is used by many big, big names? RoR peoples are good at marketing. And Ruby's object model is probably less alien - at least at first sight - to the Java crowd than Python's object model is. But still, Python seems to get some serious exposure - at least outside of the Java world - these last monthes. > And do I dare to say it is much more charming? > What do you think of Ruby/Rails? do they worth learning and working > with? Both are certainly worth learning. I can't tell about the "working with" part since I never used any of them for anything serious. > Any way, I'm not leaving Python and I will try to study it every time > I get a chance... > Thanks. From redalastor at gmail.com Fri Aug 22 11:24:44 2008 From: redalastor at gmail.com (Dan) Date: Fri, 22 Aug 2008 11:24:44 -0400 Subject: Regex on a huge text Message-ID: I'm looking on how to apply a regex on a pretty huge input text (a file that's a couple of gigabytes). I found finditer which would return results iteratively which is good but it looks like I still need to send a string which would be bigger than my RAM. Is there a way to apply a regex directly on a file? Any help would be appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From matthieu.brucher at gmail.com Thu Aug 7 03:48:28 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Thu, 7 Aug 2008 09:48:28 +0200 Subject: .cpp to .pyd In-Reply-To: References: Message-ID: > I think that my MS visual studio cannot find "boost python", if > that's the problem then can you tell me how can I solve it. > This is very begginer question,but I can't find answer nowhere, and I > don't have any expirience with Microsoft products. Hi, Put Boost in your include path (options of Visual Studio). Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher From sjmachin at lexicon.net Tue Aug 26 20:52:00 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 26 Aug 2008 17:52:00 -0700 (PDT) Subject: Date Comparison and Manipulation Functions? References: Message-ID: <6cdf0c14-80b6-42c4-8047-8c01fda8b87c@r15g2000prh.googlegroups.com> On Aug 27, 10:21 am, "W. eWatson" wrote: > > I'm using IDLE for Python 2.4, and put pfydate distribution in > C:\Python24\Lib\site-packages\pfydate, as required by the > page. > How to install pyfdate. > > Save pyfdate.py into your PythonNN/Lib/site-packages directory. > I copied it into C:\Python24\Lib\site-packages\pfydate If that means that you ended up with C:\Python24\Lib\site-packages\pfydate\pyfdate.py then you have *not* followed the instructions "Save pyfdate.py into your PythonNN/Lib/site-packages directory". You need to end up with C:\Python24\Lib\site-packages\pyfdate.py If in doubt, get to a command prompt and type dir C:\Python24\Lib\site-packages\pfydate* and tell us what you see. > > Execution in IDLE produced: > --------------------------------- > Traceback (most recent call last): > File > "C:\Sandia_Meteors\Improved_Sentinel\Sentinel_Playground\date_example.py", > line 1, in ? > from pyfdate import * > ImportError: No module named pyfdate > --------------------------------- > Looking in the Path Browser, I don't see pyfdate. I see PIL package and > scipy package. From shyamala1010 at gmail.com Wed Aug 20 18:40:24 2008 From: shyamala1010 at gmail.com (syam) Date: Wed, 20 Aug 2008 15:40:24 -0700 (PDT) Subject: shyam Message-ID: E-mail:shyamala1010 at gmail.com web - http://www.shyamalaindian.blogspot.com/ From fredrik at pythonware.com Thu Aug 14 11:41:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 17:41:13 +0200 Subject: a question about mysqldb In-Reply-To: <9b1bd962-9e03-43bd-8c0b-2c6c1cccc95d@x16g2000prn.googlegroups.com> References: <9b1bd962-9e03-43bd-8c0b-2c6c1cccc95d@x16g2000prn.googlegroups.com> Message-ID: Evan wrote: > a simple problem but I do not know why...:(, could anyone help me? > > MySQLdb nominally uses just the %s placeholder style, in my script, i > got error if you want to use placeholder(%s) for table name: Placeholders are supposed to be used for *values*, not other parts of the SQL statement. To insert table names, column names and stuff like that, use Python-level formatting. try doing: table = "tmp" sql = "select tID,tNote from " + table + " where tID=%s" param = [1] s.dbptr.execute(sql, param) > But sql worked but the I got no query result: > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ > >>> >>> str="select tID,tNote from tmp where %s = %s" > >>> >>> e=["tID",int(1)] the string value "tID" doesn't match an integer with the value 1, so that's expected. From mwojc at NOSPAMp.lodz.pl Tue Aug 12 17:17:49 2008 From: mwojc at NOSPAMp.lodz.pl (mwojc) Date: Tue, 12 Aug 2008 23:17:49 +0200 Subject: __getattr__, __setattr__ and pickle References: <48a1cdce$0$14748$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > mwojc a ?crit : >> Hi! >> My class with implemented __getattr__ and __setattr__ methods cannot be >> pickled because of the Error: >> >> ====================================================================== >> ERROR: testPickle (__main__.TestDeffnet2WithBiases) >> ---------------------------------------------------------------------- >> Traceback (most recent call last): >> File "deffnet.py", line 246, in testPickle >> cPickle.dump(self.denet, file) >> TypeError: 'NoneType' object is not callable >> >> ---------------------------------------------------------------------- >> >> Is there an obvious reason i don't know, which prevents pickling with >> those methods (if i comment them out the pickling test passes)? >> >> I'm using Python 2.4.4 on Gentoo Linux. The mentioned methods goes as >> follows: >> >> def __setattr__(self, name, value): >> if name == 'weights': >> j = 0 >> for net in self.nets: >> w1 = self.wmarks[j] >> w2 = self.wmarks[j+1] >> net.weights = value[w1:w2] >> j += 1 >> else: >> self.__dict__[name] = value >> >> def __getattr__(self, name): >> if name == 'weights': >> j = 0 >> for net in self.nets: >> w1 = self.wmarks[j] >> w2 = self.wmarks[j+1] >> self._weights[w1:w2] = net.weights >> j += 1 >> return self._weights > > __getattr__ should raise an AttributeError when name != 'weight' instead > of (implicitely) returning None. pickle looks for a couple special > method in your object[1], and it looks like it doesn't bother to check > if what it found was really callable. Yes, raising AttributeError helped. Thanks! > > FWIW, you'd be better using a property instead of __getattr__ / > __setattr__ if possible. You're probably right again, in this case it's better to use property. > And while we're at it, you dont need to > manually take care of your index in the for loop - you can use > enumerate(iterable) instead: > > for j, net in enumerate(self.nets): > w1 = self.wmarks[j] > w2 = self.wmarks[j+1] > self._weights[w1:w2] = net.weights > return self._weights > Sometimes i use manual handling of index because i'm convinced that enumeration is a bit slower than this. But i'm not really sure about it... Thanks again. Greetings, -- Marek From python.leojay at gmail.com Fri Aug 22 13:47:23 2008 From: python.leojay at gmail.com (Leo Jay) Date: Sat, 23 Aug 2008 01:47:23 +0800 Subject: How to read and write the same socket in different threads? Message-ID: <4e307e0f0808221047p739effb3pd81bfacfe3126b93@mail.gmail.com> I'd like to read and write the same socket in different threads. one thread is only used to read from the socket, and the other is only used to write to the socket. But I always get a 10022 'Invalid argument' exception. Anyone knows why? I'm using windows xp. my source code is here: http://pastebin.com/m23e633a2 and the stack trace is: C:\WINDOWS\system32\cmd.exe /c python "main.py" Exception in thread Thread-1: Traceback (most recent call last): File "c:\Python25\lib\threading.py", line 486, in __bootstrap_inner self.run() File "c:\Python25\lib\threading.py", line 446, in run self.__target(*self.__args, **self.__kwargs) File "main.py", line 7, in read_socket sock.connect(('127.0.0.1', remoteport)) File "", line 1, in connect error: (10022, 'Invalid argument') Exception in thread Thread-3: Traceback (most recent call last): File "c:\Python25\lib\threading.py", line 486, in __bootstrap_inner self.run() File "c:\Python25\lib\threading.py", line 446, in run self.__target(*self.__args, **self.__kwargs) File "main.py", line 7, in read_socket sock.connect(('127.0.0.1', remoteport)) File "", line 1, in connect error: (10022, 'Invalid argument') If i replace the 'args' in line 39 with '(socket(), remoteport)', which means use a different socket to connect to the remote port, the program works. But if the first element of the tuple is 's', the program doesn't work. Is it possible to read and write the same socket in different threads? Thanks in advance. -- Best Regards, Leo Jay From fredrik at pythonware.com Wed Aug 20 17:46:45 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 20 Aug 2008 23:46:45 +0200 Subject: Negative integers In-Reply-To: References: Message-ID: johnewing wrote: > I am trying to figure out how to test if two numbers are of the same > sign (both positive or both negative). I have tried > > abs(x) / x == abs(y) / y > > but that fails when one of the numbers is 0. I'm sure that there is > an easy way to do this. Any suggestions? (a < 0) == (b < 0) From geonomica at gmail.com Sat Aug 30 08:33:18 2008 From: geonomica at gmail.com (gianluca) Date: Sat, 30 Aug 2008 05:33:18 -0700 (PDT) Subject: __stack_chk_fail_local References: <40a21602-a613-484b-aae4-4643dab9e146@8g2000hse.googlegroups.com> Message-ID: <1217e9d2-b81f-471d-854e-4f39ad9b40f5@x35g2000hsb.googlegroups.com> On 30 Ago, 12:05, "Marco Bizzarri" wrote: > On Fri, Aug 29, 2008 at 7:53 PM, gianluca wrote: > > hy list, > > I've built _libfoo.so and libfoo.py library with swig and I've copied > > in /usr/lib/python2.5/lib-dynload/ but when import the module > > >>>import libfoo > > > I've that message > > > Traceback (most recent call last): > > File "", line 1, in > > ImportError: /usr/lib/python2.5/lib-dynload/_libfoo.so: undefined > > symbol: __stack_chk_fail_local > > > Could anybody help me? > > > gianluca > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Have you tried to use ldd against the _libfoo.so to check if it is > able to get all the libraries it needs? > > Regards > Marco > > -- > Marco Bizzarrihttp://iliveinpisa.blogspot.com/ I've tried with ldd and the library aren't loaded. I don't use my *.i interface so is quite difficult modify it (realy, the libraru is supplied with make). Any suggests? gianluca From musiccomposition at gmail.com Mon Aug 25 21:52:24 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 25 Aug 2008 18:52:24 -0700 (PDT) Subject: Enhanced property decorator References: <9e36cdd4-7d66-4eae-aa60-1782e500abfe@34g2000hsh.googlegroups.com> Message-ID: <25ffaf6d-1bcb-4f6b-8074-a1ca82a1e6a8@d1g2000hsg.googlegroups.com> On Aug 25, 8:45?pm, Daniel wrote: > I've often been frustrated by the inability of the built-in property > descriptor to handle anything other than a read-only property when > used as a decorator. Furthermore, read/write/delete properties take > their doc-string and property definition at a non-intuitive and > awkward place (after the getter/setter/delter functions). The > following are three possible solutions to this problem (inspired by > messagehttp://groups.google.com/group/comp.lang.python/msg/9a56da7ca8ceb7c7). > I don't like the solution in that thread because it uses apply() which > will go away in Python 3. I didn't read the rest of the thread, but I think Python 2.6 may have want you want: class A(object): @property def my_prop(): return self._prop @my_prop.setter def my_prop(prop): self._prop = prop @my_prop.deleter def my_prop(): del self._prop From timid.gentoo at gmail.com Sun Aug 10 16:24:00 2008 From: timid.gentoo at gmail.com (Spitfire) Date: Sun, 10 Aug 2008 16:24:00 -0400 Subject: parsing XSD References: <489ee8e9$0$12948$9b4e6d93@newsspool2.arcor-online.net> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Stefan, Stefan Behnel wrote: | BTW, if you want to write XML handling code that lets you understand what you | are doing, try ElementTree or lxml. lxml also has support for XML Schema, in | case you want to do more than parsing with it. | | Stefan Thanks! - -- _ _ _]{5pitph!r3}[_ _ _ __________________________________________________ ?I'm smart enough to know that I'm dumb.? ~ - Richard P Feynman -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFIn05gKVWYDRRZoskRAm0aAKCk3Sc7amPz16t1fhBaeSMvqJtnEgCffLL2 YHO0ahXp4cAese+zPSrzyH0= =yQIO -----END PGP SIGNATURE----- From PaulAlexWilson at gmail.com Mon Aug 4 08:39:22 2008 From: PaulAlexWilson at gmail.com (Wilson) Date: Mon, 4 Aug 2008 05:39:22 -0700 (PDT) Subject: Limits of Metaprogramming References: <0c56829a-7ad2-4ff2-b225-7981538e7c7a@j22g2000hsf.googlegroups.com> <0b5bd851-0e5c-4aef-bee6-6faa7c82a1e1@l64g2000hse.googlegroups.com> Message-ID: On 4 Aug, 12:55, Jeff wrote: > You could write a class composed of states and then use the pickle > module to serialize it to disk. Thanks Jeff. I guess this is my intermediary format! From danb_83 at yahoo.com Thu Aug 7 00:09:30 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 6 Aug 2008 21:09:30 -0700 (PDT) Subject: random numbers according to user defined distribution ?? References: <00aa4a9a$0$20317$c3e8da3@news.astraweb.com> Message-ID: <41695897-6fec-4de1-ae8d-e8ec31510476@j1g2000prb.googlegroups.com> On Aug 6, 8:26?pm, Steven D'Aprano wrote: > On Wed, 06 Aug 2008 15:02:37 -0700, Alex wrote: > > Hi everybody, > > > I wonder if it is possible in python to produce random numbers according > > to a user defined distribution? Unfortunately the random module does not > > contain the distribution I need :-( > > This is a strange question. Of course you can -- just write a function to > do so! Here's some easy ones to get you started: > ... > > There's no general way to create a random function for an arbitrary > distribution. I don't think there's a general way to *describe* an > arbitrary random distribution. What about the quantile function? From mh at pixar.com Thu Aug 28 21:24:38 2008 From: mh at pixar.com (mh at pixar.com) Date: Fri, 29 Aug 2008 01:24:38 GMT Subject: iterating over two arrays in parallel? Message-ID: I want to interate over two arrays in parallel, something like this: a=[1,2,3] b=[4,5,6] for i,j in a,b: print i,j where i,j would be 1,4, 2,5, 3,6 etc. Is this possible? Many TIA! Mark -- Mark Harrison Pixar Animation Studios From paul.hankin at gmail.com Sat Aug 2 14:58:05 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 2 Aug 2008 11:58:05 -0700 (PDT) Subject: Searching for some kind of data type References: <33d13c77-e710-4951-a559-7ea8b6e15287@26g2000hsk.googlegroups.com> Message-ID: <61fc0a0b-2c87-4e7b-8b9a-5dd04e30226b@z66g2000hsc.googlegroups.com> On Aug 2, 1:12?pm, "Giampaolo Rodola'" wrote: > Hi, > for an FTP server I wrote I'd need to group the FTP commands in one > table that defines the command itself, the syntax string, required > permission, whether it requires authorization, whether it takes > argument and whether there's a need to validate the path from the > argument. > The more obvious way I found to do that is something like this: > > class CommandProperty: > ? ? def __init__(self, perm, auth_needed, arg_needed, check_path, > syntax): > ? ? ? ? self.perm = perm > ? ? ? ? self.auth_needed = auth_needed > ? ? ? ? self.arg_needed = arg_needed > ? ? ? ? self.check_path = check_path > ? ? ? ? self.syntax = syntax > > ftp_cmds = { > ? ? "ABOR" : CommandProperty(perm=None, auth_needed=True, > arg_needed=False, check_path=False, syntax="ABOR (abort transfer)."), > ? ? "APPE" : CommandProperty(perm='a', ?auth_needed=True, > arg_needed=True, ?check_path=True, ?syntax="APPE file-name > (append data to an existent file)."), > ? ? "CDUP" : CommandProperty(perm='e', > auth_needed=True,arg_needed=False, check_path=False, syntax="CDUP (go > to parentdirectory)."), > ? ? ... > ? ? ... > ? ? ... > ? ? } > > ...but I find it somewhat redundant and... "ugly". > I was wondering if there was some kind of data type which could better > fit such purpose or if someone could suggest me some other approach to > do this same thing. Maybe using a dictionary is not the better choice > here. How about something like this? The idea is to summarize the command table, then construct the ftp command dictionary programatically from it. cmd_table = dict( ABOR='-AR- (abort transfer)', APPE='aARP file-name (append data to a file)', CDUP='eA-- (go to parent directory)', ... ) The first block of four characters give the options: permission, whether authentication is needed, whether the argument is required, and whether the path needs checking. Permission is the permission letter or - (for none), A or - for authentication, R or - for argument required, and - or P for path required. Then the help text follows (with the command name omitted since it's redundant). Turning these into CommandProperty's is straightforward (untested code): ftp_commands = {} for cmd, descriptor in cmd_table.iteritems(): options, help = descriptor.split(' ', 1) options = [None if opt == '-' else opt for opt in options] perm, auth, arg, path = options assert perm is None or perm in 'ae...' assert auth is None or auth == 'A' assert arg is None or arg == 'R' assert path is None or path == 'P' ftp_commands[cmd] = CommandProperty(perm=perm, auth_required=auth, arg_required=arg, check_path=path, syntax = '%s %s' % (cmd, help)) -- Paul Hankin From rweir at ertius.org Wed Aug 13 02:21:00 2008 From: rweir at ertius.org (Rob Weir) Date: Wed, 13 Aug 2008 16:21:00 +1000 Subject: Checking a file's time stamp -- followup References: <48A2790A.6080108@it.uu.se> Message-ID: <877ialtoz7.fsf@hypercube.ertius.org> On 13 Aug 2008, Virgil Stokes wrote: > Is it possible to change the time stamp of a file (Win2K platform)? If > yes, how? os.utime, http://docs.python.org/lib/os-file-dir.html. -- -rob From castironpi at gmail.com Fri Aug 22 12:44:42 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 22 Aug 2008 09:44:42 -0700 (PDT) Subject: property() usage - is this as good as it gets? References: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> Message-ID: <421a4af5-0421-4d63-8aa2-b6097fcc83f3@a70g2000hsh.googlegroups.com> On Aug 22, 11:18?am, David Moss wrote: > Hi, > > I want to manage and control access to several important attributes in > a class and override the behaviour of some of them in various > subclasses. > > Below is a stripped version of how I've implemented this in my current > bit of work. > > It works well enough, but I can't help feeling there a cleaner more > readable way of doing this (with less duplication, etc). > > Is this as good as it gets or can this be refined and improved > especially if I was to add in a couple more attributes some fairly > complex over-ride logic? > > #!/usr/bin/env python > > class A(object): > ? ? def __init__(self): > ? ? ? ? self._x = None > ? ? ? ? self._y = None > > ? ? def _set_x(self, value): > ? ? ? ? self._x = value > > ? ? def _get_x(self): > ? ? ? ? return self._x > > ? ? x = property(_get_x, _set_x) > > ? ? def _set_y(self, value): > ? ? ? ? self._y = value > > ? ? def _get_y(self): > ? ? ? ? return self._y > > ? ? y = property(_get_y, _set_y) Within the bounds of Python, that's it. In the cases where you're not executing code on 'get' or 'set', it might be possible to have a default getter/setter, that just sets the value of a variable name. This keeps your interface the same across inheritance and changes. Possible to have it assign a default value too. def _set_z(self, value): self._z = value #def _get_z(self): # return self._z z = property( True, _set_z ) #still gets self._z Unless, you are looking at something 'periodic' or regular. From something I'm working on: def _getbalance( self ): return self._tree.geti( self.where+ self.lookup[ 'balance' ] ) def _getparent( self ): return self._tree.getI( self.where+ self.lookup[ 'parent' ] ) Where 'balance' and 'parent' could both come from something generic: balance= property( tree_lookup( 'balance' ) ) parent= property( tree_lookup( 'parent' ) ) They would have to take care to define 'self' properly and everything. From __peter__ at web.de Mon Aug 25 13:08:05 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 25 Aug 2008 19:08:05 +0200 Subject: Why do all my loggers start auto-disabled? References: <13922a38-da45-4608-9bab-2bc153a07eae@k7g2000hsd.googlegroups.com> Message-ID: jonfroehlich wrote: > I am a relative newbie to Python and its logging infrastructure; > however, I have programmed extensively with Java/C# and log4j and > log4net. That, I suppose, could be the root of my problem :) > > I am trying to setup one logger per module (as this is roughly > analogous to how I've used log4j/log4net). However, I've noticed that > my loggers have the disabled flag set to true (more accurately, 1) > when they are initialized. For each logger, do I have to force > disabled = False? To make this more concrete, here is an example. > > In example.py: > > import logging > import logging.config > > _log = logging.getLogger("prediction.predict") > > def main(): > logging.config.fileConfig('logconfig.conf') > _log.warn("test warning!") > > if __name__ == "__main__": > main() > > Unfortunately, this does not print out "test warning!" and if I put a > breakpoint at the _log.warn("test warning!") line, _log.disabled > equals 1. If I change main to: > > def main(): > logging.config.fileConfig('predict_logconfig.conf') > _log.disabled = False > _log.warn("test warning!") > > It works! So, am I doing something wrong or do I always have to force > my loggers to be enabled? Should I update my configuration file so > that loggers start as enabled? Here is my config file I think you have to put the logger into your config file to avoid that it will be disabled by fileConfig(): > (logconfig.conf): > > [formatters] > keys: detailed,simple > > [handlers] > keys: console,filelog [loggers] keys: root, predict # ... [logger_predict] qualname: prediction.predict handlers: Peter From rajanikanth at gmail.com Thu Aug 28 01:35:02 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Wed, 27 Aug 2008 22:35:02 -0700 Subject: Python on Mac In-Reply-To: <37e1fa620455c7c04b3d8b000e30770e@85.18.140.153> References: <37e1fa620455c7c04b3d8b000e30770e@85.18.140.153> Message-ID: <84bdef3c0808272235o1e5fa1fdu2c49fbba2a5c4f08@mail.gmail.com> Hi! Luca, All you need to do is in the final step of (configure, make and make install), use make altinstall instead of make install. That way, your original python implementation won't be affected. Thanks, Raj On Wed, Aug 27, 2008 at 7:46 AM, wrote: > Hi All. > I'm really new in the python world, so, sorry if my question is particulary > stupid. > I've just installed on my system (Mac OS X 10.4 PPC) the python version > 2.5.2 and all works fine. > My next step is to install the version 3.0 (when available). I've read > somewhere that this version will break the backward compatibility with the > 2.x series. I know that several Mac apps (such as Xcode developement > environment) use python for its internal functionalities. Now, my question > is: what will appen to the Mac apps if I install the version 3.0 of python? > Is it safe to install this version without to compromise the behaviour of > the system? > > Thanks in advance for any answer and, again, sorry if my question is > particulary stupid, I will learn with time. > > Luca. > > -- > Email.it, the professional e-mail, gratis per te: http://www.email.it/f > > Sponsor: > Libera la tua voglia di giocare. Scarica Videogames sul cellulare! > Clicca qui: http://adv.email.it/cgi-bin/foclick.cgi?mid=7753&d=20080827 > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From bedouglas at earthlink.net Fri Aug 29 11:16:12 2008 From: bedouglas at earthlink.net (bruce) Date: Fri, 29 Aug 2008 08:16:12 -0700 Subject: No subject Message-ID: <0a6201c909ea$2cd566b0$0301a8c0@tmesa.com> Hi. I'm using mechanize to parse a page/site that uses the meta http-equiv tag in order to perform a refresh/redirect of the page. I've tried a number of settings, and read different posts on various threads, but seem to be missing something. the test.html page is the page that the url returns, however, i was expecting the test.py app to go ahead and perform the redirect/refresh automatically. does the page (test.html) need to be completely valid html? Any thoughts on what's screwed up here?? thanks ---------------------------------------------------- test.py -------- import re import libxml2dom import urllib import urllib2 import sys, string from mechanize import Browser import mechanize #import tidy import os.path import cookielib from libxml2dom import Node from libxml2dom import NodeList import subprocess import time ######################## # # Parse pricegrabber.com ######################## cj = "p" COOKIEFILE = 'cookies.lwp' #cookielib = 1 urlopen = urllib2.urlopen #cj = urllib2.cookielib.LWPCookieJar() cj = cookielib.LWPCookieJar() Request = urllib2.Request br = Browser() br2 = Browser() if cj != None: print "sss" #install the CookieJar for the default CookieProcessor if os.path.isfile(COOKIEFILE): cj.load(COOKIEFILE) print "foo\n" if cookielib: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) print "foo2\n" user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values1 = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } url="http://schedule.psu.edu/" #======================================= if __name__ == "__main__": # main app txdata = None #---------------------------- ##br.set_cookiejar(cj) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.set_handle_refresh(True) br.addheaders = [('User-Agent', 'Firefox')] #url=str(url)+str("act_main_search.cfm")+"?" #url=url+"Semester=FALL%202008%20%20%20&" #url=url+"CrseLoc=OZ%3A%3AAbington%20Campus&" #url=url+"CECrseLoc=AllOZ%3A%3AAbington%20Campus&" #url=url+"CourseAbbrev=ACCTG&CourseNum=&CrseAlpha=&Search=View+schedule" #url="http://schedule.psu.edu/act_main_search.cfm?Semester=FALL%202008%20%20 %20%20&CrseLoc=OZ%3A%3AAbington%20Campus&CECrseLoc=AllOZ%3A%3AAbington%20Cam pus&CourseAbbrev=ACCTG&CourseNum=&CrseAlpha=" url="http://schedule.psu.edu/act_main_search.cfm?Semester=FALL%202008%20%20% 20%20&CrseLoc=OZ%3A%3AAbington%20Campus&CECrseLoc=AllOZ%3A%3AAbington%20Camp us&CourseAbbrev=ACCTG&CourseNum=&CrseAlpha=&CFID=543143&CFTOKEN=71842529" print "url =",url br.open(url) #cj.save(COOKIEFILE) # resave cookies res = br.response() # this is a copy of response s = res.read() print "slen=",len(s) print s ========================================= test.html Tech Type --------------------------------------------------------- sys.exit() From Graham.Dumpleton at gmail.com Mon Aug 25 02:44:54 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 24 Aug 2008 23:44:54 -0700 (PDT) Subject: How to check in CGI if client disconnected References: <75a68632-1f47-48d7-a890-fe1b92484c2a@w24g2000prd.googlegroups.com> <57942430-2040-4a42-8d3b-f9248aee21be@r35g2000prm.googlegroups.com> Message-ID: On Aug 25, 4:26?pm, Vishal wrote: > Hi, > > ? Thanks for the replies. In my case, the cgi is sending a large file > to the client. In case the the stop button is pressed on the browser > to cancel the download, i want to do some cleanup action. It's all one- > way transfer in this case, so i can't expect the client to send > anything to me. I read somewhere that apache sends the SIGTERM signal > to a cgi when the client disconnects. However, my cgi is not getting > the signal - is there a way to have the cgi catch and handle the > SIGTERM? > > I tried using the signal module > > --- > def sigtermHandler(signum, frame): > ? ? # do some cleanup > > signal.signal(signal.SIGTERM, sigtermHandler) > > --- > > But even this doesn't work. Have you considered simply checking to see if the amount of POST content read matches the inbound Content-Length specified in the CGI environment. If your processing of POST content finds less than what was meant to be sent, then likely that the client browser aborted request before all content could be sent. Graham > Regards, > > -vishal. > On Aug 25, 2:58?am, "Gabriel Genellina" > wrote: > > > En Sun, 24 Aug 2008 17:51:36 -0300, Wojtek Walczak escribi?: > > > > On Sun, 24 Aug 2008 17:21:52 -0300, Gabriel Genellina wrote: > > >>> ? ?I am writing a CGI to serve files to the caller. I was wondering if > > >>> there is any way to tell in my CGI if the client browser is still > > >>> connected. If it is not, i want to execute some special code before > > >>> exiting. > > > >>> ? ?Is there any way to do this? Any help on this is appreciated :) > > > >> I don't think so. A CGI script runs once per request, and exits. The server may find that client disconnected, but that may happen after the script finished. > > > > I am not a web developer, but I think that the only way is to > > > set a timeout on server side. You can't be sure that the client > > > disconnected, but you can stop CGI script if there's no > > > action on client side for too long. > > > Which kind of client action? Every link clicked or form submitted generates a different request that triggers a CGI script; the script starts, reads its parameters, do its task, and exits. There is no "long running process" in CGI - the whole "world" must be recreated on each request (a total waste of resources, sure). > > > If processing takes so much time, it's better to assign it a "ticket" - the user may come back later and see if its "ticket" has been finished, or the system may send an email telling him. > > > -- > > Gabriel Genellina From sjmachin at lexicon.net Wed Aug 6 17:06:30 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 6 Aug 2008 14:06:30 -0700 (PDT) Subject: Parsing of a file References: <760c7cd4-5a23-4e8e-801d-31670afd050b@l42g2000hsc.googlegroups.com> Message-ID: <91b5cd11-1bb6-4715-8964-85afc77862d1@1g2000pre.googlegroups.com> On Aug 7, 6:02 am, Mike Driscoll wrote: > On Aug 6, 1:55 pm, Tommy Grav wrote: > > > > > I have a file with the format > > > Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames > > 5 Set 1 > > Field f31448: Ra=20:24:58.13 Dec=+79:39:43.9 MJD=53370.06811620 Frames > > 5 Set 2 > > Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames > > 5 Set 3 > > Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames > > 5 Set 4 > > Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames > > 5 Set 5 > > Field f30560: Ra=20:27:01.82 Dec=+74:47:50.3 MJD=53370.06860400 Frames > > 5 Set 6 > > Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames > > 5 Set 7 > > Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames > > 5 Set 8 > > Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames > > 5 Set 9 > > Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames > > 5 Set 10 > > > I would like to parse this file by extracting the field id, ra, dec > > and mjd for each line. It is > > not, however, certain that the width of each value of the field id, > > ra, dec or mjd is the same > > in each line. Is there a way to do this such that even if there was a > > line where Ra=****** and > > MJD=******** was swapped it would be parsed correctly? > > > Cheers > > Tommy > > I'm sure Python can handle this. Try the PyParsing module or learn > Python regular expression syntax. > > http://pyparsing.wikispaces.com/ > > You could probably do it very crudely by just iterating over each line > and then using the string's find() method. > Perhaps you and the OP could spend some time becoming familiar with built-in functions and str methods. In particular, str.split is your friend: C:\junk>type tommy_grav.py # Look, Ma, no imports! guff = """\ Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames 5 Set 1 Field f31448: MJD=53370.06811620123 Dec=+79:39:43.9 Ra=20:24:58.13 Frames 5 Set 2 Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames 5 Set 3 Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames 5 Set 4 Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames 5 Set 5 Field f30560: Ra=20:27:01.82 Dec=+74:47:50.3 MJD=53370.06860400 Frames 5 Set 6 Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames 5 Set 7 Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames 5 Set 8 Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames 5 Set 9 Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames 5 Set 10 """ is_angle = { 'ra': True, 'dec': True, 'mjd': False, } def convert_angle(text): deg, min, sec = map(float, text.split(':')) return (sec / 60. + min) / 60. + deg def parse_line(line): t = line.split() assert t[0].lower() == 'field' assert t[1].startswith('f') assert t[1].endswith(':') field_id = t[1].rstrip(':') rdict = {} for f in t[2:]: parts = f.split('=') if len(parts) == 2: key = parts[0].lower() value = parts[1] assert key not in rdict if is_angle[key]: rvalue = convert_angle(value) else: rvalue = float(value) rdict[key] = rvalue return field_id, rdict['ra'], rdict['dec'], rdict['mjd'] for line in guff.splitlines(): line = line.strip() if not line: continue field_id, ra, dec, mjd = parse_line(line) print field_id, ra, dec, mjd C:\junk>tommy_grav.py f29227 20.3962611111 67.5 53370.0679769 f31448 20.4161472222 79.6621944444 53370.0681162 f31226 20.4126388889 78.4458888889 53370.0682386 f31004 20.4181333333 77.2296944444 53370.0683602 f30782 20.4310944444 76.0135 53370.0684821 f30560 20.4505055556 74.7973055556 53370.068604 f30338 20.4756527778 73.5811111111 53370.0687262 f30116 20.5060277778 72.3648888889 53370.0688489 f29894 20.5412611111 71.1486111111 53370.0689707 f29672 20.5810805556 69.9323888889 53370.0690935 Cheers, John From bdesth.quelquechose at free.quelquepart.fr Fri Aug 15 11:05:08 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 15 Aug 2008 17:05:08 +0200 Subject: You advice please In-Reply-To: <2a611c23-16a9-4a9d-8c93-3b24d7b404af@e39g2000hsf.googlegroups.com> References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> <2a611c23-16a9-4a9d-8c93-3b24d7b404af@e39g2000hsf.googlegroups.com> Message-ID: <48a5b718$0$10768$426a74cc@news.free.fr> Hussein B a ?crit : (snip) > But this critisim looks so serious: > http://en.wikipedia.org/wiki/Ruby_programming_language#Criticism Most of what's written here could apply to Python too - all the part which mostly reflects the usual parano?a from bondage&discipline langages addicts wrt/ dynamic languages. The remaining is about implementation issues in ruby 1.8. From alexnbryan at gmail.com Mon Aug 18 19:10:46 2008 From: alexnbryan at gmail.com (Alexnb) Date: Mon, 18 Aug 2008 16:10:46 -0700 (PDT) Subject: searching through a string and pulling characters In-Reply-To: <307cf7b3-311d-4c1e-bb89-c685c0d548c9@n38g2000prl.googlegroups.com> References: <19039594.post@talk.nabble.com> <307cf7b3-311d-4c1e-bb89-c685c0d548c9@n38g2000prl.googlegroups.com> Message-ID: <19041720.post@talk.nabble.com> If by "What happened when you did:" you mean dictionary.com and yourdictionary.com? Nothing, they work but screen scraping isn't medicore at best. They both work fine (yourdictionary is better for screen scraping) but. I want maybe an offline soloution. But the whole reason for the program is that I can type in 20 words at one time, get them defined and formatted and then save all from my app. So far, all is good, I just need an offline soloution, or one from a database. You say a free dictionary program. But how can I get definitions from another program w/o opening it? Anyway, Ideas? John Machin wrote: > > On Aug 19, 8:34 am, Alexnb wrote: > >> The number is based on the word(s) they type into my program, and then it >> fetches the number that word is in the list of words and then will search >> the definitions document and go to the nth def. It probably won't work, >> but >> that is the Idea. > > Consider (1) an existing (free) dictionary application (2) using a > database, if you feel you must write your own application. > >> >> Also, on a side-note, does anyone know a very simple dictionary site, >> that >> isn't dictionary.com or yourdictionary.com. Or, a free dictionary that I >> can >> download to have an offline reference? > > What happened when you did: > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/searching-through-a-string-and-pulling-characters-tp19039594p19041720.html Sent from the Python - python-list mailing list archive at Nabble.com. From dlenski at gmail.com Fri Aug 15 09:56:41 2008 From: dlenski at gmail.com (Dan Lenski) Date: Fri, 15 Aug 2008 13:56:41 GMT Subject: negative numbers are not equal... References: Message-ID: On Thu, 14 Aug 2008 17:18:55 -0300, ariel ledesma wrote: > hello guys > > i just ran into this when comparing negative numbers, they start > returning False from -6 down, but only when comparing with 'is' > > >>> m = -5 > >>> a = -5 > >>> m is a > True > >>> m = -6 > >>> a = -6 > >>> m is a > False > >>> m == a > True > > i read that 'is' compares if they are really the same object, but i > don't that's it because then why does -5 return True? of course i could > only use == to compare, but still, what am i missing here? thanks in > advance They also return False for positive numbers > 256. Try this: >>> print [x for x in range(-10,260) if x is not x+1-1] [-10, -9, -8, -7, -6, 257, 258, 259] There is a good explanation for this: the "is" operator checks for object identity, not equality. Basically "a is m" asks, does the variable name "a" reference the same memory location as the variable name "m"? For integers in the range of -5<=x<=256, Python pre-caches all of these values, and whenever a variable takes on one of those values, it uses the cached value. This is an optimization: it prevents the need to allocate a new Python object for these very very common small integer values. For integer literals outside this range, a new Python object gets created when they are assigned to variables, so a=500 followed by m=500 will create new objects. The "is" operator just shows the effect of this caching. It's unimportant for real code since you never care whether two numeric variables refer to the same object (only important for complex data structures where their storage may overlap)... only whether they are equal or not. Dan Lenski (PS- The small integer pre-caching is described somewhere in the C API docs.) From fredrik at pythonware.com Fri Aug 15 13:58:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 15 Aug 2008 19:58:51 +0200 Subject: negative numbers are not equal... In-Reply-To: References: Message-ID: castironpi wrote: > This case actually misses handleC(). The solution is that the > function that is returning '-10' cannot return -10, it has to return > flagC. This can cause difficulties in cases when you're doing > operations on flags. Worse, if flagC is nested somewhere, say > moduleA.classB.flagC, you still have to work with that, not its value. do you *ever* make any sense at all? From news1234 at free.fr Wed Aug 13 17:22:31 2008 From: news1234 at free.fr (nntpman68) Date: Wed, 13 Aug 2008 23:22:31 +0200 Subject: How to execute commands in internal zones of solaris using python running from the global zone ? In-Reply-To: <48a29165$0$7602$426a34cc@news.free.fr> References: <425e481f-95ce-42a6-aaf6-1f42a3fe7239@w39g2000prb.googlegroups.com> <48a29165$0$7602$426a34cc@news.free.fr> Message-ID: <48a35097$0$17491$426a74cc@news.free.fr> > Hishaam wrote: >> How to execute commands in internal zones of solaris using python >> running from the global zone ? >> >> i tried -- >> 1> os.popen("zlogin ") >> 2> os.popen("zonename") >> >> the 2nd command executes back into the global zone and not into the >> internal zone >> can anyone help? Hmm, I was't reading enough. popen2 can be imported with popen2 the more modern alternative to popen seems to be subprocess.Popen http://docs.python.org/lib/node539.html And here a short example: #!/bin/env python import sys import os import popen2 # default host / command host="zone1" command='uname -n' # host / command via command line # didn't have time to check whether # shifting sys.argv is a common practice if(len(sys.argv) > 1): host=sys.argv[1] if(len(sys.argv) > 2): command=sys.argv[2] # ============== solution 1 ============ # just passing command to command line of ssh / rsh / zlogin pipe_in = os.popen('ssh ' + host + ' ' + command) a = pipe_in.read() print 'Result of solution 1',a # a minor variation of solution 1 would be the next line # in ssh the switch -T disables tty allocation and gets rid of a warning' #pipe_in = os.popen('echo '+command+' | ssh -T' + host) # =========== solution 2 ================= # using popen2 # if you do a little more than one command this might # be prone to dead locks # for more complex cases it's probably better # to use one thread for sending the commands and one thread for # collecting the responses # # if you want to see the warning remove it ;-_ [ z1_stdout , z1_stdin ] = popen2.popen2('ssh -T '+host) z1_stdin.write(command + '\n') z1_stdin.close() a = z1_stdout.read() print "Result of solution 2 is: ",a nntpman68 wrote: >> >> >> Hishaam > > > Very probably you didn't want to start two pipes (two processes on your > host) > > > > Can you ssh or rsh to zone 1? > > Then you want probably something like: > > os.popen('echo zonename | ssh ') > > > If not you could look at pexpect, though I didn't use it myself so far. > just look at the thread 'SSH utility' to get some examples. > you just had to replace 'ssh' with 'zlogin' > > ( http://www.noah.org/wiki/Pexpect ) > > > > Or you could try popen2, http://docs.python.org/lib/module-popen2.html > > Strange thing is though, that popen doesn't seem to exist on my python. > Perhaps it's not a standard library. > No idea. I myself am rather new to python :-( > > > However if you want to try popen2 read also 17.4.2 'Flow Control Issues' > in order to be sure, that your program doesn't deadlock > > > > [ z1_stdin , z1_stdout ] = os.popen2('ssh z1_stdin.write('zonename\n') > z1_stdout.readline() > > > bye N > > > From maric at aristote.info Sat Aug 2 02:28:28 2008 From: maric at aristote.info (Maric Michaud) Date: Sat, 2 Aug 2008 08:28:28 +0200 Subject: simple error i hope In-Reply-To: <1217631110.30810.11.camel@generator> References: <44e9dc820808011308k728e5702wdfcb465c01339156@mail.gmail.com> <1217631110.30810.11.camel@generator> Message-ID: <200808020828.28854.maric@aristote.info> Le Saturday 02 August 2008 00:51:50 Clay Hobbs, vous avez ?crit?: > It is also a good idea to open files with the open() function and not the > file() function. ?They do the exact same thing, and take the exact same > parameters, just open() makes your code a bit more readable (or at least > that's what I think). The main point with open I think is to easy later evolution. While you could override "file" name as well as "open" by a custom funcion, it's a bad idea to override the name of the type because a simple isinstance(file_, file) won't work anymore if you do so. -- _____________ Maric Michaud From fredrik at pythonware.com Sat Aug 30 13:21:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 30 Aug 2008 19:21:58 +0200 Subject: Which is faster? In-Reply-To: References: Message-ID: Lie wrote: >> how does doing something twice not change complexity? yes it maybe >> belongs to the same complexity-class but is still twice as slow no? > > Who is doing something twice? Definitely not sum(). nobody's claiming that -- but as mentioned above, even if sum() had done two passes over the source sequence, it'd still be O(n). From notvalid2 at sbcglobal.net Wed Aug 27 05:10:18 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Wed, 27 Aug 2008 02:10:18 -0700 Subject: Date Comparison and Manipulation Functions? In-Reply-To: References: <6cdf0c14-80b6-42c4-8047-8c01fda8b87c@r15g2000prh.googlegroups.com> Message-ID: <9U8tk.19080$cW3.13729@nlpi064.nbdc.sbc.com> John Machin wrote: > On Aug 27, 11:24 am, "W. eWatson" wrote: >> John Machin wrote: >>> On Aug 27, 10:21 am, "W. eWatson" wrote: >>>> I'm using IDLE for Python 2.4, and put pfydate distribution in >>>> C:\Python24\Lib\site-packages\pfydate, as required by the >>>> page. >>>> How to install pyfdate. >>>> Save pyfdate.py into your PythonNN/Lib/site-packages directory. >>>> I copied it into C:\Python24\Lib\site-packages\pfydate >>> If that means that you ended up with >>> C:\Python24\Lib\site-packages\pfydate\pyfdate.py >>> then you have *not* followed the instructions "Save pyfdate.py into >>> your PythonNN/Lib/site-packages directory". >>> You need to end up with >>> C:\Python24\Lib\site-packages\pyfdate.py >> None of the folders in C:\Python24\Lib\site-packages\ have py as a suffix >> (as seen either by the IDLE path browser or XP). My folder is exactly >> C:\Python24\Lib\site-packages\pfydate in XP and it contains about 12 py files. >> There are exactly three folders under >> C:\Python24\Lib\site-packages\ according to the IDLE path browser. This does >> not agree with XP, which has: >> Numeric >> pfydate >> scipy >> numpy >> PIL > > (1) "pfydate" != "pyfdate" typo > (2) The instructions say to put pyfdate.py [that's *ONE* file, not 12 > files] in the ..../site-packages folder, *not* a sub-folder > Got it. Ah, I see upon closer inspection the other files are just international versions. Thanks. It works. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From kyosohma at gmail.com Thu Aug 7 16:07:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 7 Aug 2008 13:07:13 -0700 (PDT) Subject: os.system question References: <1c5bf$489a4add$4275d90a$15022@FUSE.NET> Message-ID: On Aug 6, 8:07?pm, Kevin Walzer wrote: > ?>>> import os > ?>>> foo = os.system('whoami') > kevin > ?>>> print foo > 0 > ?>>> > > The standard output of the system command 'whoami' is my login name. Yet > the value of the 'foo' object is '0,' not 'kevin.' How can I get the > value of 'kevin' associated with foo? > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com Just an FYI, the os.system, commands, and os.popen* stuff is deprecated in Python 2.4+. The subprocess module is supposed to replace them all. See the docs for more info: http://docs.python.org/lib/module-subprocess.html I think the equivalent is subprocess.Popen with the communicate() method: http://docs.python.org/lib/node532.html HTH Mike From haxier at gmail.com Mon Aug 11 05:26:35 2008 From: haxier at gmail.com (haxier) Date: Mon, 11 Aug 2008 02:26:35 -0700 (PDT) Subject: Digitally sign PDF files Message-ID: <3d9825dc-be85-4fe5-98fa-979090830ea7@34g2000hsh.googlegroups.com> Hi all I'm developing an application with some reports and we're looking for advice. This reports should be openoffice.org .odf files, pdf files, and perhaps microsoft word files (.doc, .docx?) and must be digitally signed. Is out there some kind of libraries to ease this tasks? * Access to the local user certificate store, and read PEM or PKCS12 certificate files. * Read, parse and validate user certificates * Sign documents: as a binary stream, within an specific document (pdf, odt, doc) I've been googling and found very few documentation about this -- except some examples using jython and ironpython. Thanks From bj_666 at gmx.net Thu Aug 21 01:11:13 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Aug 2008 05:11:13 GMT Subject: Get parameters from the URL References: Message-ID: <6h4bnhFishf5U1@mid.uni-berlin.de> On Thu, 21 Aug 2008 10:04:35 +0530, Sohrab Pawar wrote: > I'm a python noob so don't be mean :) I have a URL like > http://mySite.net?userID=398&age=28 I'm trying to create a new python > script that is called when a user click a button "Redirect". When a user > clicks the "Redirect" button, I want to send the user to either of the 2 > pages, depending on the age of the user (sent as a parameter using the > URL). > > What is the best way to > 1. Read the URL and get the parameters (age=28 in this case) 2. Redirect > the the user accordingly > > I have done this kind of thing in a jsp/servlet environment but I have > no idea how to proceed in the Python world. If you really got that string you can use the modules `urlparse` and `cgi` to get the query part: In [48]: url = 'http://mySite.net?userID=398&age=28' In [49]: urlparse.urlparse(url) Out[49]: ('http', 'mySite.net', '', '', 'userID=398&age=28', '') In [50]: cgi.parse_qs(urlparse.urlparse(url)[4]) Out[50]: {'age': ['28'], 'userID': ['398']} But maybe you should read about the `cgi` module and how to use it. Ciao, Marc 'BlackJack' Rintsch From fabio.oikawa at gmail.com Fri Aug 1 11:45:18 2008 From: fabio.oikawa at gmail.com (Fabio Oikawa) Date: Fri, 1 Aug 2008 12:45:18 -0300 Subject: Python Written in C? In-Reply-To: References: <8d3752f20807202258w2a4167e4hd40b56b12c0c74fc@mail.gmail.com> Message-ID: <47e3464c0808010845n70a13b0ai39296c0b626f0f45@mail.gmail.com> 2008/8/1 Tim Rowe > 2008/7/21 Krishnakant Mane : > > > First off all c# is absolute rubbish waist of time. > > What a pity others are joining in this pointless language flame-war. > > Look, I recently had to write a script for manipulating some data; I > struggled to organise it in Python and in C++, but when I tried C# > everything fell naturally into place and I had it done in next to no > time. Other times it has been Python or C++ that has been the most > natural way to express what I'm trying to do. Just because /you/ > don't like C# doesn't mean it's rubbish or a waste of time; personally > I loathe Perl, but I respect the fact that a lot of programmers can > get good results very quickly in it. > > I reckon that the programmer who only knows one language is like a > carpenter trying to make a cabinet with just a chisel. Ok for making > the joints (although a hammer would have been handy to hit it with), > not /really/ as good as a plane for getting large areas smooth, and > the blade keeps jumping out when you try to use it as a screwdriver... > > The one-language programmer isn't really in a position to choose the > right tool for the job, because they only have one tool. Anybody who > says that a language in real use is a waste of time is denying the > reality of those who find it an effective tool. Similarly, anybody who > says that a language -- any language -- is right for all jobs plainly > doesn't understand that language design involves a lot of compromises, > and that the compromises that are appropriate choices for one task are > inappropriate for another. Python is a great tool. So is C#. You /can/ > do the same job with either, but the smart move is to choose the one > that is best adapted to the task in hand. > Great, I agree! The only problem is to be so good in several languages. Generally programmers are proficient in one or two. Cheers, F?bio -------------- next part -------------- An HTML attachment was scrubbed... URL: From Josef.Robert.Novak at gmail.com Wed Aug 13 06:12:48 2008 From: Josef.Robert.Novak at gmail.com (kettle) Date: Wed, 13 Aug 2008 03:12:48 -0700 (PDT) Subject: python tr equivalent (non-ascii) References: <552ee625-5d07-4f37-958f-abe046cdff3d@v1g2000pra.googlegroups.com> Message-ID: On Aug 13, 5:33 pm, Fredrik Lundh wrote: > kettle wrote: > > I was wondering how I ought to be handling character range > > translations in python. > > > What I want to do is translate fullwidth numbers and roman alphabet > > characters into their halfwidth ascii equivalents. > > In perl I can do this pretty easily with tr: > > > tr/\x{ff00}-\x{ff5e}/\x{0020}-\x{007e}/; > > > and I think the string.translate method is what I need to use to > > achieve the equivalent in python. Unfortunately the maktrans method > > doesn't seem to accept character ranges and I'm also having trouble > > with it's interpretation of length. What I came up with was to first > > fudge the ranges: > > > my_test_string = u"???????" > > f_range = "".join([unichr(x) for x in > > range(ord(u"\uff00"),ord(u"\uff5e"))]) > > t_range = "".join([unichr(x) for x in > > range(ord(u"\u0020"),ord(u"\u007e"))]) > > > then use these as input to maketrans: > > my_trans_string = > > my_test_string.translate(string.maketrans(f_range,t_range)) > > Traceback (most recent call last): > > File "", line 1, in ? > > UnicodeEncodeError: 'ascii' codec can't encode characters in position > > 0-93: ordinal not in range(128) > > maketrans only works for byte strings. > > as for translate itself, it has different signatures for byte strings > and unicode strings; in the former case, it takes lookup table > represented as a 256-byte string (e.g. created by maketrans), in the > latter case, it takes a dictionary mapping from ordinals to ordinals or > unicode strings. > > something like > > lut = dict((0xff00 + ch, 0x0020 + ch) for ch in range(0x80)) > > new_string = old_string.translate(lut) > > could work (untested). > > excellent. i didnt realize from the docs that i could do that. thanks From notvalid2 at sbcglobal.net Fri Aug 29 12:32:01 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Fri, 29 Aug 2008 09:32:01 -0700 Subject: Date Comparison and Manipulation Functions? In-Reply-To: <9U8tk.19080$cW3.13729@nlpi064.nbdc.sbc.com> References: <6cdf0c14-80b6-42c4-8047-8c01fda8b87c@r15g2000prh.googlegroups.com> <9U8tk.19080$cW3.13729@nlpi064.nbdc.sbc.com> Message-ID: <8AVtk.8079$np7.5970@flpi149.ffdc.sbc.com> I just tried the following code, and got an unexpected result. from pyfdate import * t = Time() ts = Time(2008, 8, 29,15,20,7) tnew = ts.plus(months=6) print "new date: ", tnew Result: new date: 2009-02-28 15:20:07 I believe that should be April 1, 2009. If I use months = 1 and day =31, I get Sept. 30, 2008 and not Oct. 1, 2008. Is there a way to get around this? -- W. Watson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet From stefan_ml at behnel.de Fri Aug 8 10:38:14 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 08 Aug 2008 16:38:14 +0200 Subject: how to find out if an object is a class? In-Reply-To: References: <871w105qs3.fsf@benfinney.id.au> <489be85f$0$12954$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <489c5a56$0$1077$9b4e6d93@newsspool3.arcor-online.net> Miles wrote: > On Fri, Aug 8, 2008 at 2:31 AM, Stefan Behnel wrote: >> I recently had the reverse case that a (stupidly implemented) extension module >> required a callback function and I wanted to pass a function wrapped in a >> wrapper object. That failed, because it specifically checked for the argument >> being a function, not just a callable object. I had to pull quite a number of >> tricks to reimplement the wrapper class as a function (thank god, it's Python!). > > You really only needed one trick: > > def functionize(callable): > return lambda *args, **kwargs: callable(*args, **kwargs) Congratulations, you found the trivial case. Stefan From dudeja.rajat at gmail.com Mon Aug 25 09:00:31 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 25 Aug 2008 14:00:31 +0100 Subject: Tkinter - How to create combo box using Tix with the existing Tkinter widgets/ In-Reply-To: References: Message-ID: On Mon, Aug 25, 2008 at 12:57 PM, wrote: > Hi, > > I'm using Tkinter module to create a GUI application. I found that the > combo box is not present in Tkinter module. > It comes with Tix module. Could some one give me an example to create > a combo box whilst using Tix and Tkinter? > > I've been using the following to create my tkinter widgets: > myRoot = Tk() > > and in my Gui code, I've been using > self.lbAnalysisLib = Listbox(master, \ > yscrollcommand = self.vsbAnalysisLib.set,\ > height = 1, > width = 30) > > Please suggest how could I call the Tix's combo box from my existing > GUI application that heavily uses the Tkinter widgets? > Kindly provide me some code examples. > > Thanks and regards, > Rajat > Ok...now I found the way to do that. But I'm stuck further. my code is as below: main module ********************** myRoot = Tix.Tk() myAppGUIObject = myAppGUI(myRoot) Gui module **************** class myAppGUI: def __init__(self, master): self.cbAnalysisLib = Tix.ComboBox(master, label = "Analysis Library:") self.cbAnalysisLib.grid(row = 3, column = 1, padx = 30, pady = 30, sticky = W) self.cbAnalysisLib.config(editable = 0) self.cbAnalysisLibVersion = Tix.ComboBox(master, label = "Reference Analysis Library Version:", \ labelside = 'left') self.cbAnalysisLibVersion.grid(row = 5, column = 1, padx = 30, pady = 30, sticky = W) self.cbAnalysisLibVersion.config(editable = 0) The problem is that the labelside option is not working. I'm not able to use even the wraptext option. -- Regrads, Rajat From cromulent at justextrememetal.com Mon Aug 11 11:58:00 2008 From: cromulent at justextrememetal.com (Cromulent) Date: Mon, 11 Aug 2008 16:58:00 +0100 Subject: Problems returning data from embedded Python Message-ID: <2008081116580016807-cromulent@justextrememetalcom> Okay I'm having a few issues with this and I can't seem to get it sorted out (most likely due to my inexperience with Python). Here is my Python code: def fileInput(): data = [] s = raw_input("Please enter the filename to process (enter full path if not in current directory): ") fd = open(s, "r") fd.readline() line = fd.readlines() for record in line: record = record.strip() items = record.split(',') for i in range(1, 5): items[i] = float(items[i]) items[5] = int(items[5]) data.append(items) fd.close() return items It works perfectly and does exactly what I want it to do. The problem comes when I try and convert the data I returned from the Python script and turn it into something useable in C. I have no idea. The C functions that seem most use deal with Tuples, when this is a list and I can't see any specific functions for dealing with lists in the C API. Can anyone give me some pointers in the right direction at all please? I know the C program has received the data correctly, I just need to put it in C types. Thank you. -- "I disapprove of what you say, but I'll defend to the death your right to say it." - Voltaire From bdesth.quelquechose at free.quelquepart.fr Wed Aug 27 12:52:18 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 27 Aug 2008 18:52:18 +0200 Subject: exception handling in complex Python programs In-Reply-To: References: <00bb4e2f$0$20315$c3e8da3@news.astraweb.com> <8cb19b0b-1df8-4c5b-b546-a273c6fbc2e3@j1g2000prb.googlegroups.com> <00bc565e$0$20315$c3e8da3@news.astraweb.com> Message-ID: <48b5a232$0$10445$426a74cc@news.free.fr> Lie a ?crit : > On Aug 21, 12:59 am, Steven D'Aprano cybersource.com.au> wrote: >> On Wed, 20 Aug 2008 09:23:22 -0700, dbpoko... at gmail.com wrote: >>> On Aug 19, 4:12 pm, Steven D'Aprano >> cybersource.com.au> wrote: >>>> On Tue, 19 Aug 2008 11:07:39 -0700, dbpoko... at gmail.com wrote: >>>>> def do_something(filename): >>>>> if not os.access(filename,os.R_OK): >>>>> return err(...) >>>>> f = open(filename) >>>>> ... >>>> You're running on a multitasking modern machine, right? What happens >>>> when some other process deletes filename, or changes its permissions, >>>> in the time after you check for access but before you actually open it? >>> This is a good point - if you want to use the correct way of opening >>> files, and >>> you don't want to worry about tracking down exception types, then we can >>> probably >>> agree that the following is the simplest, easiest-to-remember way: >>> def do_something(filename): >>> try: >>> f = open(filename) >>> except: >>> >> No, we don't agree that that is the correct way of opening files. Simple >> it might be, but correct it is not. >> >> If you're using Python 2.6 or greater, then you should be using a with >> block to handle file opening. >> >> And regardless of which version of Python, you shouldn't use a bare >> except. It will mask exceptions you *don't* want to catch, including >> programming errors, typos and keyboard interrupts. >> >>> Opening files is a special case where EAFP is the only correct solution >>> (AFAIK). I still liberally sprinkle LBYL-style "assert isinstance(...)" >> Oh goodie. Another programmer who goes out of his way to make it hard for >> other programmers, by destroying duck-typing. >> >> BTW, assertions aren't meant for checking data, because assertions can be >> turned off. Outside of test frameworks (e.g. unit tests), assertions are >> meant for verifying program logic: >> >> def foo(x): >> # This is bad, because it can be turned off at runtime, >> # destroying your argument checking. >> assert isinstance(x, int) >> # And it raises the wrong sort of exception. >> >> # This is better (but not as good as duck-typing). >> if not isinstance(x, int): >> raise TypeError('x not an int') >> # And it raises the right sort of error. >> >> y = some_function(x) >> # y should now be between -1 and 1. >> assert -1 < y < 1 >> do_something_with(y) >> >>> and other similar assertions in routines. The point is that EAFP >>> conflicts with the interest of reporting errors as soon as possible >> Not necessarily. Tell me how this conflicts with reporting errors as soon >> as possible: >> >> def do_something(filename): >> try: >> f = open(filename) >> except IOError, e: >> report_exception(e) # use a GUI, log to a file, whatever... >> >> How could you report the exception any earlier than immediately? > > I'm sure different people would have different view on what > immediately means. The LBYL supporters define immediately as > immediately after a definite potential problem is detected (by ifs or > assertion), while the EAFP supporters define immediately as > immediately after a problem arises. No side is right or wrong, both > have weakness and strength, but python-style programs are encouraged > to use EAFP-style exception handling whenever feasible, but with the > spirit of the Zen: "Special cases aren't special enough to break the > rules, although practicality beats purity", if LBYL makes things much > easier in that case, and doing EAFP would just convolute the code, > then practicality beats purity. > Hear hear... From bedouglas at earthlink.net Sun Aug 17 17:35:34 2008 From: bedouglas at earthlink.net (bruce) Date: Sun, 17 Aug 2008 14:35:34 -0700 Subject: list/tuple/dict question In-Reply-To: Message-ID: <005b01c900b1$2f1693f0$0301a8c0@tmesa.com> Hi Fredrik... so, this still doesn't get me an array called 'cat', or 'dog' or do i somehow use stuff to add/extract the vals...??? thanks -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Fredrik Lundh Sent: Sunday, August 17, 2008 2:27 PM To: python-list at python.org Subject: Re: list/tuple/dict question bruce wrote: > a dict doesn't seem to work, as it is essentially a series of key/values, > which isn't exactly what i want... so what do you think a variable namespace is? as usual, Python works best if you use it to write Python program, and in Python, the right way to store a collection of name/value pairs is to use a dictionary: stuff = {} foo = [] foo.append('cat') foo.append('dog') stuff[foo[1]] = [] -- http://mail.python.org/mailman/listinfo/python-list From kyosohma at gmail.com Fri Aug 8 13:49:11 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 8 Aug 2008 10:49:11 -0700 (PDT) Subject: small issue with Idle References: <2c192ba3-bc94-4f55-9d59-0fe14b8069a0@z6g2000pre.googlegroups.com> Message-ID: On Aug 8, 9:41?am, v4vijayakumar wrote: > When you press 'home' button cursor goes before >>> prompt. This is > little uncomfortable. > > I am using Idle 1.2.2. (python 2.5.2.) There's a free version of Wing IDE that has an IDLE-like interface that doesn't have this issue...or you could just use the command line version of IDLE. Mike From Levon.Ghazaryan at gmail.com Mon Aug 25 16:54:59 2008 From: Levon.Ghazaryan at gmail.com (~levon) Date: Mon, 25 Aug 2008 13:54:59 -0700 (PDT) Subject: signal and threading References: <78b957b0-3a29-45ba-9c7e-d8934c900127@i76g2000hsf.googlegroups.com> Message-ID: this seems to be the solution: http://code.activestate.com/recipes/496735/ On Aug 25, 3:37?pm, "~levon" wrote: > Hello group, > > in following example, a signal handler is registered and a thread > started. if I call self.doSomethin() directly > the code works as I would expect. as i send a SIGINT shutdown is > called and the script terminates. > > as soon as I call doSomething() in a thread the the SIGINT handler is > never called again and > i have to terminate the script with a SIGTERM or SIGKILL. > > well, i would expect the handler to be called in both cases, am i > missing something? > > by the way. calling os.kill(os.getpid(), signal.SIGINT) works as I > would expect, what > don't is kill -s SIGINT pid # where pid is the actual process id > > the code: > > class Runner(object): > ? ? def __init__(self): > ? ? ? ? print os.getpid() > ? ? ? ? self.shd = False > ? ? ? ? signal.signal(signal.SIGINT, self.shutdown) > ? ? ? ? threading.Thread(target=self.doSomething).start() > ? ? ? ? # the following works fine: > ? ? ? ? #os.kill(os.getpid(), signal.SIGINT) > > ? ? def doSomething(self): > ? ? ? ? while not self.shd: > ? ? ? ? ? ? pass > > ? ? def shutdown(self, signo, frm): > ? ? ? ? self.shd = True > > if __name__ == '__main__': > ? ? Runner() > > ~levon From marco.bizzarri at gmail.com Sat Aug 30 13:28:53 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 30 Aug 2008 19:28:53 +0200 Subject: Advice on the style to use in imports In-Reply-To: References: <3f0d61c40808300512x1dcd5061t19ad7323b7ef15e9@mail.gmail.com> Message-ID: <3f0d61c40808301028teb64a72ibcd65f9b946de915@mail.gmail.com> Hi bearophile On Sat, Aug 30, 2008 at 4:04 PM, wrote: > > from somemodule import somename > > is often acceptable IHMO, but there are some things to consider: > - you and the person that reads your code have to remember where > somename comes from. So you can do it for well known names like izip > or imap, but if you import lots of names from lots of modules, things > may become too much complex. So often it can be better to import just > the modules, and use somemodule.somename. Yes, that's true; but when I see that I need so many symbols from another module, I take that as an hint that either my module is doing too many things, and it should be splitted, or it is tightly coupled to that module... actually, being forced to write all the imports in that way was a tool into inspecting the dependencies in our project. > - somemodule.somename is longer to write and to read, and if it's > repeated many times it may worsen the program readability, making > lines of code and expressions too much long and heavy. So you have to > use your brain (this means that you may have to avoid standard > solutions). Note that you can use a compromise, shortening the module > name like this: > import somemodule as sm > Then you can use: > sm.somename it is not a problem to have special cases, as long as they are "special"; I'm looking for more or less accepted solutions; of course any project has some area where it is better to follow readability over standards; I'm just trying to understand the standards, then I will deviate from them. I feel like I'm learning to drive: first I learn the rules, then I learn the exceptions ;) > - somemodule.somename requires an extra lookup, so in long tight loops The slowdown was what in the first place made me import all the names directly; but I'm not afraid too much from that, right now. > (if you don't use Psyco) it slows down the code. This can be solved > locally, assigning a local name into a function/method (or even in > their argument list, but that's a hack to be used only once in a > while): > localname = somemodule.somename > > Bye, > bearophile > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks again for sharing your thoughts with me, bearophile. -- Marco Bizzarri http://iliveinpisa.blogspot.com/ http://notenotturne.blogspot.com/ From Edwin.Madari at VerizonWireless.com Wed Aug 13 22:28:18 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Wed, 13 Aug 2008 22:28:18 -0400 Subject: Random Problems In-Reply-To: Message-ID: <20080814022928.D699B1E4005@bag.python.org> use songs.extend( asongs ) #append is for single item - where ever it might be. >>> l1 = range(5) >>> l2 = range(5,10) >>> l1 [0, 1, 2, 3, 4] >>> l2 [5, 6, 7, 8, 9] >>> l1.extend(l2) >>> l1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> good luck. Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of Cousin Stanley Sent: Wednesday, August 13, 2008 10:19 PM To: python-list at python.org Subject: Re: Random Problems > Well the othe day I was making a program to make a list > of all the songs in certian directorys but I got a problem, > only one of the directorys was added to the list. > .... > Here's some code .... that illustrates yours .... import glob songs = glob.glob( '/path/to/somewhere/*.mp3' ) asongs = glob.glob( 'path/to/somewhere/else/*.mp3' ) songs.append( asongs ) # repeat a few times appending lists from other dirs > all goes well but pick awalys is from the first directory > but songs awalys includes all the files I want it to. songs.append( asongs ) is appending the entire asongs list as a single item to the end of the songs list, not adding each individual song as an entry .... For example .... >>> l1 = range( 0 , 5 ) >>> l2 = range( 5 , 10 ) >>> l3 = range( 11 , 15 ) >>> >>> l1 [0, 1, 2, 3, 4] >>> >>> l2 [5, 6, 7, 8, 9] >>> >>> l3 [11, 12, 13, 14] >>> >>> l1.append( l2 ) >>> >>> l1 [0, 1, 2, 3, 4, [5, 6, 7, 8, 9]] >>> >>> l1.append( l3 ) >>> >>> l1 [0, 1, 2, 3, 4, [5, 6, 7, 8, 9], [11, 12, 13, 14]] So, if you have a lot of entries in the original songs list you're only adding a few entries to it in the form of another list and most likely you didn't run enough random.choice tests to flush out a pick that turned out to be one of the entire asong lists that you added .... You might try something like the following where each tune gets added individually to the song pool .... un-tested .... # ------------------------------------------------------------------- import random import glob base_dir = 'c:/Documents and Settings/Admin/My Documents' list_subdirs = [ 'LimeWire/Saved/*.mp3' , 'Downloads/*/*.mp3' , 'Downloads/*/*/*.mp3' , 'Downloads/*/*/*/*.mp3 ] song_pool = [ ] for this_dir in list_subdirs : list_songs = glob.glob( "'%s/%s'" % ( base_dir , this_dir ) if list_songs : for this_song in list_songs : song_pool.append( this_song ) npicks = 41 print for n in range( npicks ) : this_pick = random.choice( song_pool ) print ' ' , this_pick # ------------------------------------------------------------------- -- Stanley C. Kitching Human Being Phoenix, Arizona -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From cbabcock at kolonelpanic.org Sat Aug 30 23:59:04 2008 From: cbabcock at kolonelpanic.org (Chris Babcock) Date: Sat, 30 Aug 2008 20:59:04 -0700 Subject: Mako --> Genshi Message-ID: <20080830205904.725f1bef@mail.asciiking.com> Is there a cheap way to convert Myghty/Mako templates to Kid/Genshi? There's some code written for Pylons that I want to incorporate into a TurboGears 2 project and Genshi templates are more likely to behave themselves with the tools I'm used to. Chris From frank at chagford.com Sat Aug 30 01:25:28 2008 From: frank at chagford.com (Frank Millman) Date: Fri, 29 Aug 2008 22:25:28 -0700 (PDT) Subject: Ensure only single application instance. References: Message-ID: On Aug 29, 11:25?pm, Uberman wrote: > On Fri, Aug 29, 2008 at 6:51 AM, Heston James wrote: > > Good afternoon all. > > > I have an application/script which is launched by crontab on a regular > > basis. I need an effective and accurate way to ensure that only one instance > > of the script is running at any one time. > The following is taken from the getmail FAQ - ------------------------------------------ If you need to prevent two instances of getmail from running simultaneously, use any standard Unix method of providing a mutex for this purpose. One example would be to run getmail under a program like setlock (part of the daemontools package). Change your script or crontab file to invoke getmail like this: /path/to/setlock -n /path/to/lockfile /path/to/getmail [getmail options] There are other programs that provide functionality similar to setlock. ------------------------------------------ HTH Frank Millman From fredrik at pythonware.com Sun Aug 17 16:56:20 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 17 Aug 2008 22:56:20 +0200 Subject: python-mode errors In-Reply-To: References: Message-ID: Rustom Mody wrote: > When I start python mode I get the error: > > idle error: # -Wrong number of arguments : # set-match-data> 2" > > The Python mode version is 4.78 > > Is this a known problem? there are plenty of google hits for that message, and they all seem to agree that the problem is caused by using ELC files generated for a newer emacs with an older version. try loading the EL file to see if the problem goes away. From dudeja.rajat at gmail.com Sat Aug 30 09:51:40 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 30 Aug 2008 14:51:40 +0100 Subject: How to delete elements from Tix Combo Box? In-Reply-To: References: Message-ID: On Sat, Aug 30, 2008 at 2:32 PM, Fredrik Lundh wrote: > dudeja.rajat at gmail.com wrote: > >> I'm using a Tix combo box (I call it combo2), the contents of which >> are loaded depeding on the selection in another Tix combo box(I call >> it combo1) >> I have used the commands: >> >> self.cbAnalysisLibVersion.insert(END, results) >> >> to insert elements to the combo box. >> >> I'm looking for some similar option to delete elements from the combo >> box. I mean, as soon as I change selection in >> combo1 the previous elements in the combo2 should get cleared up( or >> deleted) and | shall be able to the above insert command to add new >> elements to the combo2 ( depending upon selection in combo1) >> >> Please suggest how can I clear up the ( delete the entries) in combo2. > > no time to test this, but iirc, the combobox content is held in an ordinary > listbox widget, so you should be able to use the subwidget method to fetch > that widget, and then use ordinary listbox methods to change the content. > Something like this: > > lb = w.subwidget("listbox") > lb.delete(0, END) # delete all items > > > > -- > http://mail.python.org/mailman/listinfo/python-list > Fredrik, Thanks so much. That worked. Following this, I can now see that my combo2 has no previous elements and contains only the elements relevant to selection in combo1. Now, as soon as I select something in combo 2 and go back to change selection in combo1 the combo2 must get its history cleared up (i.e the previous selection in combo2's entry subwidget) I used the command before I delete the entires : self.combo2.config(history = False) But this does not seem to be working; Here is my code snippet: **************** Inside the callback function of combo1: for libName, libResults in self.__libVerDict.items(): if libName == selectedLibName: #Get the list of labelled results resultsVer = self.__libVerDict[libName] self.combo2.config(state = NORMAL) self.combo2.config(history = False) #Delete the previous entries from the listbox #subwidget of combo box subLB = self.combo2.subwidget("listbox") subLB.delete(0, END) #Add the results to the combo box for results in resultsVer: self.combo2.insert(END, results) -- Regards, Rajat From invalid at invalid.invalid Sun Aug 10 14:13:31 2008 From: invalid at invalid.invalid (WP) Date: Sun, 10 Aug 2008 20:13:31 +0200 Subject: My very first python program, need help In-Reply-To: References: <6g8a56FenevdU1@mid.individual.net> Message-ID: <6g8pecFerglbU1@mid.individual.net> Wojtek Walczak wrote: [snip] Thanks for all your help. I've incorporated your suggestions and moved on to my next program. See new thread. :) - Eric (WP) From castironpi at gmail.com Mon Aug 4 15:15:01 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 4 Aug 2008 12:15:01 -0700 (PDT) Subject: custom allocation and custom type Message-ID: Hi all, I am trying to create a custom tuple type. I want it to live in a custom memory region, which will be a memory-mapped file. Its contents cannot be PyObject*. They have to be offsets into mapped memory. GetItem( i ) would return: (PyObject *)( t->ob_item[ i ]+ mmap_base_addr ); In the constructor, each item x would be stored as: BYTE* x_offset= x- mmap_base_addr; t->ob_item[ 0 ]= x_offset; For starters, only ints, strings, and other tuples will be members. I'll work out the list type and user-defined classes at a later time. Each will be required to be already existing in the mmap; that is, be of custom types too. I had partial success with strings and ints just memcpy-ing the entire PyObject structure. They are easier because they are immutable, and don't contain references. That's why tuple is my next step: it's immutable, but can contain references. I want to back up a step and ask some questions about ints first. What worries are there in memcpy-ing a PyIntObject? Would it be better to compile my own MmapIntObject? I do Py_INCREF on the object I return, to ensure it lives on, but I am getting an occasional crash on exit. What did I miss? Do I need to readjust the ob_type pointer every time I load the module (and lock for exclusive access)? Does Python try to free the memory when it exits? For the tuples, is there any way I can reuse the tuple code? The constructor uses a custom pool for speed which I'd probably eliminate, for the time. Slices would have to be MmapTupleObject instances too. Should I also create MmapTupleIterObject? PyObject_GC_New and PyObject_GC_NewVar are confusing. I can't follow them to the actual call to 'malloc', since they themselves lead around Python's custom memory pool. What steps do I need to be sure to take in my own? I'm having trouble building PerstTupleObject.c (persistent tuple object) to try it out. I'm using MinGW on WinXP. I added #include "persttupleobject.h" to the top of "persttupleobject.c" already, but it's a duplicate otherwise, with the name replaced. --- C>c:/programs/mingw/bin/g++ persttupleobject.c -c -Ic:/programs/ python25/include persttupleobject.c:650: warning: 'PyPerstTuple_Type' defined locally after being referenced with dllimport linkage C>c:/programs/mingw/bin/g++ -shared persttupleobject.o -o persttupleobject.pyd -L c:/programs/python25/libs -lpython25 persttupleobject.o(.text+0xce):persttupleobject.c: undefined reference to `_imp_ _PyPerstTuple_Type' persttupleobject.o(.text+0x15c):persttupleobject.c: undefined reference to `_PyG C_generation0' [snip] --- I get some of the same errors when compiling tupleobject.c from the Python-2.5.2 distribution: C>c:/programs/mingw/bin/g++ tupleobject.c -c -Ic:/programs/python25/ include tupleobject.c:649: warning: 'PyTuple_Type' defined locally after being reference d with dllimport linkage C>c:/programs/mingw/bin/g++ -shared tupleobject.o -o tupleobject.pyd - Lc:/progra ms/python25/libs -lpython25 c:/programs/python25/libs/libpython25.a(dcbbs00622.o)(.text+0x0): multiple defin ition of `PyTuple_Type' tupleobject.o(.data+0x140):tupleobject.c: first defined here tupleobject.o(.text+0x15c):tupleobject.c: undefined reference to `_PyGC_generati on0' [snip] --- Thanks in advance. From sjmachin at lexicon.net Wed Aug 27 04:03:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 27 Aug 2008 01:03:34 -0700 (PDT) Subject: Date Comparison and Manipulation Functions? References: <6cdf0c14-80b6-42c4-8047-8c01fda8b87c@r15g2000prh.googlegroups.com> Message-ID: On Aug 27, 11:24?am, "W. eWatson" wrote: > John Machin wrote: > > On Aug 27, 10:21 am, "W. eWatson" wrote: > >> I'm using IDLE for Python 2.4, and put pfydate distribution in > >> C:\Python24\Lib\site-packages\pfydate, as required by the > >> page. > >> How to install pyfdate. > > >> ? ? ?Save pyfdate.py into your PythonNN/Lib/site-packages directory. > >> I copied it into C:\Python24\Lib\site-packages\pfydate > > > If that means that you ended up with > > ? ?C:\Python24\Lib\site-packages\pfydate\pyfdate.py > > then you have *not* followed the instructions "Save pyfdate.py into > > your PythonNN/Lib/site-packages directory". > > You need to end up with > > ? ?C:\Python24\Lib\site-packages\pyfdate.py > > None of the folders in C:\Python24\Lib\site-packages\ have py as a suffix > (as seen either by the IDLE path browser or XP). My folder is exactly > C:\Python24\Lib\site-packages\pfydate in XP and it contains about 12 py files. > There are exactly three folders under > C:\Python24\Lib\site-packages\ according to the IDLE path browser. This does > not agree with XP, which has: > Numeric > pfydate > scipy > numpy > PIL (1) "pfydate" != "pyfdate" (2) The instructions say to put pyfdate.py [that's *ONE* file, not 12 files] in the ..../site-packages folder, *not* a sub-folder From joan.pallares at gmail.com Mon Aug 18 18:02:38 2008 From: joan.pallares at gmail.com (=?ISO-8859-1?Q?Joan_Pallar=E8s?=) Date: Tue, 19 Aug 2008 00:02:38 +0200 Subject: Python encoding Message-ID: I have problems encoding some team names. Python can't work with: ?, ?, ?..... I tried to create unicode in this two ways: self.nombreLocal = unicode(nombreLocal) self.nombreLocal = unicode(nombreLocal, 'iso-8859-1') But there is always one character that can't be encoded!! unicode doesn`t encode everything? How can I make the program to try several encoding till one work? Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From hubaghdadi at gmail.com Wed Aug 13 08:46:03 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Wed, 13 Aug 2008 05:46:03 -0700 (PDT) Subject: You advice please References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> <48a2d62b$0$3732$426a74cc@news.free.fr> Message-ID: On Aug 13, 7:40 am, Bruno Desthuilliers wrote: > ?lvaro G. Vicario a ?crit : > > > > > Hussein B escribi?: > >> The sad fact (at least to me), Ruby is getting a lot of attention > >> these days. > >> Why Python isn't getting this attention although is a much more mature > >> language and it is used by many big, big names? > >> And do I dare to say it is much more charming? > > > The opinion of a PHP developer who's playing with Python as well: > > > I've come across Python almost everywhere. Many programs I use (or I've > > evaluated) are written in Python or use it for scripting: source control > > software (Subversion, Bazaar, Mercurial), IDEs (Komodo Edit), popular > > web applications (Zope, Trac)... If you're looking for a script for > > admin tasks your search results will probably contain something in > > Python. If you want to build a Firefox extension you'll find a *.py file > > sitting around. > > > But I've never came across a Ruby app. Sure, I know Ruby exists and > > people are very enthusiastic about it (though they often mistake it with > > Ruby on Rails), but that's all. > > Redmine is a nice alternative to Trac. And Twitter is certainly a > well-known app too. (Yes, RoR apps in both cases...). > > > Ruby is popular among bloggers but I'm not sure whether it's popular > > among developers. > > Almost as much as Python, I'd say. But both languages fight for the same > niches in languages/techno ecosystem, and Python, being older, tend to > get more visibility. But Twitter is suffering from sever scaling problems, I read it maybe will be reimplemented in Java ... From kay.schluehr at gmx.net Wed Aug 13 16:49:41 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 13 Aug 2008 13:49:41 -0700 (PDT) Subject: ANN: P4D 1.2 References: <3bc040e5-738b-4176-a023-2b5e2fa0eca3@79g2000hsk.googlegroups.com> Message-ID: <2d07561f-5b1b-4506-b2a4-51c49223bc78@z72g2000hsb.googlegroups.com> On 12 Aug., 12:54, Kay Schluehr wrote: > On 12 Aug., 10:50, Uwe Grauer wrote: > > > > > Kay Schluehr wrote: > > > P4D = E4X style embedded DSL for Python but without E and X. > > > > The main feature of P4D 1.2 are *Bytelets*. While the primary purpose > > > of P4D 1.1 was the support textual data which can be considered as > > > isomorphic to XML the new release is focussed on binary data. Bytelets > > > are P4D objects that are assembled from hexcode which is reified as a > > > Hex object. Bytelets can also be serialized as Hex objects which makes > > > them apt for low level communication. Bytelets can be used to parse > > > hexcode into other Bytelets of the same structure and Bytelets can be > > > cloned like object prototypes which makes it easy to produce sequences > > > of variations of one Bytelet ( usually you do not derive from a > > > Bytelet but modify a prototype ). > > > > For more information see: > > > >http://pypi.python.org/pypi/P4D > > >http://www.fiber-space.de > > >http://www.fiber-space.de/EasyExtend/doc/p4d/bytelets.html > > > That's a really bad name for the project as there is P4D (Python for > > Delphi) already. > > Maybe try to find a different naming to help distinguish your project > > from other meanings. > > > Uwe > > Hmm... using three letter acronyms is a mess. Sorry for this > interference! > > Actually "P4D" is not used innocently in the implementation code. It's > also a file extension, a prompt, an XML namespace prefix, a class name > etc. not just a project name and I'm not going to change all this. > > I also don't think this is too critical when context has been > established but since the package is also distributed as "P4D" I'm > going to rename it into "P4D Langlet 1.3" in the next release and > adapt the URLs somewhat. I hope this helps avoiding confusion. > > Kay Done. I removed the "P4D" project from PyPI and launched "P4D Langlet" instead ( although in the version 1.2.2 not in 1.3 as mentioned above). Kay From mccredie at gmail.com Sat Aug 9 17:14:32 2008 From: mccredie at gmail.com (Matimus) Date: Sat, 9 Aug 2008 14:14:32 -0700 (PDT) Subject: Missing exceptions in PEP 3107 References: Message-ID: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> On Aug 9, 9:08?am, Christoph Zwerschke wrote: > I'm just reading PEP 3107 (function annotations) and wonder why > exceptions are not mentioned there. I think it would be helpful if one > could specify which exceptions can be raised by a function, similarly to > how it is possible in C++ using the "throw" clause. The syntax would be > something like this: > > def foo(a: expr, b: expr = 5) raises expr -> expr: > > The expr in that "raises" clause should be a list of Exceptions. > > Having the list of possible exceptions as annotation alone would be > already helpful. Of course it could be also discussed whether Python > should check that the function really raises only these exceptions (as > in C++), or we could even have checked exceptions (as in Java, but this > seems to be a controversial issue). > > Has this already been discussed, or is it in a different PEP? > > -- Christoph Keep in mind that annotations are just a way of associating some information with the parameters or a function. There is a special parameter called `return` to help associate information with the return value. Whether that information is used to describe the types of the function parameters, how they are used, or something completely different is up to the application that uses them. When you say: > The expr in that "raises" clause should be a list of Exceptions. You are clearly confusing the annotation feature with a possible application of the annotation feature. Annotation could be used for many different applications besides type safety. Annotation simply creates a dictionary. The name `return` was chosen for the return value because it _is_ a keyword and therefore could not conflict with the name of any of the parameters. Using "raises" would mean that we would have to introduce the name "raises" as a new keyword. It would be better just to use they existing keyword "raise". With all of that being said, a package or application that uses annotation could simply use the data-structure associated with "return" to also contain exception information. That might not seem intuitive, but keep in mind that the value associated with "return" in the associations dictionary is going to be a special case anyway. def foo(a: "a info", b: "b info") -> "return info", "exception info": return "hello world" Matt From sharon.kim96 at gmail.com Mon Aug 25 10:15:56 2008 From: sharon.kim96 at gmail.com (sharon k) Date: Mon, 25 Aug 2008 22:15:56 +0800 Subject: newbie question Message-ID: hi all, i am new to python. i fetch a webpage with urllib, extract a few numbers in a format as follow; 10,884 24,068 my question is how to remove the comma between the number, since i have to add them up later. sorry for my bad english. -------------- next part -------------- An HTML attachment was scrubbed... URL: From soid.exe at gmail.com Sat Aug 23 07:15:25 2008 From: soid.exe at gmail.com (Grigory Temchenko) Date: Sat, 23 Aug 2008 04:15:25 -0700 (PDT) Subject: How to know a top directory? Message-ID: <0f3ab42d-8fc8-4c23-b255-4be7235ee4ca@s20g2000prd.googlegroups.com> Hey there, Help me please. How to know a top directory? I mean I have path "/this/ is/path" and I wanna get "/this/is". Also I want to use it as platform independent. If I want to pass "c: \that\path" then I need to get "c:\that". Does anyone have ideas? From williamhpurcell at gmail.com Thu Aug 14 09:07:40 2008 From: williamhpurcell at gmail.com (William Purcell) Date: Thu, 14 Aug 2008 08:07:40 -0500 Subject: reading plist files Message-ID: Hi, I'm trying to write a bookmark synchronizer from Firefox/Foxmarks to Safari. The Firefox side of things will be fairly easy and I thought the Safari side would be too. Right now I am simply attempting to read my Bookmarks.plist file using plistlib.py. Here is my attempt to read the file along with the traceback that I get... ------------------------------------------------------------------------------------------------------------------------------------------- In [1]: import plistlib In [2]: plistlib.Plist.fromFile('Bookmarks.plist') fileobj ---> --------------------------------------------------------------------------- Traceback (most recent call last) /home/william/williamFAT/utilities/mac_projs/ in () /usr/lib/python2.5/plistlib.py in fromFile(cls, pathOrFile) 339 def fromFile(cls, pathOrFile): 340 """Deprecated. Use the readPlist() function instead.""" --> 341 rootObject = readPlist(pathOrFile) 342 plist = cls() 343 plist.update(rootObject) /usr/lib/python2.5/plistlib.py in readPlist(pathOrFile) 75 didOpen = 1 76 p = PlistParser() ---> 77 rootObject = p.parse(pathOrFile) 78 if didOpen: 79 pathOrFile.close() /usr/lib/python2.5/plistlib.py in parse(self, fileobj) 401 parser.CharacterDataHandler = self.handleData 402 print 'fileobj --->',fileobj --> 403 parser.ParseFile(fileobj) 404 return self.root 405 : not well-formed (invalid token): line 1, column 8 ------------------------------------------------------------------------------------------------------------------------------------------- Also, I can read other plist files fine such as SignaturesByAccount.plist and AddressBookMe.plist. I am trying to do this in Ubuntu with Python2.5. The xml version might also be useful... In [4]: xml.__version__ Out[4]: '0.8.4' Thanks, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From george.sakkis at gmail.com Fri Aug 22 09:52:42 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 22 Aug 2008 06:52:42 -0700 (PDT) Subject: codecs, csv issues Message-ID: <8aafd67e-6633-4371-a880-805d07089400@k37g2000hsf.googlegroups.com> I'm trying to use codecs.open() and I see two issues when I pass encoding='utf8': 1) Newlines are hardcoded to LINEFEED (ascii 10) instead of the platform-specific byte(s). import codecs f = codecs.open('tmp.txt', 'w', encoding='utf8') s = u'\u0391\u03b8\u03ae\u03bd\u03b1' print >> f, s print >> f, s f.close() This doesn't happen for the default encoding (=None). 2) csv.writer doesn't seem to work as expected when being passed a codecs object; it treats it as if encoding is ascii: import codecs, csv f = codecs.open('tmp.txt', 'w', encoding='utf8') s = u'\u0391\u03b8\u03ae\u03bd\u03b1' # this works fine print >> f, s # this doesn't csv.writer(f).writerow([s]) f.close() Traceback (most recent call last): ... csv.writer(f).writerow([s]) UnicodeEncodeError: 'ascii' codec can't encode character u'\u0391' in position 0: ordinal not in range(128) Is this the expected behavior or are these bugs ? George From cjw at ncf.ca Sun Aug 17 14:27:57 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sun, 17 Aug 2008 14:27:57 -0400 Subject: like a "for loop" for a string In-Reply-To: References: Message-ID: Alexnb wrote: > Okay, so lets say you have a list: > > funList = [1,2,3,4,5] > > and you do: > > for x in funList: > print x > > this will print 1-5 > But I am wondering is there a way to something like this: > > funString = "string string string non-string non-string string" > and > for "string" in funString: > print something > > I know you can't do that; but, is there a way do do something similar that > gets the same result? Your funString has six elements, funList has five. How do you want the result to appear on the page? It is possible that the % operator could help you. Colin W. From steve at REMOVE-THIS-cybersource.com.au Sat Aug 2 23:46:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 03 Aug 2008 03:46:33 GMT Subject: Profiling weirdness: Timer.timeit(), fibonacci and memoization References: <59994541-2fb7-450c-ac14-9922d87b6aa1@m45g2000hsb.googlegroups.com> Message-ID: <00a52572$0$20316$c3e8da3@news.astraweb.com> On Sat, 02 Aug 2008 06:02:02 -0700, ssecorp wrote: > I am not clear about the results here. > > > from timeit import Timer > import Decorators > > def fib(n): > a, b = 1, 0 > while n: > a, b, n = b, a+b, n-1 > return b [...] > s = 100 > > t1 = Timer('fib(s)', 'from __main__ import fib, s') > t2 = Timer('fibmem(s)', 'from __main__ import fibmem, s') > t1.repeat(number=1) > t2.repeat(number=1) > print t1.timeit() > print t2.timeit() > > > 35.3092010297 > 1.6516613145 > > So memoization is 20+ times faster than the idiomatic way? Or am I > missing something here? Memoization *can be* faster, not *is* -- memoization requires work, and if it is more work to look something up than to calculate it, then it will be a pessimation instead of an optimization. That's probably less of an issue with high-level languages like Python, but in low level languages you would need to start thinking about processor caches and all sorts of complications. But I digress... in Python, yes, I would expect a significant speedup with memoization. That's why people use it. > Ok for fun I added memoization to the idiomatic one: [...] > didn't think it would make a difference there but it certainly did. > > 1.59592657726 > 1.60179436213 Just curious, but why don't you show the results of the call to repeat()? It makes me uncomfortable to see somebody showing only half their output. But yes, with memoization, the lookup to find the Fibonacci number should decrease the time it takes to calculate the Fibonacci number. I'm not sure why you are surprised. Regardless of which Fibonacci algorithm you are using, the Timer object is essentially timing one million lookups, minus 100 calculations of the Fibonacci number. The 999,900 cache lookups will dominate the time, far outweighing the 100 calculations, regardless of which method of calculation you choose. That's why the results are almost identical. -- Steven From tjreedy at udel.edu Tue Aug 5 15:16:36 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 05 Aug 2008 15:16:36 -0400 Subject: Link Checking Issues - Sub domains In-Reply-To: <1e36d085-1b73-4576-ba16-dd5fa5e86519@x35g2000hsb.googlegroups.com> References: <1e36d085-1b73-4576-ba16-dd5fa5e86519@x35g2000hsb.googlegroups.com> Message-ID: rpupkin77 wrote: > Hi, > > I have written this script to run as a cron that will loop through a > text file with a list of urls. It works fine for most of the links, > however there are a number of urls which are subdomains (they are > government sites) such as http://basename.airforce.mil, these links > are always throwing 400 errors even though the site exists. Have you looked at urllib/urllib2 (urllib.request in 3.0) for checking links? If 'http://basename.airforce.mil' works typed into your browser, this from the doc for urllib.request.Request might be relevant: "headers should be a dictionary, and will be treated as if add_header() was called with each key and value as arguments. This is often used to ?spoof? the User-Agent header, which is used by a browser to identify itself ? some HTTP servers only allow requests coming from common browsers as opposed to scripts. For example, Mozilla Firefox may identify itself as "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11", while urllib?s default user agent string is "Python-urllib/2.6" (on Python 2.6)." From grflanagan at gmail.com Thu Aug 14 13:50:20 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Thu, 14 Aug 2008 19:50:20 +0200 Subject: Formatting input text file In-Reply-To: <70e8a7c3-b16e-4f3a-960a-bf83f89563f0@d77g2000hsb.googlegroups.com> References: <70e8a7c3-b16e-4f3a-960a-bf83f89563f0@d77g2000hsb.googlegroups.com> Message-ID: victor.herasme at gmail.com wrote: > Hi, > > it's me again with tons of questions. I hava an input file structured > like this: > > X XYData-1 > > 1. 3.08333 > 2. 9.05526 > 3. 3.13581 > ....... > > X XYData-2 > > 1. 4.08322 > 2. 4.02526 > 3. 3.95891 > ............... > > i want to format it so i only get the second column, in order to place > it in a mxn matrix. Let's say i want this: > > number1 number2 number3 > number4 number5 number6 > def iter_data(fileobj, numcols=3): i = 0 keys = [str(j) for j in range(1, numcols+1)] for line in fileobj: if not line.strip(): continue parts = line.split() if len(parts) != 2: continue key, val = parts[0].strip()[:-1], parts[1].strip() if key in keys: i = (i % numcols) + 1 while key > str(i): yield None i = (i % numcols) + 1 yield val elif i and val.startswith('XYData-'): # reset index for a new data row, also padding previous row while i < numcols: yield None i += 1 def iter_coords(numcols): row = 0 while True: yield divmod(row, numcols) row += 1 from itertools import izip from StringIO import StringIO data = ''' X XYData-1 1. 3.08333 2. 9.05526 3. 3.13581 X XYData-2 2. 4.02526 3. 3.95891 X XYData-3 1. 4.08322 2. 3.95891 X XYData-4 1. 3.08333 3. 3.13581 X XYData-5 1. 3.08333 2. 9.05526 4. 3.13581 5. 3.13581 ''' print buf = StringIO(data) k = 0 for item in iter_data(buf, 5): if k % 5 == 0: print print '| %s%s' % (item, ' ' * (8-len(str(item)))), k += 1 print buf = StringIO(data) for item in izip(iter_coords(5), iter_data(buf, 5)): print item print buf = StringIO(data) d = dict(izip(iter_coords(5), iter_data(buf, 5))) print d ++++++++++++++++++++++++++++++++++++++++++++++ | 3.08333 | 9.05526 | 3.13581 | None | None | None | 4.02526 | 3.95891 | None | None | 4.08322 | 3.95891 | None | None | None | 3.08333 | None | 3.13581 | None | None | 3.08333 | 9.05526 | None | 3.13581 | 3.13581 ((0, 0), '3.08333') ((0, 1), '9.05526') ((0, 2), '3.13581') ((0, 3), None) ((0, 4), None) ((1, 0), None) ((1, 1), '4.02526') ((1, 2), '3.95891') ((1, 3), None) ((1, 4), None) ((2, 0), '4.08322') ((2, 1), '3.95891') ((2, 2), None) ((2, 3), None) ((2, 4), None) ((3, 0), '3.08333') ((3, 1), None) ((3, 2), '3.13581') ((3, 3), None) ((3, 4), None) ((4, 0), '3.08333') ((4, 1), '9.05526') ((4, 2), None) ((4, 3), '3.13581') ((4, 4), '3.13581') {(1, 3): None, (3, 0): '3.08333', (2, 1): '3.95891', (0, 3): None, (4, 0): '3.08333', (1, 2): '3.95891', (3, 3): None, (4, 4): '3.13581', (2, 2): None, (4, 1): '9.05526', (1, 1): '4.02526', (3, 2): '3.13581', (0, 0): '3.08333', (0, 4): None, (1, 4): None, (2, 3): None, (4, 2): None, (1, 0): None, (0, 1): '9.05526', (3, 1): None, (2, 4): None, (2, 0): '4.08322', (4, 3): '3.13581', (3, 4): None, (0, 2): '3.13581'} From sln at netherlands.com Fri Aug 22 19:36:07 2008 From: sln at netherlands.com (sln at netherlands.com) Date: Fri, 22 Aug 2008 23:36:07 GMT Subject: The Importance of Terminology's Quality References: <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: On Fri, 22 Aug 2008 23:23:57 +0000 (UTC), Martin Gregorie wrote: >On Fri, 22 Aug 2008 22:56:09 +0000, sln wrote: > >> On Thu, 21 Aug 2008 09:11:48 -0500, rpw3 at rpw3.org (Rob Warnock) wrote: >> >>>sln at netherlands.com> wrote: >>>*IS* raw machine code, *NOT* assembler!! >> [snip] >> >> I don't see the distinction. >> Just dissasemble it and find out. >> >There's a 1:1 relationship between machine code and assembler. >Unless its a macro-assembler, of course! > >> >> Each op is a routine in microcode. >> That is machine code. Those op routines use machine cycles. >> >Not necessarily. An awful lot of CPU cycles were used before microcode >was introduced. Mainframes and minis designed before about 1970 didn't >use or need it and I'm pretty sure that there was no microcode in the >original 8/16 bit microprocessors either (6800, 6809, 6502, 8080, 8086, >Z80 and friends). > >The number of clock cycles per instruction isn't a guide either. The only >processors I know that got close to 1 cycle/instruction were all RISC, >all used large lumps of microcode and were heavily pipelined. > >By contrast the ICL 1900 series (3rd generation mainframe, no microcode, >no pipeline, 24 bit word) averaged 3 clock cycles per instruction. >Motorola 6800 and 6809 (no microcode or pipelines either, 1 byte fetch) >average 4 - 5 cycles/instruction. Surely you have caved to intelligence. And there is nothing beyond op. What has the friggin world come to!!! sln From grante at visi.com Tue Aug 12 16:33:52 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 12 Aug 2008 15:33:52 -0500 Subject: Pyserial not getting response every time, input/output errors References: Message-ID: On 2008-08-12, Carsten Haese wrote: > Rainy wrote: >> Hello! >> >> I'm having some trouble with pyserial package, I'm sending commands >> and reading responses from a custom pcb, and sometimes I get a proper >> response, at other times I get nothing, and sometimes I get about half >> of the response string with beginning cut off. About half the time an >> empty string is returned, the other ~half time good response, and more >> rarely I get partial response. >> >> When I try to use the same Serial instance to send/receive a few >> times, I end up getting an input/output error. >> >> Here are some examples: >> >>>>> ser = serial.Serial('/dev/ttyAM1', 115200, timeout=0.1) > > One possible point of failure is that you're not supplying any > parameters for the data format (byte size, parity, stop bits) and flow > control. The Serial object will assume defaults, and those defaults may > or may not be correct. None of those things are capable of creating an input/output error -- you'll just get goofy data values (or no answer from the device at the other end of cable). An input/output error usually means that there are issues with the underlying bus or there are hardware failures. > Try to find out what data format and flow control you should > be using and set explicit Serial parameters accordingly. -- Grant Edwards grante Yow! ... If I had heart at failure right now, visi.com I couldn't be a more fortunate man!! From dbpokorny at gmail.com Wed Aug 20 12:23:22 2008 From: dbpokorny at gmail.com (dbpokorny at gmail.com) Date: Wed, 20 Aug 2008 09:23:22 -0700 (PDT) Subject: exception handling in complex Python programs References: <00bb4e2f$0$20315$c3e8da3@news.astraweb.com> Message-ID: <8cb19b0b-1df8-4c5b-b546-a273c6fbc2e3@j1g2000prb.googlegroups.com> On Aug 19, 4:12?pm, Steven D'Aprano wrote: > On Tue, 19 Aug 2008 11:07:39 -0700, dbpoko... at gmail.com wrote: > > ? def do_something(filename): > > ? ? if not os.access(filename,os.R_OK): > > ? ? ? return err(...) > > ? ? f = open(filename) > > ? ? ... > > You're running on a multitasking modern machine, right? What happens when > some other process deletes filename, or changes its permissions, in the > time after you check for access but before you actually open it? This is a good point - if you want to use the correct way of opening files, and you don't want to worry about tracking down exception types, then we can probably agree that the following is the simplest, easiest-to-remember way: def do_something(filename): try: f = open(filename) except: ... Opening files is a special case where EAFP is the only correct solution (AFAIK). I still liberally sprinkle LBYL-style "assert isinstance(...)" and other similar assertions in routines. The point is that EAFP conflicts with the interest of reporting errors as soon as possible (on which much has been written see, for instance Ch. 8 - Defensive Programming in Code Complete), but LBYL conflicts with correctness when objects can be shared. Also, look at the man page for access. I have found at least two (one on my Linux box, another online) that essentially say "never use it." I completely forgot about this in my last post... David From bearophileHUGS at lycos.com Wed Aug 6 22:04:21 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 6 Aug 2008 19:04:21 -0700 (PDT) Subject: Parsing of a file References: Message-ID: <63a07a1e-ca5b-4430-baac-e31691ea8c0c@m45g2000hsb.googlegroups.com> Paul McGuire: > This code creates a single dict for the input lines, keyed by id. > Each value contains elements labeled 'id', 'ra', and 'mjd'. ... > d = dict( > (rec.split()[1][:-1], > dict([('id',rec.split()[1][:-1])] + > [map(str.lower,f.split('=')) > for f in rec.split()[2:5]] ) ) > for rec in data > ) ... Please, don't try to shove the program in one line, use PyParsing :o) Bye, bearophile From nytrokiss at gmail.com Fri Aug 22 17:12:56 2008 From: nytrokiss at gmail.com (James Matthews) Date: Fri, 22 Aug 2008 14:12:56 -0700 Subject: Python one-liner?? In-Reply-To: References: Message-ID: <8a6b8e350808221412u1e131595k72b9fbcc283c3cb2@mail.gmail.com> What i use them for is to test for packages. e.g python -c "import django" On Fri, Aug 22, 2008 at 2:03 PM, Matimus wrote: > > Do we have python one-liner like perl one-liner 'perl -e'?? > > > The answer is python -c... > > but python -h is useful too. > > Matt > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Tue Aug 19 08:14:44 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Aug 2008 14:14:44 +0200 Subject: WindowsXP/ CTypes - How to convert ctypes array to a string? In-Reply-To: References: Message-ID: dudeja.rajat at gmail.com wrote: > I also add the letter 'v' same as you suggested. However, I'm looking > to store this into some variable ( that variable could be be a string, > tuple or anything, Im not sure which is the suited one) the expression gives you a string object; you'll store it in a variable in the same way as you'd store any other expression result in Python. version = "v%d.%d.%d.%d" % tuple(version) but when you find yourself getting stuck on things like this, it might a good idea to take a step back and read the tutorial again: http://docs.python.org/tut/tut.html pay special attention to the parts that discuss how variables work in Python. if you prefer some other entry level tutorial, the following is said to be really good: http://www.ibiblio.org/g2swap/byteofpython/read/ From maebert at uos.de Mon Aug 25 10:32:41 2008 From: maebert at uos.de (Manuel Ebert) Date: Mon, 25 Aug 2008 16:32:41 +0200 Subject: newbie question In-Reply-To: References: Message-ID: <3BCE7A93-6908-4ABD-AD78-8349FD998EB8@uos.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi sharon, as I understand, you want to remove certain characters of a string. Try: number = int(fetched_number.replace(',', '')) this will first remove any , characters and then convert the string into an integer. Best, Manuel On Aug 25, 2008, at 4:15 PM, sharon k wrote: > hi all, > > i am new to python. > > i fetch a webpage with urllib, extract a few numbers in a format as > follow; > > 10,884 > 24,068 > > my question is how to remove the comma between the number, since i > have to add them up later. > > sorry for my bad english. > -- > http://mail.python.org/mailman/listinfo/python-list -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIssKJcZ70OCIgLecRAkxTAJ4wWKxmlAS8hdQZK0Eoj7pAxwx41wCaA/eI NY9GZKX6+PNIYIGaaghNvZg= =JN2/ -----END PGP SIGNATURE----- From gagsl-py2 at yahoo.com.ar Tue Aug 12 02:17:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Aug 2008 03:17:07 -0300 Subject: WinCvs Macros References: Message-ID: En Thu, 07 Aug 2008 06:22:31 -0300, Ren ChunYi escribi?: > Does anyone here have some doc like WinCVS API? I'm reading WinCvs > integrated Macros, but someplace make me puzzle. Better ask those questions in the WinCVS mailing list (or Yahoo group: http://tech.groups.yahoo.com/group/cvsgui ) -- Gabriel Genellina From mypetslug at gmail.com Wed Aug 20 16:48:10 2008 From: mypetslug at gmail.com (mypetslug at gmail.com) Date: Wed, 20 Aug 2008 13:48:10 -0700 (PDT) Subject: py2exe importing a package not in library.zip Message-ID: Hi, I'm sorry if this has been asked before, but I can't seem to find an answer to this anywhere and so far, trial and error hasn't gotten me far either. Using python 2.4, I've created a testing application. When the app starts up, I do a [code]from tests import *[/code] and it looks at the /tests directory and loads up all the tests it finds at that time. This works fine when interpreting the python code directly. The problem I'm having is trying to create an executable for distribution. What I'd like to be able to do is to include everything in the library.zip *except* the tests directory and then as I (or whoever) creates more and more tests, have the ability to simply drop them into the directory and the next time the app starts, it'll pick them up. However, if I don't include the tests in library.zip, then when I hit the [code]from tests import *[/code], it complains "AttributeError: 'module' object has no attribute 'test1'" when it gets to the first test. And If I do include the tests in the library.zip, it works with the tests that I have now, but then I still can't add any new ones without the attribute error unless I regenerate the exe every time. Basically, it seems like it comes down to importing a package outside the library.zip. So, is there any way to do this with py2exe? Or even another exe creating application? Thanks, MyPetSlug From rpm9deleteme at earthlink.net Mon Aug 4 18:39:26 2008 From: rpm9deleteme at earthlink.net (RPM1) Date: Mon, 04 Aug 2008 18:39:26 -0400 Subject: Wrapping C with Python References: Message-ID: brad wrote: > RPM1 wrote: > ... >> Basically you just compile your C code as a regular C code dll. >> ctypes then allows you to access the functions in the dll very easily. > > Does that work with C++ code too or just C? I believe it does work with C++ although I have not done that. Here's a simple example: http://wolfprojects.altervista.org/dllforpyinc.php I bet if you google around you'll find what you need. Remember there is documentation for ctypes in the Python documentation that comes with Python. Patrick From mail at microcorp.co.za Tue Aug 26 16:32:48 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 26 Aug 2008 22:32:48 +0200 Subject: Python String Immutability Broken! Message-ID: <004501c907bb$0c98f780$0d00a8c0@hendrik> "Simon Brunning": >You can indeed use ctypes to modify the value of a string - see >. You can use it to crash the OS, too. > >My advice - don't. Thanks for the link. Any advice on what to do or use as an I/O structure for dissemination? Ken Seehart: 8<----------- using ctypes to make 1+14 = 10 ------------------ >I love ctypes. So cool. It's not supposed to be safe. And here I thought I was weird? > Life is either a daring adventure or nothing. Security does not > exist in nature, nor do the children of men as a whole experience > it. Avoiding danger is no safer in the long run than exposure. > *Helen Keller * > /US blind & deaf educator (1880 - 1968)/ > >Of course I would not hire anyone who believes this quote, other than >Helen Keller, if she were still with us. Why not? ? as I see it, the Keller quote states the literal truth of the matter ? we all live under an illusion of security ? but then that might just be because I am South African, and the country is run by cattle thieves. >It is quite possible to write a small program that works using abused >strings. But my life better not depend on it. Among other things, if >you use the abused string as a key anywhere, you will not get correct >results. Trying to change the length of the string will cause >disasters. Lengthening a string will corrupt memory, and shortening the >string will not shorten it but rather embed '\0' in it. Understood. ? remember I am using it as a kind of array of ?pseudoports? - memory representations of what goes on on wires on the outside. So only a real madman would try to impute the kind of cross bit correlation needed to use the bunch of bits as a key. The length would be fixed, governed by the existence of real hardware on the outside. Ken Seehart again: >Yes, there is a better way. Use a character array instead of a string. The original reason I used a string directly instead of array.array was to try to skip the serialisation step when disseminating the information via sockets. As you can appreciate, this is all ?hot stuff? as it represents said wire states, and is of interest system wide. So lets explore this further ? lets say I use two arrays ? one to represent the stuff that must be output, and one to represent the latest inputs read. Then, I think, first prize would be the ability to ?publish? that information as a shared memory block, that can be accessed by other python processes. Then it will be possible to a priori ?chop up the ownership? of the various bits, so that a process can simply monitor the bits of interest to it, setting or clearing the bits of the outputs it is responsible for. In this way the work could be divided amongst many processes. Then, on a periodic basis, the I/O would be done, much like one would do it in an embedded system using an interrupt driven ticker routine. That would be really cool. Does anybody know how to get such memory sharing done in Python? (Linux only) - Hendrik From dullrich at sprynet.com Sat Aug 2 12:16:32 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Sat, 02 Aug 2008 11:16:32 -0500 Subject: PIL (etc etc etc) on OS X References: <489379A7.5060009@codebykevin.com> Message-ID: >From the other reply it seems I may not need to worry about any of this. Otoh I've had issues with pythonmac versus OSX versions, etc, in the past. Just in case, also in the spirit of that curious idea that learning things is good: First, it occurred to me that I've got wxPython installed and it includes jpeg support. I don't suppose that means that wxPython has already put a libjpeg somewhere and I just need to tell PIL where it is? Regardless, about your suggestions below (again, any assertions here are really questions): Presumably jibjpeg needs to be unzipped into its own directory, or configure/make etc wouldn't be able to figure out what I want to make. Presumably that happens automatically when I unzip it. Then after I do the configure/make/sudo make install will libjpeg automatically be in some standard place? If not, what's a good choice of standard place to put it, and how do I put it there? (If I start here then it will unzip to there, and then after I make it there it will be installed in this third place, which is where I want it.) Thanks. Sorry to be so dumb - yes, it's perfectly reasonable for eff to assume that people using PIL are programmers. With a "new thing" in, say, Python I'd just try something and then figure out what to try next to make it work - I don't want to take that approach here lest I re-make part of Darwin or something. Once many years ago I learned a new thing: Attempting to run a sufficiently invalid DOS exe could cause physical damage to a hard drive... that wasn't the only thing I learned that day. (Probably won't get back to this til Monday, btw, in case you say something and I don't seem interested.) DU. In article <489379A7.5060009 at codebykevin.com>, Kevin Walzer wrote: > David C. Ullrich wrote: > > Decided to try to install PIL on my Mac (OS X.5). > > OK, sounds good. > > > > I know nothing about installing programs on Linux, > > nothing about building C programs, nothing about > > installing libraries, nothing about "fink", nothing > > about anything. Please insert question marks after > > every sentence: > > For the record, OS X isn't Linux--it's a variant of BSD Unix. Similar, > but no identical, to Linux. > > > > > I saw a "BUILDME" with instructions "for lazy programmers". > > I did that. It seems that everything worked except a > > jpg library is missing. > > OK. > > > > > I read that I need to install libjpeg. I read that on OS X > > this is "usually" done using fink. Great: > > > > (i) The idea of installing fink scares me, for no reason > > I could name. There's no way that's going to confuse the > > rest of Darwin, right? > > You don't really need Fink just to install libjpeg. You do need the > developer tools (Xcode) installed, otherwise you can't build any > software at all. > > Libjpeg can be downloaded from http://www.ijg.org/. Download it, > untar/unzip it. Fire up terminal, cd to the libjpeg directory, and type > these commands: > > configure > make > sudo make install > > That should get libjpeg built and installed. > > > > > (ii) When I look at the fink website I see a list of > > supported libraries, not including libjpeg. > > So don't worry about Fink. > > > > > I hate messing with things that I don't understand at _all_... > > Well, that's understandable, but this is your chance to learn something > new. > > > > Thanks for any advice or comments. > > > > DU. > > > --Kevin -- David C. Ullrich From timr at probo.com Thu Aug 28 02:59:08 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 28 Aug 2008 06:59:08 GMT Subject: struct.Struct random access References: Message-ID: castironpi wrote: > >I'd like to seriously nominate this idea and get a considered opinion >on it. > >struct.Struct lets you encode Python objects into structured memory. >It accepts a format string, and optionally a buffer and offset to/from >which to read/write the structure. What do you think of random access >to the results? To avoid Marc's concern about meaningless anonymous >record entries, model the constructor after 'namedtuple' type. > >(unproduced) >>>> packer= struct.Struct( 'IIIf255p', 'i1 i2 i3 afloat name' ) >>>> packer.pack_into( buf, off, 10, 20, 30, 0.5, 'abc' ) >>>> packer.unpack_from( buf, off, 'i3' ) >30 >>>> packer.unpack_from( buf, off ) >( 10, 20, 30, 0.5, 'abc' ) >>>> packer.pack_into( buf, off, 'i1', 12 ) What data type would you expect "buf" to be? Your design requires it to be both an input and an output parameter. Today's "struct" converts into and out of a string, and strings are immutable. So, to continue with that standard, you would have to pass a string into "pack_into" and have the modified result returned as an output: buf = packer.pack_into( None, 0, 10, 20, 30, 0.5, 'abc' ) buf = packer.pack_into( buf, 0, 'i1', 12 ) In the end, I'm not sure you are really saving anything. >Even in sequential access speed benefits, by avoiding the construction >of n-1 objects. This is a fairly major change, because it requires a "struct.Struct" object to maintain state, something that the "struct" module currently does not do. In my personal opinion, this is a rather large and confusing change, for very little benefit. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From paul at boddie.org.uk Sun Aug 17 15:46:44 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 17 Aug 2008 12:46:44 -0700 (PDT) Subject: dynamic attribute syntax References: Message-ID: On 17 Aug, 21:29, castironpi wrote: > > What are the changes, pros and cons, involved in something like: > > obj:att for a dynamic access, and obj.att for static? A previous proposal and discussion can be found here: http://www.python.org/dev/peps/pep-0363/ Paul From tjreedy at udel.edu Mon Aug 11 17:56:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 11 Aug 2008 17:56:21 -0400 Subject: eval or execute, is this the (most) correct way ? In-Reply-To: <48A07B27.5060308@gmail.com> References: <00b06501$0$14351$c3e8da3@news.astraweb.com> <48A07B27.5060308@gmail.com> Message-ID: Stef Mientki wrote: > Steven D'Aprano wrote: >> The best solution is not to re-invent the wheel: "import code" is the >> way to emulate Python's interactive interpreter. > sorry, but that confuses me even more, "The code module provides facilities to implement read-eval-print loops in Python. Two classes and convenience functions are included which can be used to build applications which provide an interactive interpreter prompt." IDLE uses it to do just that. File idelib/pyshell.py imports InteractiveInterpreter. A quarter of the file is the definition of class ModifiedInterpreter(InteractiveInterpreter): > I don;t have a file / module, > just a workspace and one or more lines of code in memory. The code module has many options. "InteractiveConsole.push(line) Push a line of source text to the interpreter. " Anyway, your first post indicated that those 'lines of code in memory' originate from console input, which, I believe, is the default input source for the classes. You will need to experiment to see just how they work. >> Doing a search of the file code.py, I don't find the string "eval" at >> all. My guess is that your approach is probably not the best way. It would use 'exec' on statements, even if they happen to be expression statements. Exec is not going away. It is a built-in function in 3.0. Terry Jan Reedy From brencam at gmail.com Wed Aug 27 03:12:23 2008 From: brencam at gmail.com (BrendanC) Date: Wed, 27 Aug 2008 00:12:23 -0700 (PDT) Subject: Inspecting the Instance Vars in a class/object - How? Message-ID: <1efcc029-17cc-4d5e-b70b-2a2e25dfd214@k36g2000pri.googlegroups.com> I'm trying to understand reflection/introspection in Python. How can I identify the the type of attribute (e.g. instance var) in a class? The following returns all the class attributes (methods and instance vars). However I'm interested in identifying the type of value for each case - (e.g. I'd like to identify the instance variables separately). (The Inspect module has an ismethod method, but not an isinstancevariable method). e.g. In the following example I'd like to extract the class vars strvar and intNum and ignore the methods/other attribute types. What is the best way to do this? class test: # Dummy Class for reflection testing strVar = '1234' intNum = 0 def nullmethod(): pass def addmethod(self,v1, v2): v = v1 + v2 return v if __name__ == "__main__": mytest = test() for key in dir(mytest): value = getattr(object, key) print 'Key: %s ; Value %s ' % (str(key) ,str(value)) From norseman at hughes.net Thu Aug 14 19:54:30 2008 From: norseman at hughes.net (norseman) Date: Thu, 14 Aug 2008 16:54:30 -0700 Subject: The Importance of Terminology's Quality In-Reply-To: <48a4b2ba$0$20923$607ed4bc@cv.net> References: <48617847$0$5021$607ed4bc@cv.net> <486ae06b$0$5011$607ed4bc@cv.net> <4883bc90$0$7327$607ed4bc@cv.net> <48a4b2ba$0$20923$607ed4bc@cv.net> Message-ID: <48A4C5B6.1070109@hughes.net> John W Kennedy wrote: > Robert Maas, http://tinyurl.com/uh3t wrote: >> John W Kennedy wrote: >> JWK> Into the 60s, indeed, there were still machines being made >> JWK> that had no instruction comparable to the mainframe BASx/BALx >> JWK> family, or to Intel's CALL. You had to do a subprogram call by >> JWK> first overwriting the last instruction of what you were >> JWK> calling with a branch instruction that would return back to >> JWK> you. >> HUMMmmmmm! Brings back memories. The Monroe-bot 9, Olivetti, Sperry-Rand and the rest. I came in on the IBM-360 original series in the mid-60'. Subroutine docs were important. You needed to know from which register the sub was going to use/store the return address. (As well as which registers it used for what both incoming and out going.) it's been so long I forget the actual mnemonics. something like: . . load R12,rtn89 (alt) jump sub32 sub32: sub32: rtn89: stor R12,safe . . . . . . jump R12 rtrv R12,safe jump R12 Programs were simple then. Card, paper tape, mag tape IN and card, paper tape, mag tape and hardcopy paper OUT. The monitor was the guy who looked at the flashing lights on the metal panel. And to change a program on the 1401 usually required the soldering iron, patch cables and a patch board! And a new deck of cards containing the next program. Don't use a used deck 'cause then the reader will eat the cards. :) I helped Chevron East convert from 1401 to 360. Long ago, far away and with no intention of returning to those long long hours in 'the room'. LSI??? Ha-Ha. Anyone remember the word transistor?. Power supply was tubes. However, core was 3-axis iron core. That I miss. 17 flip switches set 1-16 & flip 17 to load first half word set 1-16 & flip 17 to load 2nd half word 1st boot word ready . . core boot loaded mag master 1 and read next sequence which ... only took 45 min. to boot if first effort succeeded. Otherwise... it was going to be a long day.... The "Good 'Ole Days"? Point of view. Code was tight and comradely was what kept us going. The long hours and being shunned by company people as gargoyles down there or some such - I can do without. ...(snip) Steve norseman at hughes.net OH- If the sub might be called other than as if in-line, an area of memory was given to safe and it would be incremented/decremented upon use. safe was just an address. safe dw 40 or whatever From mensanator at aol.com Sat Aug 9 11:07:26 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 9 Aug 2008 08:07:26 -0700 (PDT) Subject: list question... unique values in all possible unique spots References: Message-ID: <57fcf019-1afd-4c48-b329-42a0ffc4c5ac@x35g2000hsb.googlegroups.com> On Aug 9, 8:05?am, ToshiBoy wrote: > I'm wondering how to do this the most elegant way: I found this quiz > in some magazine. I've already solved it on paper, but want to write a > python program to solve it. It comes down to being able to represent > range(1,27) through a number of formulas. How do I write a loop that > will loop through this list, so that: 1. every number only occurs > once, and 2. I get every possibility of order within the list? I guess > it'd be somewhat similar to Sudoku, where you have the numbers from > 1-9 in any possible order. Here it's 1-26. Python 2.6 has a permutation function: IDLE 2.6b1 >>> import itertools >>> for i in itertools.permutations(range(4)): print i (0, 1, 2, 3) (0, 1, 3, 2) (0, 2, 1, 3) (0, 2, 3, 1) (0, 3, 1, 2) (0, 3, 2, 1) (1, 0, 2, 3) (1, 0, 3, 2) (1, 2, 0, 3) (1, 2, 3, 0) (1, 3, 0, 2) (1, 3, 2, 0) (2, 0, 1, 3) (2, 0, 3, 1) (2, 1, 0, 3) (2, 1, 3, 0) (2, 3, 0, 1) (2, 3, 1, 0) (3, 0, 1, 2) (3, 0, 2, 1) (3, 1, 0, 2) (3, 1, 2, 0) (3, 2, 0, 1) (3, 2, 1, 0) Bur bear in mind that permutations of size n are n!. So the permutaions of range(1,27) is 26! which is >>> print gmpy.fac(26) 403291461126605635584000000 That's 403 octillion. Are you sure you want to do this? From jura.grozni at gmail.com Sat Aug 9 11:52:28 2008 From: jura.grozni at gmail.com (azrael) Date: Sat, 9 Aug 2008 08:52:28 -0700 (PDT) Subject: Ascii to binary conversion References: <9a2f9777-8261-4365-a741-a3edab83266a@n38g2000prl.googlegroups.com> Message-ID: You see, I don't like reading some tutorials. I pick myself a problem and look for ways to slove it. I am using Python for about 2 years, but mostly for image processing. As you say, ord is oposite to chr. I learn by example. thnx guys, this looks great On 9 kol, 16:47, Larry Bates wrote: > azrael wrote: > > looks nice. is there an oposite function of ord() so I could also > > bring a binary number also back to ascii. > > > the speed matters if you plan to exchange about 10 M ascii chars and > > don't wont to wait a year for the results. :) > > > On 9 kol, 15:39, John Machin wrote: > >> On Aug 9, 11:18 pm, azrael wrote: > > >>> Hy folks, > >>> I googled, and searched, and can not bealive that I have not found a > >>> built in way to convert the easy and elegant python way a function to > >>> easily convert simple ascii data to binary and back. > >>> I've written some my own but they were pretty slow using binascii > >>> linbrary with hexifly and unhexifly functions conbined with a > >>> lookuptable of binary and hex values. > >>> Any idea how to easily write a function that recieves a character or > >>> string and returns a binary number like: > >>> ascii("1") is converted to bin("00110001") > >> Here's one way: > > >>>>> def a2b(a): > >> ... ? ?ai = ord(a) > >> ... ? ?return ''.join('01'[(ai >> x) & 1] for x in xrange(7, -1, -1)) > >> ... > > >>>>> a2b('1') > >> '00110001' > >>>>> a2b('2') > >> '00110010' > >>>>> a2b(chr(0)) > >> '00000000' > >>>>> a2b(chr(255)) > >> '11111111' > > >> BUT ... why are you doing this so much that the speed matters??? > > Opposite of ord() is chr(). ?These functions have been available in every > language I've used for the last 30 years. ?I would suggest that you might want > to spend a little time reading a good Python book and to work through the > tutorial. ?It will be worth your investment of time. > > -Larry From inquiry at officeexpander.com Sat Aug 16 13:03:47 2008 From: inquiry at officeexpander.com (Office Expander) Date: Sat, 16 Aug 2008 13:03:47 -0400 Subject: Plot pkg - Multiple Y axes? Message-ID: <9D73D2B0-A506-4097-A087-92C6E48A8D3E@officeexpander.com> Hello, You can make Multiple Y Axes plots in Excel using Multy_Y or EZplot. There is a demo version at www.OfficeExpander.com Cheers! ______________________________________ Hello, I'm searching for a plotting package that will allow multiple y axes of different scales. For example I'd like to overlay 4 or 5 time series with each series having a separate axis. Does anyone know of such a package? Thank you, Frank From castironpi at gmail.com Fri Aug 22 18:42:02 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 22 Aug 2008 15:42:02 -0700 (PDT) Subject: In-place memory manager, mmap (was: Fastest way to store ints and floats on disk) Message-ID: <1cf85075-17a1-4a1d-8ea5-bf5104541528@s50g2000hsb.googlegroups.com> Hi, I've got an "in-place" memory manager that uses a disk-backed memory- mapped buffer. Among its possibilities are: storing variable-length strings and structures for persistence and interprocess communication with mmap. It allocates segments of a generic buffer by length and returns an offset to the reserved block, which can then be used with struct to pack values to store. The data structure is adapted from the GNU PAVL binary tree. Allocated blocks can be cast to ctypes.Structure instances using some monkey patching, which is optional. Want to open-source it. Any interest? From bedouglas at earthlink.net Tue Aug 26 17:22:43 2008 From: bedouglas at earthlink.net (bruce) Date: Tue, 26 Aug 2008 14:22:43 -0700 Subject: libxml2dom - parsing maligned html In-Reply-To: <78db1ed5-49d5-47ab-893d-925fedb96357@p10g2000prf.googlegroups.com> Message-ID: <008e01c907c1$e1b0c230$0301a8c0@tmesa.com> hi paul... so you're the guy behind the libxml2dom ehh..!! glad to say hey! so this really is an issue with libxml2dom. ok, good, at least i know where the issue is. and yeah, i know the real issue is the fact that the html isn't valid!! shouldn't have multiple "html" trees... from what i can tell, this isn't really solved via tidy/beautifulsoup either, as a multiple html tree structure probably won't be looked at as being invalid fom a token perspective. ok, i can somehow live with this, i can accommodate it. but tell me, when the parse module/class for libxml2dom does its thing, why does it not go forward on the tree when it comes to a , if there's more text in the string to process??? oh, also, regarding screen parsing/crawling, i've seen a number of sites that have discussed using a web testing app, like selinium, and driving a browser process, in order to really capture all the required data. any thoughts on the pros/cons of this kind of approach to scraping data... thanks -bruce -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Paul Boddie Sent: Tuesday, August 26, 2008 8:48 AM To: python-list at python.org Subject: Re: libxml2dom - parsing maligned html On 26 Aug, 17:28, "bruce" wrote: > so it's as if the parseString only reads the initial "html" tree. i've > reviewed as much as i can find regarding libxml2dom to try to figure out how > i can get it to read/parse/handle both html trees/nodes. Maybe there's some possibility to have libxml2 read directly from a file descriptor and to stop after parsing the first document, leaving the descriptor open; currently, this isn't supported by libxml2dom, however. Another possibility is to feed text to libxml2 until it can return a well-formed document, which I do as part of the libxml2dom.xmpp module, but I don't really support this feature in the public API. Again, improvements to libxml2dom may happen if I find the time to do them. Paul -- http://mail.python.org/mailman/listinfo/python-list From srinuakula89 at yahoo.com Tue Aug 19 09:15:54 2008 From: srinuakula89 at yahoo.com (srinu) Date: Tue, 19 Aug 2008 06:15:54 -0700 (PDT) Subject: View this blogspot Message-ID: <79fbc483-87aa-424a-91ca-9d975c1e0c28@j1g2000prb.googlegroups.com> http://indianmasalavideos4u.blogspot.com/ From deets at nospam.web.de Tue Aug 26 09:09:16 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Aug 2008 15:09:16 +0200 Subject: property() usage - is this as good as it gets? References: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> <48b3bedd$0$4472$426a34cc@news.free.fr> <794a023d-be80-4849-b508-e448b90cc3b4@a3g2000prm.googlegroups.com> Message-ID: <6hidktFlt0voU2@mid.uni-berlin.de> > P.S. How did my post manage to ignite a mini flame war?! Because of the high resident troll quota in replies - which is created by just one rather annoying member of this community... Diez From ggpolo at gmail.com Thu Aug 28 15:17:16 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 28 Aug 2008 16:17:16 -0300 Subject: ImageTk.Photoimage not displayed In-Reply-To: References: Message-ID: On Thu, Aug 28, 2008 at 4:07 PM, harryos wrote: > hi > i am trying to display an image on a canvas in a gui made with Tkinter > widgets > > > class PhotoDisplay: > def __init__(self,parent): > self.mainframe = Frame(parent,background="grey") > ..... > #added a subframe to hold canvas and button > .... > self.canvFrame=Frame(self.mainframe,...) > .... > self.mycanvas=Canvas(self.canvFrame,...) > ... > > def okbuttonClick(self): > self.mycanvas.delete(ALL) > myimagename=...#get an imagefilename from somewhere.. > self.showSelectedImage(myimagename) > > def showSelectedImage(self,imageName): > myimg=ImageTk.PhotoImage(file=imageName) > imgtag=self.mycanvas.create_image(70,100,image=myimg) > self.mycanvas.update_idletasks() > > > when i click the button ,the image is displayed for a fraction of a > second on the canvas and disappears.I couldn't figure out why this is > happening.I am quite new to Tkinter and still going thru Fredrik > Lundh's intro to tkinter..can someone tell me if i am doing sthing > wrong here? You have to keep a reference to these images you are creating, otherwise as soon as those methods finishes they are gone. > thanks in advance > harry > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From b-cousson at ti.com Wed Aug 13 11:32:00 2008 From: b-cousson at ti.com (Cousson, Benoit) Date: Wed, 13 Aug 2008 17:32:00 +0200 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: <76fd5acf0808121415h41cc580bj85d96e648c54ab4b@mail.gmail.com> References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> <76fd5acf0808120651u259e5d8dt32a8d49bb5d77add@mail.gmail.com> <200808122240.22517.maric@aristote.info> <76fd5acf0808121415h41cc580bj85d96e648c54ab4b@mail.gmail.com> Message-ID: <74583B8642AB8841B30447520659FCA92CC054B5@dnce01.ent.ti.com> > Defining it as a nested class saves you one line > of code, but IMHO makes the result just a bit more cluttered, while > reducing the elegance of reusing the metaclass. The whole point of nested class is to avoid polluting the namespace with classes that are only used locally. So the argument about the elegance of reusing is not very valid in that case. I agree that they are other ways using module to avoid namespace pollution, but in some case it is easier to use nested class instead and keep everything in the same file. In my case, I'm trying to use a similar approach as XIST's one, meaning using Python class to model hierarchical data. So clearly nested class is a very nice and easy understandable way to do that. > Here are only a few examples of threads giving good reasons against > class nesting. I've never seen any good arguments for it. There are > dozens of good reasons we don't encourage it and won't actively > support it. > > http://mail.python.org/pipermail/python-dev/2005-March/052454.html > http://mail.python.org/pipermail/python-dev/2002-November/029872.html >From what I quickly read in these email threads, except for the pickling issue and the fact that Guido does not like nested classes, I do not see strong argument against it either. Regards, Benoit From lists at cheimes.de Thu Aug 14 16:42:24 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 14 Aug 2008 22:42:24 +0200 Subject: negative numbers are not equal... In-Reply-To: <48A4932F.4010302@gmail.com> References: <48A4932F.4010302@gmail.com> Message-ID: ariel ledesma wrote: > i read that 'is' compares if they are really the same object, but i > don't that's it because then why does -5 return True? > of course i could only use == to compare, but still, what am i missing > here? Rule of thumb: Never use 'is' with any kind of string or numeric object. 'is' is not a comparison operator. It checks for object identity. You are getting the result because Python optimized small integers. See http://svn.python.org/projects/python/trunk/Objects/intobject.c Integers between -5 and +256 are singletons as are some other objects like strings with one element or empty tuples. You must not rely on the optimization. Christian From stefan_ml at behnel.de Tue Aug 19 14:32:13 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 19 Aug 2008 20:32:13 +0200 Subject: HTML Tables In-Reply-To: References: Message-ID: <48ab11ad$0$11730$9b4e6d93@newsspool1.arcor-online.net> Amie wrote: > Thanks for your help so far. Ok here's a scenario: I have to create a > site that displays 34 html tables. > In each of these tables the following information has to be displayed: > logo (image), site name, date, time. > Remember: in all of these 34 tables. the information displayed on each > of these tables is retrieved from the database. I did write a mysql > query, I just don't know how to link it with the for loop that has to > display all these tables. If anyone can, can you roughly show me how > to go about doing this. This might get you going: http://codespeak.net/lxml/lxmlhtml.html#creating-html-with-the-e-factory Try something like this: tables = [] for row in rows_returned_by_the_query: tables.append( E.TABLE( ... ) ) html_body = E.BODY( *tables ) Stefan From elessar at nienna.org Fri Aug 1 08:28:09 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 01 Aug 2008 06:28:09 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <9f4b1c12-d010-45f6-91ee-d490e2f850dc@79g2000hsk.googlegroups.com> Message-ID: <48930159.2020306@nienna.org> Antoon Pardon wrote: > On 2008-08-01, Erik Max Francis wrote: >> Antoon Pardon wrote: >> >>> I now have the following question for people who argue that "if x" >>> is more polymorphic. I could subclass list, so that instances >>> of this new sequence would always behave as true, even if they are >>> empty. I could then rewrite my loop as follows: >>> >>> while 1: >>> extra = produce() >>> if not extra: >>> break >>> for el in extra: >>> adjust_with(el) >>> calculate() >>> >>> Is this second loop now more polymorphic as the first? >> It's more confusing since you've changed the standard behavior of a >> standard type, which doesn't really have anything to do with >> polymorphism. It's more confusing, if that's a benefit. > > So you accept my point that "if x" can be less polymorphic > and in fact can be more confusing than a more specific test. > I think your example is more related to a trap with polymorphism in general rather than an argument against 'is x' specifically. Any time you override a method, you have an opportunity to change the behavior in unexpected ways. Especially in languages like Python that don't do type checking. For example, you write a __cmp__ method like this: class ReallyBadPractice(object): def __cmp__(self, other): return -cmp(self, other) Of course any code that does comparisons on this class is going to behave unexpectedly! -Matt From invalid at invalid.invalid Sun Aug 10 09:52:37 2008 From: invalid at invalid.invalid (WP) Date: Sun, 10 Aug 2008 15:52:37 +0200 Subject: My very first python program, need help Message-ID: <6g8a56FenevdU1@mid.individual.net> Hello, below is my very first python program. I have some questions regarding it and would like comments in general. I won't be able to get my hands on a good python book until tomorrow at the earliest. The program takes a string and sums all numbers inside it. I'm testing with the following string: "123xx,22! p1" which should yield a sum of 123 + 22 + 1 = 146. My solution to this exercise was to write a function that takes a string and splits it into a list of numbers and then I will sum up the numbers in the list. In fact, I wrote two versions of this function: One uses a for loop to replace all characters that is not a digit and not a space with a space. That should leave me with the numbers intact and with only spaces separating these numbers. Then I call split to get a list of numbers (here I discovered I must not use a sep equal to ' ' or the returned list would contain empty strings as well). This is calculate_sum_1() and look at the comment in the code to see what worries me there. The second one uses regular expressions and the problem I have with that is that I get a list of containing not just the numbers but empty strings as well. I'm working around that in my loop that sums the numbers but it would be better to not have these empty string in the list in the first place. Here's the code: import re def calculate_sum_1(str): for c in str: if c.isdigit() == False and c != ' ': # That we assign to the variable we're looping over worries me... str = str.replace(c, ' ') mylist = str.split() print "(for loop version) mylist after replace() and split() = ", mylist sum = 0 for item in mylist: sum += long(item) return sum def calculate_sum_2(str): #print "In replace_nondigits_2(), str = ", str p = re.compile('[^0-9]') mylist = p.split(str) print "(regex version) mylist after calling split(): ", mylist sum = 0 for item in mylist: if item.isdigit(): sum += long(item) return sum str = "123xx,22! p1" # Sum = 123 + 22 + 1 = 146 print "str = ", str print "calculate_sum_1(str): %d" % calculate_sum_1(str) print "calculate_sum_2(str): %d" % calculate_sum_2(str) The output when run is: str = 123xx,22! p1 (for loop version) mylist after replace() and split() = ['123', '22', '1'] calculate_sum_1(str): 146 (regex version) mylist after calling split(): ['123', '', '', '22', '', '', '1'] calculate_sum_2(str): 146 Hope I made some sense and thanks for reading! - Eric (WP) From tino at wildenhain.de Sun Aug 31 09:23:36 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sun, 31 Aug 2008 15:23:36 +0200 Subject: Writing to ms excel In-Reply-To: References: <09tjb4p32lfbk4nji4sqjg5mk0e99gub2v@4ax.com> <00c9fe68$0$20302$c3e8da3@news.astraweb.com> Message-ID: <48BA9B58.5030006@wildenhain.de> Marin Brkic wrote: >... > I remember an older coleague who said; "open, free and whatever > licence type ... software is free, only up to some amount of $$/per > hour". After that you just want things to work, and if they don't > work, there are people who are paid $/per hour to make it work. Well I hear that too but its obviously the biggest lie in IT. You can't make MS Office to work. There is no way to do so. Even asking MS the question why something does not work costs a lot of money and you don't get a solution. Example: try to put group templates on a WEBDAV "share". So in the OS world you can actually spend that money on someone indeed giving you a solution. Btw, SUN has a plugin for MS office to read/write odf. (Which works instead of the solution from MS itself). Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From tslocum at gmail.com Mon Aug 4 01:14:27 2008 From: tslocum at gmail.com (Trevor Slocum) Date: Sun, 3 Aug 2008 22:14:27 -0700 Subject: Peer-to-Peer Chat Program Message-ID: <98ad656a0808032214w23b51020j29d97fac1249d14a@mail.gmail.com> Python seemed like the right choice for writing a peer-to-peer application, as the support for sockets is adequate and the cross-platform ability is nominal. That's why I searched around for P2P frameworks in Python, and didn't have much luck. The framework that I did find was designed specifically for file transfers, rather than simple message carriers, and implemented a complex multicast system. So, with Python in one hand and Google in the other, I set out to write my own P2P app in Python, with zero previous P2P experience. I had to start off by looking up how P2P works, then figure out how to get messages across the network, and then how to bootstrap each node, without centralizing the network. I decided to make it connectionless because they were simple messages. The current implementation is that a peer creates a message and forwards it to all of its known peers, and then the other peers do the same. This is for simplicity, as it causes quite a bit of needless rebound from each of the other peers sending a message which has already been received. In order to reduce this, each message is tagged with a unique ID which is verified against upon each arrival. Once that worked well, I needed to get peers to know each other. My current solution is a provider script running on a single server which is auto-pinged every minute by each peer, and any new peers receive a list of known peers from it. This can easily be expanded to many more servers in case any go offline. Even if zero providers are online, users can manually add nodes from the console and the framework will automatically build a known peer list from them. Like I said, I didn't know anything about P2P before this, and I'm sure much of what I've done so far can be improved upon. That's why I'm posting here. I'd like to make an open request to anyone who would like to assist me in the application development to reduce the resource usage and improve the overall network efficiency. Even simple "Ah, I saw you were doing this in your code, I recommend you do this..." would be of great help. If you are interested, you may view the Google Code page at http://code.google.com/p/kaishi/ or checkout the SVN repository directly using http://kaishi.googlecode.com/svn/trunk/ I have proper hosting and can set up a specific website for collaboration on project ideas and such if support is carried after this message. I thank anyone who has taken their time to read this. -- Trevor "tj9991" Slocum -------------- next part -------------- An HTML attachment was scrubbed... URL: From eliben at gmail.com Fri Aug 15 10:45:00 2008 From: eliben at gmail.com (eliben) Date: Fri, 15 Aug 2008 07:45:00 -0700 (PDT) Subject: Parsing and Editing Source References: Message-ID: <1f8af357-67ee-462a-9211-c6ac4933e302@d1g2000hsg.googlegroups.com> On Aug 15, 4:21?pm, "Paul Wilson" wrote: > Hi all, > > I'd like to be able to do the following to a python source file > programmatically: > ?* Read in a source file > ?* Add/Remove/Edit Classes, methods, functions > ?* Add/Remove/Edit Decorators > ?* List the Classes > ?* List the imported modules > ?* List the functions > ?* List methods of classes > > And then save out the result back to the original file (or elsewhere). > > I've begun by using the tokenize module to generate a token-tuple list > and am building datastructures around it that enable the above > methods. I'm find that I'm getting a little caught up in the details > and thought I'd step back and ask if there's a more elegant way to > approach this, or if anyone knows a library that could assist. > > So far, I've got code that generates a line number to token-tuple list > dictionary, and am working on a datastructure describing where the > classes begin and end, indexed by their name, such that they can be > later modified. > > Any thoughts? > Thanks, > Paul Consider using the 'compiler' module which will lend you more help than 'tokenize'. For example, the following demo lists all the method names in a file: import compiler class MethodFinder: """ Print the names of all the methods Each visit method takes two arguments, the node and its current scope. The scope is the name of the current class or None. """ def visitClass(self, node, scope=None): self.visit(node.code, node.name) def visitFunction(self, node, scope=None): if scope is not None: print "%s.%s" % (scope, node.name) self.visit(node.code, None) def main(files): mf = MethodFinder() for file in files: f = open(file) buf = f.read() f.close() ast = compiler.parse(buf) compiler.walk(ast, mf) if __name__ == "__main__": import pprint import sys main(sys.argv) From tjreedy at udel.edu Fri Aug 15 18:59:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 15 Aug 2008 18:59:43 -0400 Subject: Missing exceptions in PEP 3107 In-Reply-To: References: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> <8800beb6-c07b-44af-b9ac-fcb00f35dc3a@f36g2000hsa.googlegroups.com> Message-ID: Christoph Zwerschke wrote: > That's not quite true: PEP 3017 describes a mechanism for annotating > function parameters *and return values*, and my point was why it does > not provide a mechanism for annotating thrown exceptions, since I see > info on thrown exceptions in the same category as info on return values. I would agree... but... The problem is that code that uses a function hardly cares whether an exception that replaces the normal return is raised explicitly, by a syntax operation (and these are not yet completely documented, though perhaps they should be), or by a function called within the function. tjr From matthias.blaesing at rwth-aachen.de Fri Aug 29 06:46:05 2008 From: matthias.blaesing at rwth-aachen.de (Matthias =?iso-8859-1?q?Bl=E4sing?=) Date: 29 Aug 2008 10:46:05 GMT Subject: Iterating two arrays at once References: Message-ID: Am Fri, 29 Aug 2008 03:35:51 -0700 schrieb mathieu:> > A = [1,2,3] > B = [4,5,6] > for a,b in A,B: # does not work ! > print a,b > > It should print: > > 1,4 > 2,5 > 3,6 Hey, zip is your friend: for a,b in zip(A,B): print a,b does what you want. If you deal with big lists, you can use izip from itertools, which returns a generator. from itertools import izip for a,b in izip(A,B): print a,b HTH Matthias From Michael.Coll-Barth at VerizonWireless.com Wed Aug 13 11:51:09 2008 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Wed, 13 Aug 2008 11:51:09 -0400 Subject: You advice please In-Reply-To: References: <20080813110444.7b48ddbc.darcy@druid.net><76fd5acf0808130811y7d7d6584m721096295a72af98@mail.gmail.com><48A2FBAC.3000103@wiggly.org> Message-ID: <20080813155223.66AF21E4008@bag.python.org> > -----Original Message----- > From: Calvin Spealman > > God forbid I try to make a joke. No kidding! As a lurker newbie, I don't mind one bit. Actually, I have yet to meet a person that codes in Ruby that doesn't also do Python. I have met many Python coders that have never even looked at Ruby. Your joke may have more truth in it than you realized. And upper management reads the *V*logs and believe the hype. We should be prepared to counter the argument. The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From PaulAlexWilson at gmail.com Fri Aug 8 10:19:26 2008 From: PaulAlexWilson at gmail.com (Wilson) Date: Fri, 8 Aug 2008 07:19:26 -0700 (PDT) Subject: Limits of Metaprogramming References: <0c56829a-7ad2-4ff2-b225-7981538e7c7a@j22g2000hsf.googlegroups.com> <64c69a68-aa00-4f59-a84e-52f5cfa14913@z66g2000hsc.googlegroups.com> <04bd26b2-20b4-45fc-b080-a470c1511cb0@34g2000hsh.googlegroups.com> Message-ID: <70426441-ee9f-46f5-8525-57a5d1452039@e39g2000hsf.googlegroups.com> On 8 Aug, 13:30, Iain King wrote: > On Aug 4, 5:13 pm, Tomasz Rola wrote: > > > On Mon, 4 Aug 2008, Wilson wrote: > > > " Every sufficiently large application has a poor/incomplete > > > implementation ofLISPembedded within it ". > > > Yep, this is either exact or very close copy of what I have read. > > It's Greenspun's Tenth Rule of Programming: > > "Any sufficiently complicated C or Fortran program contains an ad-hoc, > informally-specified bug-ridden slow implementation of half of Common > Lisp." > > Iain Thanks for that. Makes my attempt look pathetic! :) From rocksportrocker at googlemail.com Tue Aug 5 07:06:56 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Tue, 5 Aug 2008 04:06:56 -0700 (PDT) Subject: Wrapping C with Python References: Message-ID: <2e7cd08c-d28f-4fca-a480-37b639260ed2@l64g2000hse.googlegroups.com> On 4 Aug., 15:14, brad wrote: > RPM1 wrote: > > ... > > > Basically you just compile your C code as a regular C code dll. ?ctypes > > then allows you to access the functions in the dll very easily. > > Does that work with C++ code too or just C? It works if the interface of the DLL is C-style, that is you declare your functions with 'extern "C" { .... }' around them. Inside your modules implementation you can use C++ without any problems. What works fine too, is f2py from numpy. It targets at wrapping Fortran code, but is able to wrap C code too, see http://www.scipy.org/Cookbook/f2py_and_NumPy?action=show Greetings, Uwe Greetings, Uwe From castironpi at gmail.com Sun Aug 24 00:23:19 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 23 Aug 2008 21:23:19 -0700 (PDT) Subject: two's complement bytes References: <9a2a633c-b1ad-47a8-ae49-168b9fa62f90@x16g2000prn.googlegroups.com> Message-ID: <9786092a-a378-40ed-b930-268eb6c4d1a3@26g2000hsk.googlegroups.com> On Aug 23, 10:51?pm, "Adam W." wrote: > I'm dabbling with AVR's for a project I have and that means I have to > use C (ageist my will). ?Because my AVR will be tethered to my laptop, > I am writing most of my logic in python, in the hopes of using at > little C as possible. > > In my quest I came across a need to pass a pair of sign extended two's > complement bytes. ?After painfully reading the wikipedia article on > what two's complement was, I then thought of how I would handle this > in python. ?I don't really recall ever having to work in binary with > python, so I really am clueless on what to do. > > I can feed python either two hex bytes or binary, but how do I convert > it into an int, and more importantly how do I make sure it handles the > sign properly? Try this out. Does it come close to what you want? import struct struct.pack( 'i', ~10 ) ~struct.unpack( 'i', _ )[ 0 ] >>> import struct >>> struct.pack( 'i', ~10 ) '\xf5\xff\xff\xff' >>> ~struct.unpack( 'i', _ )[ 0 ] 10 >>> From rajat.dudeja at aeroflex.com Wed Aug 13 10:58:39 2008 From: rajat.dudeja at aeroflex.com (Dudeja, Rajat) Date: Wed, 13 Aug 2008 10:58:39 -0400 Subject: Looking out a module for Subversion In-Reply-To: References: <48A14FB6.4020009@sellerengine.com> <27cbc0fa0808120250t5d41af68u1d72b66f46ad0995@mail.gmail.com> Message-ID: Hi Fabio > Download eclipse 3.3 from http://download.eclipse.org/eclipse/downloads/drops/R-3.3.2-200802211800 /index.php (you can download only the > "Platform Runtime Binary" in that link) and then follow the instructions to install Pydev at http://fabioz.com/pydev/manual_101_install.html I see that this link for Pydev provides a commercial version of pydev (so this points the evaluation version of it) . Is there any open source version of it? cheers, Rajat Notice: This e-mail is intended solely for use of the individual or entity to which it is addressed and may contain information that is proprietary, privileged, company confidential and/or exempt from disclosure under applicable law. If the reader is not the intended recipient or agent responsible for delivering the message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If this communication has been transmitted from a U.S. location it may also contain data subject to the International Traffic in Arms Regulations or U.S. Export Administration Regulations and cannot be disseminated, distributed or copied to foreign nationals, residing in the U.S. or abroad, without the prior approval of the U.S. Department of State or appropriate export licensing authority. If you have received this communication in error, please notify the sender by reply e-mail or collect telephone call and delete or destroy all copies of this e-mail message, any physical copies made of this e-mail message and/or any file attachment(s). -------------- next part -------------- An HTML attachment was scrubbed... URL: From ireborin at gmail.com Fri Aug 15 12:31:16 2008 From: ireborin at gmail.com (Ivan Reborin) Date: Fri, 15 Aug 2008 18:31:16 +0200 Subject: wxPython beginners problem Message-ID: Hello all, I'm new to python, new as newbies get, so please, don't take wrongly if this seems like a stupid or overly simple question. I'm going through examples in a book I have ("Beginning python", by Hetland Marcus) and I just started doing wxPython examples. But every sample I try, for example: import wx app = wx.App() win = wx.Frame(None, title="Simple editor") loadButton = wx.Button(win, label='Open') saveButton = wx.Button(win, label='Save') win.Show app.MainLoop() closes too fast. After running in python IDLE just the line === restart === shows up. How can I keep the window to "stay alive" so I see what I get ? I'm on a winxp platform using python 2.5.2. if that matters. Please, any help, constructive advice and ideas are very much appreciated. Best regards Ivan Reborin From jasper at peak.org Mon Aug 18 04:32:12 2008 From: jasper at peak.org (Jasper) Date: Mon, 18 Aug 2008 01:32:12 -0700 (PDT) Subject: Bizarre method keyword-arg bug. Message-ID: I'm stumped. I'm calling a method that has keyword args, but not setting them, and yet one of them starts off with data?! The class definition begins like so: class BattleIntentionAction( BattleAction ): def __init__( self, factionName, location, tactic='hold', targetFacName='', terrainArgs=[], garrisonIds=[] ): self.terrainArgs = terrainArgs print terrainArgs The constructor is called somewhere else, like so: act = BattleIntentionAction( facName, self.location ) During this object's construction, terrainArgs is set to a list with values corresponding to a previously created BattleIntentionAction! Even more bizarre, the terrainArgs param is a testing formality, and doesn't actually get used anywhere in my code -- the corresponding attribute is always modified after object creation. Furthermore, this doesn't happen with the other keyword args... Obviously, I'm glossing over a ton of code here, but I'm having a tough time isolating this problem, as it seems to be very dependent on events leading up to it. It feels like the sort of memory stomping bug I remember seeing from days of yore when I hacked C++. :-( I frankly don't understand how "terrainArgs" can have a value if nothing is passed for it on the calling invocation, short of some obscure compiler bug (this is Python 2.4.3). Am I being naive? Is there some way I could be bringing this about myself? I can easily work around this weirdness by having the caller set terrainArgs explicitly, but I can't shake the sensation that this "fix" just masks some deeper flaw in my code. Arg! -Jasper From mail at timgolden.me.uk Thu Aug 28 03:53:52 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 28 Aug 2008 08:53:52 +0100 Subject: calling NetShareEnum win32api with ctypes In-Reply-To: <4f48843b-545b-4c29-91b1-f10de7a563e4@c65g2000hsa.googlegroups.com> References: <4f48843b-545b-4c29-91b1-f10de7a563e4@c65g2000hsa.googlegroups.com> Message-ID: <48B65990.8060809@timgolden.me.uk> taghi wrote: > I want to call NetShareEnum, a function from netapi32.dll Not a straightforward answer but... are you aware that this particular call is already wrapped by the pywin32 packages: https://sourceforge.net/projects/pywin32/ http://timgolden.me.uk/pywin32-docs/win32net__NetShareEnum_meth.html TJG PS Is it me or is SourceForge's latest redesign actually less useful than its last one? From ironfroggy at gmail.com Tue Aug 12 13:33:19 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Tue, 12 Aug 2008 13:33:19 -0400 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: <74583B8642AB8841B30447520659FCA92CBAF3B3@dnce01.ent.ti.com> References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> <200808121311.06892.maric@aristote.info> <74583B8642AB8841B30447520659FCA92CBAF3B3@dnce01.ent.ti.com> Message-ID: <76fd5acf0808121033q42aafd3dned27ab58f1618343@mail.gmail.com> Please re-evaluate your "need" for nesting classes in the first place. On Tue, Aug 12, 2008 at 1:06 PM, Cousson, Benoit wrote: >> This is a language limitation. >> This is because nested scope is implemented for python function only since >> 2.3 >> allow late binding of free variables. the scope in class statment is not a >> closure, so there is only two possible scope in it : local and global. > > That was my understanding as well, but I think it is a pity to have that limitation. Don't you think that the same improvement that was done for method nested scope could be done as well for nested class? > > I can easily fix my current issue by doing the binding after the class declaration. > My concern is more about the lack of symmetry of that approach; meaning that if both classes are in the global scope, one can access the others, whereas if they are in the body of another class they cannot. > > This is OK: > > class A(object): > pass > > class B(object): > foo=A > > > I have to add the binding after the declaration in the case of nested: > > class C(object): > class A(object): > pass > > class B(object): > foo=None > B.foo = A > > That extra step is a little bit painful and should not be necessary for my point of view. > > >> > I'm wondering as well if the new nonlocal statement will fix that in >> py3k? >> > >> >> nonlocal doesn't adress this issue an I doubt python 3.0 fix it at all. >> >> You have the same problem with generator expressions, which bind lately >> outer >> loop variables : > > Good to know, I was not aware of that. > > Thanks, > Benoit > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy From weiguo6 at gmail.com Thu Aug 7 03:19:37 2008 From: weiguo6 at gmail.com (weiguo6 at gmail.com) Date: 7 Aug 2008 08:19:37 +0100 Subject: Horses Message-ID: <200808070720.CTU36540@manxnetsf02.manx.net> Where have all the horses gone? From Nikolaus at rath.org Fri Aug 1 02:04:13 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Fri, 01 Aug 2008 08:04:13 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> <87r69a85ek.fsf@nokile.rath.org> <87fxpq7x41.fsf@nokile.rath.org> Message-ID: <874p658e5e.fsf@nokile.rath.org> Miles writes: > On Thu, Jul 31, 2008 at 1:59 PM, Nikolaus Rath wrote: >> If it is just a matter of different rendering, what's the reason for >> doing it like that? Wouldn't it be more consistent and straightforward >> to denote builtin types as classes as well? > > Yes, and in Python 3, it will be so: > [..] > http://svn.python.org/view?rev=23331&view=rev That makes matters absolutely clear. Thanks a lot. No more questions from my side ;-). Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From sthembilengidi at gmail.com Mon Aug 18 06:16:11 2008 From: sthembilengidi at gmail.com (Amie) Date: Mon, 18 Aug 2008 03:16:11 -0700 (PDT) Subject: HTML Tables Message-ID: <6d0d25a5-4866-44e9-adb7-8772119d1b92@e39g2000hsf.googlegroups.com> Afternoon all. Just want to know how to create html tables using a for loop. I need to display 34 html tables, so I figured a for loop will do. Please show me an example of how to do that. Also how do I display the results of an sql query onto the html tables? Thanks in advance From williambattersea at gmail.com Wed Aug 13 23:16:12 2008 From: williambattersea at gmail.com (Prof. William Battersea) Date: Wed, 13 Aug 2008 23:16:12 -0400 Subject: Using Timer or Scheduler in a Class Message-ID: <97d780f10808132016s3b453765m82bf1784b1f2afb2@mail.gmail.com> I'd like a class method to fire every n seconds. I tried this: class Timed: def.__init__(self): self.t = Timer(3, self.dothing) def.start(self): self.t.start() def.dothing(self): print "Doing Thing" s = new Timed() s.start() And: class Scheduled: def.__init__(self): self.s = sched.scheduler(time.time, time.sleep) self.s.enter(3, 1, self.sync, ()) def.start(self): self.t.start() def.dothing(self): print "Syncing" s = new Scheduled() s.start() Both run once and end. I'm obviously missing something here. Thanks, Justin From pavlovevidence at gmail.com Sat Aug 30 00:24:28 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 29 Aug 2008 21:24:28 -0700 (PDT) Subject: When to use try and except? References: <8a2dd955-6641-493d-b7eb-3e29c14686a5@26g2000hsk.googlegroups.com> <914fde08-5084-455f-ac68-bef7e06cc3dc@i76g2000hsf.googlegroups.com> Message-ID: <00c7058c-2b26-42bf-8f5b-2bebe31b2130@k7g2000hsd.googlegroups.com> On Aug 29, 2:33?pm, "Chris Rebert" wrote: > On Fri, Aug 29, 2008 at 10:56 AM, cnb wrote: > > On Aug 29, 7:40 pm, Daniel wrote: > >> On Aug 29, 11:23 am, cnb wrote: > > >> > If I get zero division error it is obv a poor solution to do try and > >> > except since it can be solved with an if-clause. > > >> > However if a program runs out of memory I should just let it crash > >> > right? Because if not then I'd have to write exceptions everywhere to > >> > prevent that right? > > >> > So when would I actually use try-except? > > >> > If there can be several exceptions and I just want to catch 1 or 2? > >> > Like > >> > try: > >> > ? ? blahaba > >> > except SomeError: > >> > ? ? do something > > >> I'm not sure whay you're trying to do, but I think catching a > >> ZeroDivisionError exception is a good use of try-except. > > >> I'm also not sure that I would say you just let a program crash if it > >> runs out of memory. ?I would think that from the user perspective, you > >> would want to check memory conditions and come up with an exception > >> indicating that some memory threshold has been reached. ?When that > >> exception is raised you should indicate that to the user and exit > >> gracefully. > > > A ZeroDivisionError is better avoided wth an if-clause, don't you > > think? It is a predictable exception... > > Basically, there's a general principle (EAFP: Easier to ask > forgiveness than permission) in Python to just "try" something and > then catch the exception if something goes wrong. This is in contrast > to e.g. C where you're supposed to "Look before you leap" (LBYL) and > check for possible error conditions before performing the operation. I wouldn't say that the possibility of EAFP in Python makes it obsolute to use LBYL. (Error checking seems to be too broad a subject to apply the One Obvious Way maxim to.) C isn't always LBYL anyway; sometimes it's DFTCFE "Don't forget to check for errors". I tend to use EAFP to check if something "wrong" happened (a missing file, invalid input, etc.), and LBYL for expected conditions that can occur with valid input, even when that condition could be tested with a try...except. For instance, I'd write something like this: if x is not None: y = x.calculate_value() else: y = default_value Main reason I do this is to document that None is an expected and valid value for x, and not incidative of a problem. But it's purely a matter of style and neither way is wrong. Carl Banks From brian.lee.hawthorne at gmail.com Tue Aug 12 23:19:10 2008 From: brian.lee.hawthorne at gmail.com (Brian Hawthorne) Date: Tue, 12 Aug 2008 20:19:10 -0700 Subject: Wackness Message-ID: <796269930808122019q697a3657h59b4e95510a9823f@mail.gmail.com> p1 = property(lambda self: self.__x) class Foo (object): p1 = p1 p2 = property(lambda self: self.__x) def __init__(self): self.__x = 10 f = Foo() print f.p2 print f.p1 #------------------------------------------------------- Expecting to see: 10 10 ? Think again! Ouch, just got bit. But I guess the name mangling has to occur at compile (to bytecode) time? Cheers, Brian Hawthorne From martin at v.loewis.de Sun Aug 10 10:05:55 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 10 Aug 2008 16:05:55 +0200 Subject: download limit In-Reply-To: References: Message-ID: <489EF5C3.4040101@v.loewis.de> > I have a multithreaded script that mainly creates several wget > processes to download files. I would like to check/see and eventually > limit the bandwidth of the pool of processes. One way to do this is to > change the number of wget instances, but it's a workaround. > > What do you recommend to do the following in python: > 1) know the bitrate at the script scale > 2) control, and limit or not this bitrate I recommend to not use wget, but implement the network access directly in Python. Then you can easily measure that bitrate, and also limit it. (by having some threads sleep). Once you fork out new processes, you lose, unless there is an operating system bandwidth limitation framework available which works on groups of processes. Solaris project objects may provide such a thing, but apart from that, I don't think it's available in any operating system that you might be using. Regards, Martin From notvalid2 at sbcglobal.net Sat Aug 23 19:11:37 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Sat, 23 Aug 2008 16:11:37 -0700 Subject: Filling in Degrees in a Circle (Astronomy) In-Reply-To: References: Message-ID: tom wrote: > W. eWatson wrote: >> The other night I surveyed a site for astronomical use by measuring >> the altitude (0-90 degrees above the horizon) and az (azimuth, 0 >> degrees north clockwise around the site to 360 degrees, almost north >> again) of obstacles, trees. My purpose was to feed this profile of >> obstacles (trees) to an astronomy program that would then account for >> not sighting objects below the trees. >> >> When I got around to entering them into the program by a file, I found >> it required the alt at 360 azimuth points in order from 0 to 360 (same >> as 0). Instead I have about 25 points, and expected the program to be >> able to do simple linear interpolation between those. >> >> Is there some simple operational device in Python that would allow me >> to create an array (vector) of 360 points from my data by >> interpolating between azimuth points when necessary? All my data I >> rounded to the nearest integer. Maybe there's an interpolation operator? >> >> As an example, supposed I had made 3 observations: (0,0) (180,45) and >> (360,0). I would want some thing like (note the slope of the line from >> 0 to 179 is 45/180 or 0.25): >> alt: 0, 0.25, 0.50, 0.75, ... 44.75, 45.0 >> az : 0, 1, 2, 3, 180 >> >> Of course, I don't need the az. >> > > > If I understand you right, I think using interpolation as provided by > scipy would do what you need. > > Here's an example: > > from scipy.interpolate.interpolate import interp1d > > angles = [0, 22, 47.5, 180, 247.01, 360] > altitudes = [18, 18, 26, 3, 5, 18] > > desired_angles = range(0, 361) > > skyline = interp1d(angles, altitudes, kind="linear") > vals = skyline(desired_angles) > > # that is, vals will be the interpolated altitudes at each of the > # desired angles. > > if 1: # plot this out with matplotlib > import pylab as mx > mx.figure() > mx.plot(angles, altitudes, 'x') > mx.plot(desired_angles, vals) > mx.show() I decided this morning and roll up my sleeves and write the program. I plan to take a deeper plunge in the next month than my so far erratic look over the last 18 or more months It's working. The above looks like it's on the right track. Is scipy some collection of astro programs? mx is a graphics character plot? I just hauled it into IDLE and tried executing it. from scipy.interpolate.interpolate import interp1d ImportError: No module named scipy.interpolate.interpolate Apparently, something is missing. I posted a recent msg a bit higher that will probably go unnoticed, so I'll repeat most of it. How do I get my py code into some executable form so that Win users who don't have python can execute it? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From harrrrpo at gmail.com Sun Aug 24 07:43:57 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Sun, 24 Aug 2008 14:43:57 +0300 Subject: Imports awareness in Imported modules problem In-Reply-To: <702255f9-4bcd-471d-ad06-487cbb62f258@b38g2000prf.googlegroups.com> References: <538050a90808231529s61855330r1ec68048847ef241@mail.gmail.com> <702255f9-4bcd-471d-ad06-487cbb62f258@b38g2000prf.googlegroups.com> Message-ID: <538050a90808240443m71756241pa5e390385f19cb52@mail.gmail.com> On Sun, Aug 24, 2008 at 2:27 PM, alex23 wrote: > On Aug 24, 8:34 pm, "Mohamed Yousef" wrote: >> and sys ,string.. etc add them all twice or four / n times ? >> remove one and then forget to remove one of them in a file and start >> debugging ... this really doesn't look to be a good practice > > No, having each module contain all of the necessary imports for itself > -is- good practice. > > While it might seem more convenient to define all of your imports in > one place, what you're really doing is injecting -all- references to - > all- imported items into -every- module. Having a global soup of > imported items like such is much, much harder to control for > unexpected name conflicts. > > Ideally, you want each module's namespace to -only- contain references > to the external entities it's actually using. This not only makes each > module self-contained and more open to independent re-use, it makes > them -incredibly- easier to debug. > > Please don't confuse temporary convenience with good practice. mm , this seems to be logically or another good behind logic . as PHP already uses that convention -from which i thought python also does - but what about module-wide variables what is the approach to them , will i have to store them in a memory table (SQL) , or keep passing them between objects - which i really hate - From bedouglas at earthlink.net Fri Aug 29 11:17:32 2008 From: bedouglas at earthlink.net (bruce) Date: Fri, 29 Aug 2008 08:17:32 -0700 Subject: python/mechanize - redirect/refresh question Message-ID: <0a6301c909ea$5d862740$0301a8c0@tmesa.com> Hi. I'm using mechanize to parse a page/site that uses the meta http-equiv tag in order to perform a refresh/redirect of the page. I've tried a number of settings, and read different posts on various threads, but seem to be missing something. the test.html page is the page that the url returns, however, i was expecting the test.py app to go ahead and perform the redirect/refresh automatically. does the page (test.html) need to be completely valid html? Any thoughts on what's screwed up here?? thanks ---------------------------------------------------- test.py -------- import re import libxml2dom import urllib import urllib2 import sys, string from mechanize import Browser import mechanize #import tidy import os.path import cookielib from libxml2dom import Node from libxml2dom import NodeList import subprocess import time ######################## # # Parse pricegrabber.com ######################## cj = "p" COOKIEFILE = 'cookies.lwp' #cookielib = 1 urlopen = urllib2.urlopen #cj = urllib2.cookielib.LWPCookieJar() cj = cookielib.LWPCookieJar() Request = urllib2.Request br = Browser() br2 = Browser() if cj != None: print "sss" #install the CookieJar for the default CookieProcessor if os.path.isfile(COOKIEFILE): cj.load(COOKIEFILE) print "foo\n" if cookielib: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) print "foo2\n" user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values1 = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } url="http://schedule.psu.edu/" #======================================= if __name__ == "__main__": # main app txdata = None #---------------------------- ##br.set_cookiejar(cj) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.set_handle_refresh(True) br.addheaders = [('User-Agent', 'Firefox')] #url=str(url)+str("act_main_search.cfm")+"?" #url=url+"Semester=FALL%202008%20%20%20&" #url=url+"CrseLoc=OZ%3A%3AAbington%20Campus&" #url=url+"CECrseLoc=AllOZ%3A%3AAbington%20Campus&" #url=url+"CourseAbbrev=ACCTG&CourseNum=&CrseAlpha=&Search=View+schedule" #url="http://schedule.psu.edu/act_main_search.cfm?Semester=FALL%202008%20%20 %20%20&CrseLoc=OZ%3A%3AAbington%20Campus&CECrseLoc=AllOZ%3A%3AAbington%20Cam pus&CourseAbbrev=ACCTG&CourseNum=&CrseAlpha=" url="http://schedule.psu.edu/act_main_search.cfm?Semester=FALL%202008%20%20% 20%20&CrseLoc=OZ%3A%3AAbington%20Campus&CECrseLoc=AllOZ%3A%3AAbington%20Camp us&CourseAbbrev=ACCTG&CourseNum=&CrseAlpha=&CFID=543143&CFTOKEN=71842529" print "url =",url br.open(url) #cj.save(COOKIEFILE) # resave cookies res = br.response() # this is a copy of response s = res.read() print "slen=",len(s) print s ========================================= test.html Tech Type --------------------------------------------------------- sys.exit() From dudeja.rajat at gmail.com Tue Aug 19 06:11:56 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 19 Aug 2008 11:11:56 +0100 Subject: WindowsXP / CTypes Module - unable to access function in a dll In-Reply-To: References: Message-ID: On Tue, Aug 19, 2008 at 11:04 AM, wrote: > Hi, > > I'm using the CTYPES module of python to load a dll. My dll contains a > Get_Version function as: > long __stdcall af1xEvdoRDll_GetVersion(long version[4]); > > This function accepts a long array of 4 elements. > > Following is the python code I've written: > > from ctypes import * > abc = windll.af1xEvdoRDll > GetVersion = abc.af1xEvdoRDll_GetVersion > print GetVersion > versionArr = c_long * 4 #array of 4 longs > version = versionArr(0, 0, 0, 0) # initializing all elements to 0 > GetVersion(version) #calling dll function > print version > > I'm getting the following output: > <_FuncPtr object at 0x00A1EB70> > <__main__.c_long_Array_4 object at 0x00A86300> > > But I'm not getting the desired output which I expect as : 2.1.5.0 > > > Please suggest what am I missig? > Sorry, the problem is resolved. The code in fact is correct and I got the right answers. It is just that I was not priting results in a right manner. I added : print i in version : print i this solved my problem. Cheers. From cwitts at gmail.com Mon Aug 11 09:17:49 2008 From: cwitts at gmail.com (Chris) Date: Mon, 11 Aug 2008 06:17:49 -0700 (PDT) Subject: if len(str(a)) == len(str(r)) and isMult(a, r): faster if isMult is slow? References: Message-ID: <2c2f6222-9326-44fe-a66b-b78e4b1c5ee6@x41g2000hsb.googlegroups.com> On Aug 11, 3:03?pm, maestro wrote: > If isMult is slow then: > > if len(str(a)) == len(str(r)) and isMult(a, r): > ? ? ? ? ? ? ? ? trues.append((a, r)) > > will be much faster than: > > if isMult(a, r) and len(str(a)) == len(str(r)): > ? ? ? ? ? ? ? ? trues.append((a, r)) > > right? seems obvious ?but there is no magic going on that wouldn't > make this true right? Once a failed condition is met the rest are skipped for evaluation. Whether or not that saves you any reasonable amount of time would be up to the various tests being used with your conditions. If your function isMult is just doing the same work as "if not a % r" then that would be faster than casting your integers/floats to a string and testing their length imo. You could always go through the trouble of profiling your code with separate if statements to see how much time is spent on each, also note your mean failure rate for each conditional test and then decide for yourself which to place first. Hope that helps, Chris From steve at REMOVE-THIS-cybersource.com.au Wed Aug 20 09:24:59 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2008 13:24:59 GMT Subject: exception handling in complex Python programs References: Message-ID: <00bc1604$0$20315$c3e8da3@news.astraweb.com> On Tue, 19 Aug 2008 22:24:45 -0700, eliben wrote: > """ between file() > and open() in Python 2 and 3, a NameError is thrown with open() in > Python 3 and an IOError is thrown in the other three cases against keyboard>. > """ I'm curious about the claim that open() will raise NameError in Python3. I find it hard to credit that claim, but if it is correct, what's the justification for that? > This is *exactly* my concern with Python exceptions. You just never know > what can be thrown at you. It's true that documentation of exceptions is relatively weak in Python. And some functions can raise a bewildering array of exceptions. See for example this thread where somebody notes that urllib2.urlopen() can raise any of six different exceptions: http://mail.python.org/pipermail/baypiggies/2008-April/003187.html And I've had it raise socket.error, which makes seven. And the documentation only mentions one of those exceptions. However, as Gregory Smith describes, some of those seven exceptions are subclasses of others, so it is possible to reduce it down to three cases -- and arguably one of those cases (ValueError) is a bug that needs fixing, not an exception that needs catching. That's probably as bad as it gets in Python, at least for the standard library. Most functions don't raise arbitrary exceptions for sensible data, and if you pass non-sensible data then you should treat the exception as a bug in your code and fix it. -- Steven From toby at tobiah.org Wed Aug 6 12:20:35 2008 From: toby at tobiah.org (Tobiah) Date: Wed, 06 Aug 2008 09:20:35 -0700 Subject: regex question References: <6fqqovFcq6bmU1@mid.uni-berlin.de> Message-ID: On Tue, 05 Aug 2008 15:55:46 +0100, Fred Mangusta wrote: > Chris wrote: > >> Doesn't work for his use case as he wants to keep periods marking the >> end of a sentence. Doesn't it? The period has to be surrounded by digits in the example solution, so wouldn't periods followed by a space (end of sentence) always make it through? ** Posted from http://www.teranews.com ** From theller at python.net Fri Aug 29 17:49:44 2008 From: theller at python.net (Thomas Heller) Date: Fri, 29 Aug 2008 23:49:44 +0200 Subject: ctypes version mismatch In-Reply-To: References: Message-ID: <6hr97oFnqkdgU1@mid.individual.net> Paul McNett schrieb: > Anyone have anything to suggest on this error: > > {{{ > Traceback (most recent call last): > File "shutter_studio.py", line 41, in > File "App.pyo", line 25, in > File "ui\__init__.pyo", line 23, in > File "ui\FrmProductionOrders.pyo", line 10, in > File "ui\PagEditProductionOrders.pyo", line 8, in > File "ui\GrdProductionOrderOpenings.pyo", line 5, in > File "ui\DlgEditProductionOrderOpening.pyo", line 17, in > File "ui\ShutterCanvas.pyo", line 9, in > File "wx\lib\floatcanvas\FloatCanvas.pyo", line 6, in > File "numpy\__init__.pyo", line 46, in > File "numpy\ctypeslib.pyo", line 9, in > File "ctypes\__init__.pyo", line 20, in > Exception: ('Version number mismatch', '1.0.2', '1.0.3') > }}} > > I just updated from python 2.5.1 to 2.5.2, and wxPython 2.8.7.1 to > 2.8.8.1. The issue is only in the py2exe-built app, not when running the > script from the command line. I guess you should remove the build and dist directories and rebuild your app - this is always a good idea when something goes wrong, not only after upgrading Python or Python packages. Thomas From nadeemabdulhamid at gmail.com Fri Aug 15 23:17:12 2008 From: nadeemabdulhamid at gmail.com (Nadeem) Date: Fri, 15 Aug 2008 20:17:12 -0700 (PDT) Subject: Dynamically defined functions via exec in imported module References: <036d8731-5984-4c23-a15d-efe7e01b5d07@x35g2000hsb.googlegroups.com> Message-ID: Well, I found one hack that seems to achieve this by accessing the globals() dictionary of the outermost stack frame and adding an entry to it for the newly created functions: import inspect def dynamicdef(name, amt): '''Dynamically defines a new function with the given name that adds the given amt to its argument and returns the result.''' stm = "def %s(x):\n\treturn x + %d" % (name, amt) print stm exec stm in globals() ## ADDED THIS TO EXPORT THE NEW FUNCTION NAME TO THE TOP LEVEL... inspect.stack()[-1][0].f_globals[name] = eval(name) I guess I'll go with this unless someone suggests an alternate. Thanks anyway, :) --- nadeem From victorsubervi at gmail.com Tue Aug 12 12:04:05 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 12 Aug 2008 18:04:05 +0200 Subject: Cutting and Pasting in Windows IDLE Message-ID: <4dc0cfea0808120904o507da4tdf855e01994802ff@mail.gmail.com> Hi; A couple of weeks ago I asked how to cut and paste multiple lines in the Windows IDLE interface. I can only paste one line at a time! Frustrating. I want it to work like my Linux interpreter. Why doesn?t it? Please help. Someone wrote this, which did not help at all: Well, I'm not really sure what to say. I've just copied that whole section with drag-mouse, Ctrl-C. I then opened a new interpreter window (effectively, Start > Run > python) and right-clicked over the window. At this point, the lines I copied were copied in and the function accepted by the interpreter. I do have QuickEdit on by default in all by console windows, but the only difference I expect that to make is that you'd otherwise have to use the window's System Menu (Alt-Space, Edit, Paste). TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From piyush.chechani at tcs.com Fri Aug 1 03:54:34 2008 From: piyush.chechani at tcs.com (Piyush Chechani) Date: Fri, 1 Aug 2008 13:24:34 +0530 Subject: Sharing common memory space (In form of List) across the python processes. Message-ID: Hi, I am working on a module where I need to share contents of a big List across the processes. I am using socket programming concept for this. My current processing for this is as follows: - 1. There is a server program S which loads the list in the memory, and listens on a particular port, 2. All the other programs which want to access that list sends a request on that server port, 3. Server sends the id of the memory loaded list element to the requesting process. Here I am getting a problem in the reverse function of id(), as my client should get the list object using its id but I don't know the python function for doing this. Please help me in solving this problem, also if you have any other more robust solution for this processing then please share that. Thanks in advance. Piyush. =====-----=====-----===== Notice: The information contained in this e-mail message and/or attachments to it may contain confidential or privileged information. If you are not the intended recipient, any dissemination, use, review, distribution, printing or copying of the information contained in this e-mail message and/or attachments to it are strictly prohibited. If you have received this communication in error, please notify us by reply e-mail or telephone and immediately and permanently delete the message and any attachments. Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From gminick at nie.ma.takiego.adresu.w.sieci.pl Sun Aug 10 10:21:27 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Sun, 10 Aug 2008 14:21:27 +0000 (UTC) Subject: My very first python program, need help References: <6g8a56FenevdU1@mid.individual.net> Message-ID: Dnia Sun, 10 Aug 2008 15:52:37 +0200, WP napisa?(a): Hi, > import re > > def calculate_sum_1(str): ^^^ this word is reserved, better use some other name > for c in str: > if c.isdigit() == False and c != ' ': > # That we assign to the variable we're looping over worries > me... > str = str.replace(c, ' ') It's good that it worries you. AFAIR python behavior when assigning to a variable that is used in for loop is undefined, so you can't count on it. Better introduce second variable. > > mylist = str.split() > > print "(for loop version) mylist after replace() and split() = ", > mylist > > sum = 0 > > for item in mylist: > sum += long(item) You could use list comprehensions and sum function in here. > def calculate_sum_2(str): > #print "In replace_nondigits_2(), str = ", str > p = re.compile('[^0-9]') or: p = re.compile('\d+') '\d+' is for one or more digits > mylist = p.split(str) You don't have to split this string. Just search through it. Findall method seems appropriate. A bit more pythonic approaches to both of your functions: ======================= import re a="123xx,22! p1" # Note that 'string' isn't the best name too. It may be shadowed by # or shadow 'string' module if it's imported. def calculate_sum_1(string): result = '' for i in string: if i.isdigit(): result += i else: result += ' ' return sum([int(i) for i in result.split()]) def calculate_sum_2(string): pat = re.compile('\d+') digits = [int(i) for i in re.findall(pat, string)] return sum(digits) print calculate_sum_1(a) print calculate_sum_2(a) =========================== -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From bdesth.quelquechose at free.quelquepart.fr Fri Aug 15 11:29:17 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 15 Aug 2008 17:29:17 +0200 Subject: negative numbers are not equal... In-Reply-To: References: Message-ID: <48a5bcc0$0$4514$426a74cc@news.free.fr> castironpi a ?crit : (snip) > It would be nice to put together a really canonical case of the use of > the 'is' comparison. FTSOA for the sake of argument, when do you use > it? When I want to test objects identity. An idenity test is an identity test is an identity test is an.... > Why is it even in the language? Because there's a need for it. From rurpy at yahoo.com Thu Aug 28 09:56:34 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Thu, 28 Aug 2008 06:56:34 -0700 (PDT) Subject: How to ignore the first line of the text read from a file References: <6hmqenFmpekqU1@mid.uni-berlin.de> Message-ID: On Aug 27, 11:12 pm, Marc 'BlackJack' Rintsch wrote: > On Wed, 27 Aug 2008 21:11:26 -0700, youngjin.mich... at gmail.com wrote: > > I want to read text line-by-line from a text file, but want to ignore > > only the first line. I know how to do it in Java (Java has been my > > primary language for the last couple of years) and following is what I > > have in Python, but I don't like it and want to learn the better way of > > doing it. > > > file = open(fileName, 'r') > > lineNumber = 0 > > for line in file: > > if lineNumber == 0: > > lineNumber = lineNumber + 1 > > else: > > lineNumber = lineNumber + 1 > > print line > > > Can anyone show me the better of doing this kind of task? > > input_file = open(filename) > lines = iter(input_file) > lines.next() # Skip line. > for line in lines: > print line > input_file.close() > > Ciao, > Marc 'BlackJack' Rintsch A file object is its own iterator so you can do more simply: input_file = open(filename) input_file.next() # Skip line. for line in input_file: print line, input_file.close() Since the line read includes the terminating EOL character(s), print it with a "print ... ," to avoid adding an additional EOL. If the OP needs line numbers elsewhere in the code something like the following would work. infile = open(fileName, 'r') for lineNumber, line in enumerate (infile): # enumerate returns numbers starting with 0. if lineNumber == 0: continue print line, From davidreynon at gmail.com Thu Aug 14 11:35:15 2008 From: davidreynon at gmail.com (korean_dave) Date: Thu, 14 Aug 2008 08:35:15 -0700 (PDT) Subject: for y in range (0,iNumItems)--> not in order? References: <8514d915-95bf-4e57-a16a-68866e0ad789@l42g2000hsc.googlegroups.com> Message-ID: Still the same output... Here's the actual code... for x in range(0,2): for y in range(0,27): for z in range(0,15): print(str(x) + " " + str(y) + " " + str(z)) From nodrogbrown at gmail.com Sat Aug 30 13:56:27 2008 From: nodrogbrown at gmail.com (gordon) Date: Sat, 30 Aug 2008 10:56:27 -0700 (PDT) Subject: Tkinter event loop question References: <9eaef6c3-c913-497f-8ca2-0466eb178c7a@z6g2000pre.googlegroups.com> <759a12fe-75c8-429a-9a64-19dc73a0b779@b30g2000prf.googlegroups.com> Message-ID: <3e350b67-4114-4ce4-9414-e476ae0b0de1@k36g2000pri.googlegroups.com> On Aug 29, 10:46 pm, "Russell E. Owen" wrote: you > can safely compute stuff with a background thread and display it from> the main thread). But cross that bridge later.> > -- Russell thanks Russel gordon From tjreedy at udel.edu Thu Aug 7 14:58:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 07 Aug 2008 14:58:41 -0400 Subject: benchmark In-Reply-To: References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> Message-ID: M8R-n7vorv at mailinator.com wrote: > Is there any reason why the psyco is not a part of the core python > feature set ? Psyco was a PhD project. I do not believe the author ever offered it. Last I knew, it was almost but not completely compatible. > Is there a particular reason it is better to be kept as > a separate extension ? If he did, he would have to commit to updating it to work with new version of Python (2.6/3.0) which I don't believe he wants to do. Last I know, he was working with the PyPy project instead and its JIT technology. On the otherhand, extensions are also restricted by Python's release schedule, including no new features in bug-fix (dot-dot) releases. So library extensions need to be rather stable but maintained. > Are there any implications of using psyco ? It compiles statements to machine code for each set of types used in the statement or code block over the history of the run. So code used polymorphically with several combinations of types can end up with several compiled versions (same as with C++ templates). (But a few extra megabytes in the running image is less of an issue than it was even 5 or so years ago.) And time spent compiling for a combination used just once gains little. So it works best with numeric code used just for ints or floats. Terry J. Reedy From gminick at nie.ma.takiego.adresu.w.sieci.pl Thu Aug 14 07:22:55 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Thu, 14 Aug 2008 11:22:55 +0000 (UTC) Subject: Replace Several Items References: <513926b0-64fe-4fdc-bb33-bc4b8ad3ab10@a70g2000hsh.googlegroups.com> <00b38b78$0$14351$c3e8da3@news.astraweb.com> Message-ID: On 14 Aug 2008 01:54:55 GMT, Steven D'Aprano wrote: >>>> I don't have to, I can anticipate the results. >>> >>> Chances are that you're wrong. >> >> At the moment my average is about 0.75 of mistake per post on >> comp.lang.python (please, bare with me ;-)). I strongly believe that the >> statement I made above won't make this number rise. > Okay, is this going to be one of those things where, no matter what the > benchmarks show, you say "I was right, I *did* anticipate the results. I > just anticipated them correctly/incorrectly."? Don't count on it. I never really cared about being right or wrong and I am not one of those guys who are trying to prove something that actually makes no difference at all. Nice tests, though :) -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From castironpi at gmail.com Thu Aug 7 17:08:37 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 7 Aug 2008 14:08:37 -0700 (PDT) Subject: Fastest way to store ints and floats on disk References: Message-ID: <041395eb-f6c2-4fe6-9dc9-e75068951a1b@j7g2000prm.googlegroups.com> On Aug 7, 1:41?pm, Laszlo Nagy wrote: > ? Hi, > > I'm working on a pivot table. I would like to write it in Python. I > know, I should be doing that in C, but I would like to create a cross > platform version which can deal with smaller databases (not more than a > million facts). > > The data is first imported from a csv file: the user selects which > columns contain dimension and measure data (and which columns to > ignore). In the next step I would like to build up a database that is > efficient enough to be used for making pivot tables. Here is my idea for > the database: > > Original CSV file with column header and values: > > "Color","Year","Make","Price","VMax" > Yellow,2000,Ferrari,100000,254 > Blue,2003,Volvo,50000,210 > > Using the GUI, it is converted to this: > > dimensions = [ > ? ? { 'name':'Color', 'colindex:0, 'values':[ 'Red', 'Blue', 'Green', > 'Yellow' ], }, > ? ? { 'name':'Year', colindex:1, 'values':[ > 1995,1999,2000,2001,2002,2003,2007 ], }, > ? ? { 'name':'Make', colindex:2, 'value':[ 'Ferrari', 'Volvo', 'Ford', > 'Lamborgini' ], }, > ] > measures = [ > ? ? { 'name', 'Price', 'colindex':3 }, > ? ? { 'name', 'Vmax', 'colindex':4 }, > ] > facts = [ > ? ? ( (3,2,0),(100000.0,254.0) ?), # ( dimension_value_indexes, > measure_values ) > ? ? ( (1,5,1),(50000.0,210.0) ), > ? ?.... # Some million rows or less > ] > > The core of the idea is that, when using a relatively small number of > possible values for each dimension, the facts table becomes > significantly smaller and easier to process. (Processing the facts would > be: iterate over facts, filter out some of them, create statistical > values of the measures, grouped by dimensions.) > > The facts table cannot be kept in memory because it is too big. I need > to store it on disk, be able to read incrementally, and make statistics. > In most cases, the "statistic" will be simple sum of the measures, and > counting the number of facts affected. To be effective, reading the > facts from disk should not involve complex conversions. For this reason, > storing in CSV or XML or any textual format would be bad. I'm thinking > about a binary format, but how can I interface that with Python? > > I already looked at: > > - xdrlib, which throws me DeprecationWarning when I store some integers > - struct which uses format string for each read operation, I'm concerned > about its speed > > What else can I use? > > Thanks, > > ? ?Laszlo Take a look at the mmap module. You get direct memory access, backed by the file system. struct + mmap, if you keep your strings small? From gnewsg at gmail.com Sat Aug 2 14:11:25 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sat, 2 Aug 2008 11:11:25 -0700 (PDT) Subject: Searching for some kind of data type References: <33d13c77-e710-4951-a559-7ea8b6e15287@26g2000hsk.googlegroups.com> Message-ID: <5c1ae2a0-ed85-41a7-afca-4e5d29e1eafb@e53g2000hsa.googlegroups.com> On 2 Ago, 18:18, Gary Herron wrote: > Larry Bates wrote: > > Giampaolo Rodola' wrote: > >> Hi, > >> for an FTP server I wrote I'd need to group the FTP commands in one > >> table that defines the command itself, the syntax string, required > >> permission, whether it requires authorization, whether it takes > >> argument and whether there's a need to validate the path from the > >> argument. > >> The more obvious way I found to do that is something like this: > > >> class CommandProperty: > >> ? ? def __init__(self, perm, auth_needed, arg_needed, check_path, > >> syntax): > >> ? ? ? ? self.perm = perm > >> ? ? ? ? self.auth_needed = auth_needed > >> ? ? ? ? self.arg_needed = arg_needed > >> ? ? ? ? self.check_path = check_path > >> ? ? ? ? self.syntax = syntax > > >> ftp_cmds = { > >> ? ? "ABOR" : CommandProperty(perm=None, auth_needed=True, > >> arg_needed=False, check_path=False, syntax="ABOR (abort transfer)."), > >> ? ? "APPE" : CommandProperty(perm='a', ?auth_needed=True, > >> arg_needed=True, ?check_path=True, ?syntax="APPE file-name > >> (append data to an existent file)."), > >> ? ? "CDUP" : CommandProperty(perm='e', > >> auth_needed=True,arg_needed=False, check_path=False, syntax="CDUP (go > >> to parentdirectory)."), > >> ? ? ... > >> ? ? ... > >> ? ? ... > >> ? ? } > > >> ...but I find it somewhat redundant and... "ugly". > >> I was wondering if there was some kind of data type which could better > >> fit such purpose or if someone could suggest me some other approach to > >> do this same thing. Maybe using a dictionary is not the better choice > >> here. > > >> Thanks in advance > > >> --- Giampaolo > >>http://code.google.com/p/pyftpdlib/ > > > Seems completely reasonable to me. ?You might just consider using > > keyword arguments in the __init__ method and eliminate the dictionary > > altogether. > > > Not tested, but you will get the idea: > > > class CommandProperty: > > ? ? def __init__(self, perm = perm, auth_needed = True, arg_needed = > > True, > > ? ? ? ? ? ? ? ? ?check_path = False, syntax = syntax): > > > ? ? ? ? self.perm = perm > > ? ? ? ? self.auth_needed = auth_needed > > ? ? ? ? self.arg_needed = arg_needed > > ? ? ? ? self.check_path = check_path > > ? ? ? ? self.syntax = syntax > > > ftpCommands = dict( > > ? ? ABOR = CommandProperty(perm = None, arg_needed = False, > > ? ? ? ? ? ? ?syntax="ABOR (abort transfer)."), > > ? ? APPE = CommandProperty(perm = 'a', ?check_path=True, > > ? ? ? ? ? ? ?syntax = "APPE file-name (append data to" \ > > ? ? ? ? ? ? ? ? ? ? ? "an existent file)."), > > ? ? CDUP = CommandProperty(perm= 'e', arg_needed = False, > > ? ? ? ? ? ? ?syntax="CDUP (go> to parentdirectory)."), > > ... > > ... > > ... > > ? ? ) > > How does this strike you? ? ?With care, the comment and the table could > be kept aligned and nicely readable > > cmd_data = dict( > ?# cmd = (perm, auth, ? arg, path, ? syntax), > ?ABOR = (None, False, False, False, "ABOR (abort transfer)."), > ?APPE ?= (None, False, False, True, ?"APPE file-name (append data to"), > ?... > ] > > ftpCommands = {} > for cmd,args in cmd_data.iteritems(): > ? ? ftpCommands[cmd] = CommandProperty(*args) > > Gary Herron > > > > > > > IMHO this is a "little" easier to manage because you can take > > advantage of the default values for keyword arguments to eliminate > > some of the arguments. > > > Hope this helps, > > Larry > > -- > >http://mail.python.org/mailman/listinfo/python-list- Nascondi testo citato > > - Mostra testo citato -- Nascondi testo citato > > - Mostra testo citato - Thanks, I didnt' know dict() could be used with =. I think I'm going to use this solution. --- Giampaolo http://code.google.com/p/pyftpdlib/ From larry.bates at websafe.com` Wed Aug 13 00:43:36 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 12 Aug 2008 23:43:36 -0500 Subject: Random Problems In-Reply-To: References: Message-ID: Lanny wrote: > Well the othe day I was making a program to make a list of all the songs in > certian directorys but I got a problem, only one of the directorys was added > to the list. Heres my code: > > import random > import os > import glob > > songs = glob.glob('C:\Documents and Settings\Admin\My > Documents\LimeWire\Saved\*.mp3') > asongs = glob.glob('C:\Documents and Settings\Admin\My > Documents\Downloads\*\*.mp3') > songs.append(asongs) > asongs = glob.glob('C:\Documents and Settings\Admin\My > Documents\Downloads\*\*\*.mp3') > songs.append(asongs) > asongs = glob.glob('C:\Documents and Settings\Admin\My > Documents\Downloads\*\*\*\*.mp3') > songs.append(asongs) > pick = random.choice(songs) > > all goes well but pick awalys is from the first directory but songs awalys > includes all the files I want it to. Im baffaled. > > > > > -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- > 1) You need to either use raw string for your pathnames or use forward slashes. This is because backslash is an escape character to Python and if you get any legal escaped sequence (like \n, \t, etc) it won't work as expected. songs = glob.glob(r'C:\Documents and Settings\Admin\My Documents\LimeWire\Saved\*.mp3') or songs = glob.glob('C:/Documents and Settings/Admin/My Documents/LimeWire/Saved/*.mp3') Yes, forward slashes work just fine on windows. 2) When you have a list (songs) and append another list (asongs) you don't get a combined list, you get a list with the last element being the second list. example: >>> songs = [1,2,3] >>> asongs = [4,5,6] >>> songs.append(asongs) >>> songs [1, 2, 3, [4, 5, 6]] >>> What you wanted was songs.extend(asongs). BTW-Inserting a couple of print statements would have shown you this problem pretty quickly. -Larry From deets at nospam.web.de Fri Aug 29 06:01:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 29 Aug 2008 12:01:05 +0200 Subject: problem with execv command References: Message-ID: <6hpvnoFng7vhU1@mid.uni-berlin.de> dudeja.rajat at gmail.com wrote: > Hi, > > I'm facing problem with the execv command: > > my command is : > os.execv(' C:\Program Files\Subversion\bin\svn ', ( 'list', ' \" > http://subversion.stv.abc.com/svn/Eng \" ' ) ) > > The error I'm getting is : > OSError: [Errno 22] Invalid argument > > > I tried using a variable for http path but still I'm getting the same > error > > Please help. You need to either escape the backslashes in your path using \\, or use python raw string literals like this: r"C:\foo" or use forward-slashes, which windows accepts as well. Diez From kem1723 at yahoo.com Sun Aug 24 20:59:19 2008 From: kem1723 at yahoo.com (Kevin McKinley) Date: Sun, 24 Aug 2008 17:59:19 -0700 (PDT) Subject: Hide Console Message-ID: <300236.79697.qm@web83915.mail.sp1.yahoo.com> When I use py2exe to convert Python script to executable Windows programs I always have a black console pop up behind my program. If i run the script before i convert it with py2exe it don't have the console because i save the script ending with .pyw instead of .py. Is there a way to get rid or hide this console once i've turned it into a executable windows program? Thanks you Kevin McKinley From alexandru.palade at sellerengine.com Tue Aug 12 04:54:14 2008 From: alexandru.palade at sellerengine.com (Alexandru Palade) Date: Tue, 12 Aug 2008 11:54:14 +0300 Subject: Looking out a module for Subversion In-Reply-To: References: Message-ID: <48A14FB6.4020009@sellerengine.com> As for the open source IDE you can always try Eclipse with PyDev extension. Dudeja, Rajat wrote: > Hi, > > I'm new to Python. I only have read "Byte of Python" by Swaroop C H just > to be familiar with sytax of python. I've installed Python 2.5 from > Active State and using its PythonWin Editor / interpreter. This, > unfortunaltely, does not help in debugging. > > I'm looking for an open source IDE / editor that has source level > debugging. Please suggest some tool. > > I'm intending to write a testing tool that uses Subversion. Is there > some module available for subversion, out of the box, that I can import > in my script? > > Regards, > Rajat > > Notice: This e-mail is intended solely for use of the individual or entity to which it is addressed and may contain information that is proprietary, privileged, company confidential and/or exempt from disclosure under applicable law. If the reader is not the intended recipient or agent responsible for delivering the message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If this communication has been transmitted from a U.S. location it may also contain data subject to the International Traffic in Arms Regulations or U.S. Export Administration Regulations and cannot be disseminated, distributed or copied to foreign nationals, residing in the U.S. or abroad, without the prior approval of the U.S. Department of State or appropriate export licensing authority. If you have received this communication in error, please notify the sender by reply e-mail or collect telephone call and de! > lete or destroy all copies of this e-mail message, any physical copies made of this e-mail message and/or any file attachment(s). > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From iainking at gmail.com Wed Aug 27 10:20:34 2008 From: iainking at gmail.com (Iain King) Date: Wed, 27 Aug 2008 07:20:34 -0700 (PDT) Subject: use of Queue References: Message-ID: <0ef4ba3b-1667-4ba4-994c-6efb5180d0cb@l42g2000hsc.googlegroups.com> On Aug 27, 1:17 pm, Alexandru Mosoi wrote: > On Aug 27, 12:45 pm, Alexandru Mosoi wrote: > > > > > how is Queue intended to be used? I found the following code in python > > manual, but I don't understand how to stop consumers after all items > > have been produced. I tried different approaches but all of them > > seemed incorrect (race, deadlock or duplicating queue functionality) > > > def worker(): > > while True: > > item = q.get() > > do_work(item) > > q.task_done() > > > q = Queue() > > for i in range(num_worker_threads): > > t = Thread(target=worker) > > t.setDaemon(True) > > t.start() > > > for item in source(): > > q.put(item) > > > q.join() # block until all tasks are done > > ok. I think I figured it out :). let me know what you think > > global num_tasks, num_done, queue > num_tasks = 0 > num_done = 0 > queue = Queue() > > # producer > num_tasks += 1 > for i in items: > num_tasks += 1 > queue.put(i) > > num_tasks -= 1 > if num_tasks == num_done: > queue.put(None) > > # consumer > while True: > i = queue.get() > if i is None: > queue.put(None) > break > > # do stuff > > num_done += 1 > if num_done == num_tasks: > queue.put(None) > break Are you sure you want to put the final exit code in the consumer? Shouldn't the producer place a None on the queue when it knows it's finished? The way you have it, the producer could make 1 item, it could get consumed, and the consumer exit before the producer makes item 2. Iain From castironpi at gmail.com Sat Aug 23 20:51:01 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 23 Aug 2008 17:51:01 -0700 (PDT) Subject: property() usage - is this as good as it gets? References: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> Message-ID: On Aug 22, 11:18 am, David Moss wrote: > Hi, > > I want to manage and control access to several important attributes in > a class and override the behaviour of some of them in various > subclasses. > > Below is a stripped version of how I've implemented this in my current > bit of work. > > It works well enough, but I can't help feeling there a cleaner more > readable way of doing this (with less duplication, etc). > > Is this as good as it gets or can this be refined and improved > especially if I was to add in a couple more attributes some fairly > complex over-ride logic? > > #!/usr/bin/env python > > class A(object): > def __init__(self): > self._x = None > self._y = None > > def _set_x(self, value): > self._x = value > > def _get_x(self): > return self._x > > x = property(_get_x, _set_x) > > def _set_y(self, value): > self._y = value > > def _get_y(self): > return self._y > > y = property(_get_y, _set_y) To the OP: you have a unique procedure executed for every attribute of an instance, for each of set, get, and del. That's a lot of code. If you don't want unique procedures, what patterns should they follow? What is wrong with the way you overrode 'get_x' above? When brainstorming, don't restrict yourself to Python syntax-- make something up, and we'll write Python. From fredrik at pythonware.com Wed Aug 13 04:33:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Aug 2008 10:33:13 +0200 Subject: python tr equivalent (non-ascii) In-Reply-To: <552ee625-5d07-4f37-958f-abe046cdff3d@v1g2000pra.googlegroups.com> References: <552ee625-5d07-4f37-958f-abe046cdff3d@v1g2000pra.googlegroups.com> Message-ID: kettle wrote: > I was wondering how I ought to be handling character range > translations in python. > > What I want to do is translate fullwidth numbers and roman alphabet > characters into their halfwidth ascii equivalents. > In perl I can do this pretty easily with tr: > > tr/\x{ff00}-\x{ff5e}/\x{0020}-\x{007e}/; > > and I think the string.translate method is what I need to use to > achieve the equivalent in python. Unfortunately the maktrans method > doesn't seem to accept character ranges and I'm also having trouble > with it's interpretation of length. What I came up with was to first > fudge the ranges: > > my_test_string = u"???????" > f_range = "".join([unichr(x) for x in > range(ord(u"\uff00"),ord(u"\uff5e"))]) > t_range = "".join([unichr(x) for x in > range(ord(u"\u0020"),ord(u"\u007e"))]) > > then use these as input to maketrans: > my_trans_string = > my_test_string.translate(string.maketrans(f_range,t_range)) > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode characters in position > 0-93: ordinal not in range(128) maketrans only works for byte strings. as for translate itself, it has different signatures for byte strings and unicode strings; in the former case, it takes lookup table represented as a 256-byte string (e.g. created by maketrans), in the latter case, it takes a dictionary mapping from ordinals to ordinals or unicode strings. something like lut = dict((0xff00 + ch, 0x0020 + ch) for ch in range(0x80)) new_string = old_string.translate(lut) could work (untested). From sjmachin at lexicon.net Mon Aug 4 06:19:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 4 Aug 2008 10:19:27 +0000 (UTC) Subject: xlrd References: Message-ID: Yeats uol.com.br> writes: > > > Hi, > > Years ago i use xlrd to read data from > excel and now I need again, but i get strange result. The code is: > > from xlrd import * > > Planilha = > open_workbook('C:\\Resultados.xls')Resultados = > Planilha.sheet_by_name('Resultados')c = > (Resultados.cell_value(2,2))print c So that's cell_value(rowx=2, colx=2). colx=2 translates to column C on your screen. rowx=2 translates to row 3 on your screen. What does cell C3 show on your screen when you use Excel? > > and the result is: 0, but the value in > cell is : VERDADEIRO And in what cell is VERDADEIRO on your screen? By the way, it's usually a good idea to say what version of Windows, Python and xlrd that you are using. It's also usually a good idea to check the README file for a third-party module or package to find out where it is suggested that you ask questions ... the answer is rarely comp.lang.python. Cheers, John [xlrd author] From bearophileHUGS at lycos.com Tue Aug 5 13:14:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 5 Aug 2008 10:14:11 -0700 (PDT) Subject: proposal, change self. to . References: Message-ID: <235bd23b-9841-43dc-8629-b8cccd3abf29@b1g2000hsg.googlegroups.com> Heiko Wundram: > > how about changing the precious self. to . > > imagine > > self.update() > > .update() > > simple right? I suggest you to start using Ruby instead. Bye, bearophile From max at alcyone.com Mon Aug 4 05:25:43 2008 From: max at alcyone.com (Erik Max Francis) Date: Mon, 04 Aug 2008 02:25:43 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> <5a0b303a-8324-4eeb-a975-397371bf2875@b1g2000hsg.googlegroups.com> Message-ID: Antoon Pardon wrote: > Maybe I'm going to be pedantic here, but I fear that your code won't > work with matrices. The problem is that multiplication is not > commutative with matrices. This means that matrices have two divisions a right > and a left division. A far as I know the "/" operator usaly implements > the left division while solving is done by using a right division. > > So your code will probably fail when applied to matrices. You're right in your general point, but usually division between matrices isn't defined at all because of this ambiguity. However the general point can still exist between `solveLeft` and `solveRight` functions which do something along the lines of a*b**-1 and a**-1*b. A single `solve`, of course, would choose one of these, and syntactically it might be quite reasonable to define matrix division that does one of these and have a single `solve` function that accomplishes it. Therefore, the general point about polymorphism still stands. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis It is human nature to think wisely and act foolishly. -- Anatole France From simon at brunningonline.net Wed Aug 27 04:26:48 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 27 Aug 2008 09:26:48 +0100 Subject: Python and database unittests In-Reply-To: <3f0d61c40808270048y4173328dhddee0306bb61eb5@mail.gmail.com> References: <485093c5-a0f5-482e-b8fd-3cdd119020d1@r15g2000prd.googlegroups.com> <3f0d61c40808270048y4173328dhddee0306bb61eb5@mail.gmail.com> Message-ID: <8c7f10c60808270126k51b24a9emae30e3485997732f@mail.gmail.com> 2008/8/27 Marco Bizzarri : > I strongly disagree on using mocks for a database; checking sequences > of SQL statement is fragile, painful, and leads you to frustration > when the actual SQL and the generated SQL do not match. Clearly you need integration tests as well as unit tests, but the unit tests ought to isolate the code under test, so stubbing out external dependencies is the norm. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From michele.simionato at gmail.com Tue Aug 5 08:01:22 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 5 Aug 2008 05:01:22 -0700 (PDT) Subject: Hobbyist - Python vs. other languages References: Message-ID: <773321ae-b3ff-46c0-8e87-34a59dcec603@z72g2000hsb.googlegroups.com> On Jul 31, 8:32?pm, fprintf wrote: > Since I don't have a specific problem to solve, besides > Pythonchallenge (which I found very cryptic), and Project Euler (which > I found beyond my mathematics skills), is there a place to go for > increasingly difficult problems to solve? I have followed a number of > the recommended online tutorials that contain a logical progression of > problems and yet they all end at the point where a person has enough > knowledge of the syntax, but not really enough to do anything. Just today I saw this recipe on the cookbook, "TV-Series Current Episode Info": http://code.activestate.com/recipes/572193/ As you see, there are plenty of useful things you can do with a programming language ;) Another trivial example: I am keeping an electronic journal as a Python script which checks today's date, create a file with that date (if it does not exist already) and open it with Emacs. That's all. I can search the journal with grep. Since I write the journal in rst format I can publish it on the Web in HTML or print it in PDF. It takes 20 minutes to write a script like that, and it working better for my needs than any commercial application could. The biggest feature is the absence of features: less is more. Michele Simionato From modelnine at modelnine.org Wed Aug 6 08:54:13 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Wed, 06 Aug 2008 14:54:13 +0200 Subject: Find class of an instance? In-Reply-To: References: Message-ID: <1218027253.4182.2.camel@phoenix> Am Mittwoch, den 06.08.2008, 08:44 -0400 schrieb Neal Becker: > Sounds simple, but how, given an instance, do I find the class? .__class__ For example: Python 2.5.2 (r252:60911, Aug 5 2008, 03:26:50) [GCC 4.3.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x = "hello" >>> x.__class__ >>> --- Heiko. From deets at nospam.web.de Wed Aug 27 12:44:46 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 27 Aug 2008 18:44:46 +0200 Subject: how do I stop SocketServer()? References: Message-ID: <6hleksFmq0nuU1@mid.uni-berlin.de> Alexandru Mosoi wrote: > supposing that I have a server (an instance of SocketServer()) that > waits for a connection (ie is blocked in accept()) and in another > thread i want to stop the server, how do I do that? By setting a timeout on the socket using socket.settimeout, and then periodically check for an abortion condition in the server thread before re-accepting connections. Diez From manthra.mohan at gmail.com Thu Aug 7 12:23:51 2008 From: manthra.mohan at gmail.com (Krishna) Date: Thu, 7 Aug 2008 09:23:51 -0700 (PDT) Subject: Access individual fields in csv using python Message-ID: How do I access individual fields in csv using python? Please let me know ASAP as its real urgent for me. Thanks for your help Krishna From fredrik at pythonware.com Sun Aug 24 12:43:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 24 Aug 2008 18:43:25 +0200 Subject: IDE In-Reply-To: <53839854-fdc6-4ffb-857b-8d68ae41606a@d1g2000hsg.googlegroups.com> References: <53839854-fdc6-4ffb-857b-8d68ae41606a@d1g2000hsg.googlegroups.com> Message-ID: krishna wrote: > i need link of latest IDE of python(GUI) http://wiki.python.org/moin/IntegratedDevelopmentEnvironments (is google broken today?) From tjreedy at udel.edu Tue Aug 5 15:57:50 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 05 Aug 2008 15:57:50 -0400 Subject: string to type object (C) In-Reply-To: <4477a269-f189-4ae1-9c97-e78633bb3d27@2g2000hsn.googlegroups.com> References: <4477a269-f189-4ae1-9c97-e78633bb3d27@2g2000hsn.googlegroups.com> Message-ID: castironpi wrote: > Hello, > > I'm looking for a one-to-one function from strings to the built-in > data types in C. I will be keeping the string in a file. I need the > PyTypeObject* back from it. Use a dict mapping py strings to the object pointers (cast to py ints). From giles.thomas at resolversystems.com Tue Aug 19 12:32:45 2008 From: giles.thomas at resolversystems.com (Giles Thomas) Date: Tue, 19 Aug 2008 17:32:45 +0100 Subject: ANN: Resolver One 1.2 released Message-ID: <48AAF5AD.1050007@resolversystems.com> 2008/8/19 km Hi, sounds great - but disappointing to find it only available on window$. Is there any Linux release in near future ??? KM Not in the near future, unfortunately - but we're looking at getting it running under Mono in the medium term. The big problem is that we'll have to change (or even recode) our grid component. Best regards, Giles -- Giles Thomas MD & CTO, Resolver Systems Ltd. giles.thomas at resolversystems.com +44 (0) 20 7253 6372 Try out Resolver One! 17a Clerkenwell Road, London EC1M 5RD, UK VAT No.: GB 893 5643 79 Registered in England and Wales as company number 5467329. Registered address: 843 Finchley Road, London NW11 8NA, UK -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 26 05:11:05 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 26 Aug 2008 11:11:05 +0200 Subject: generate methods at runtime, but the wrong one gets called In-Reply-To: References: Message-ID: <48b3c879$0$8908$426a74cc@news.free.fr> Maric Michaud a ?crit : (snip) > i don't get your design, it seems over-complicated to mee at first glance. > From coolman.guron at gmail.com Sat Aug 2 16:35:23 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Sat, 2 Aug 2008 13:35:23 -0700 (PDT) Subject: why goes the time change after import statement ? Message-ID: <011a92b4-b911-4f63-9339-be46b48d5f76@v1g2000pra.googlegroups.com> hi i am working on a S3 project and facing a really weird problem! take a look at the following import statements and the time output >>> import time >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) 'Sat, 02 Aug 2008 20:21:56 GMT' # OK >>> import pygtk >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) 'Sat, 02 Aug 2008 20:22:04 GMT' # OK >>> import gtk >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) 'Sat, 02 Aug 2008 08:22:11 PM GMT' # HOW THE HELL THIS HAPPEN ??? not DATE_RFC2822 format gmt time ! i have waisted 3 hours trying to locate the source of this strange problem. so what i am asking is does anyone know to overwrite or fix the defaurl behaviour strftime() ???? From info at orlans-amo.be Sun Aug 17 04:20:48 2008 From: info at orlans-amo.be (info at orlans-amo.be) Date: Sun, 17 Aug 2008 01:20:48 -0700 (PDT) Subject: Good python equivalent to C goto References: <48a744b6$0$299$7a628cd7@news.club-internet.fr> Message-ID: <887b84d8-ee3e-4c55-8518-b2f21ab50619@a1g2000hsb.googlegroups.com> as an oldtimer, I know that in complex code the goto statement is still the easiest to code and understand. I propose this solution using exception. The string exception is deprecated but is simpler for this example. # DeprecationWarning: raising a string exception is deprecated def Goto_is_not_dead(nIn): try: if (nIn == 1): raise 'Goto_Exit' if (nIn == 2): raise 'Goto_Exit' print 'Good Input ' + str(nIn) raise 'Goto_Exit' except 'Goto_Exit': print 'any input ' + str(nIn) if __name__ == '__main__': Goto_is_not_dead(2) Goto_is_not_dead(3) From deets at nospam.web.de Tue Aug 5 18:33:15 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 06 Aug 2008 00:33:15 +0200 Subject: Dictionary to tree format (hopefully simple) In-Reply-To: References: Message-ID: <6fs2pbFd43utU1@mid.uni-berlin.de> Adam Powell schrieb: > Hi! > I have seemingly simple problem, which no doubt someone out there has > already solved, but I'm stumped. Imagine I have a dictionary like > below, in which the keys are parent nodes and the values are a list of > children nodes. > > dict = { 0: [1, 2], 1: [3], 2: [6], 3: [4,7], 4: [5,8], 8: [9] } > > Is there an obvious way to produce a nested tree format for this > dictionary, like this: > > [ 0 [ 1 [ 3 [ 4 [ 5 , 8 [ 9 ] ] , 7 ] ] , 2 [ 6 ] ] > > Thanks for any help, d = { 0: [1, 2], 1: [3], 2: [6], 3: [4,7], 4: [5,8], 8: [9] } nodelists = dict((node ,[node, []]) for node in d.keys()) for node, children in d.iteritems(): for child in children: nodelists[node][1].extend(nodelists.setdefault(child, [child])) print nodelists[0] Two remarks: - don't use "dict" as name for a dictionary - look at the above code *why* not... - the code assumes that 0 is the root. if that wouldn't be the case, you need to search for the root node. I've got an idea - you to? Diez From __peter__ at web.de Tue Aug 26 03:13:46 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 26 Aug 2008 09:13:46 +0200 Subject: smart quotes References: <4188c027-3c64-429b-a1e6-a1f3a79060e8@a3g2000prm.googlegroups.com> Message-ID: Adrian Smith wrote: > Can anyone tell me how to get rid of smart quotes in html using > Python? I've tried variations on > stuff = string.replace(stuff, "\?", "\""), but to no avail, presumably > because they're not standard ASCII. Convert the string to unicode. For that you have to know its encoding. I assume UTF-8: >>> s = "a ?smart quote? example" >>> u = s.decode("utf-8") Now you can replace the quotes (I looked up the codes in wikipedia): >>> u.replace(u"\u201c", "").replace(u"\u201d", "") u'a smart quote example' Alternatively, if you have many characters to remove translate() is more efficient: >>> u.translate(dict.fromkeys([0x201c, 0x201d, 0x2018, 0x2019])) u'a smart quote example' If necessary convert the result back to the original encoding: >>> clean = u.translate(dict.fromkeys([0x201c, 0x201d, 0x2018, 0x2019])) >>> clean.encode("utf-8") 'a smart quote example' Peter From mail at timgolden.me.uk Wed Aug 6 15:50:19 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 06 Aug 2008 20:50:19 +0100 Subject: Calculate sha1 hash of a binary file In-Reply-To: <3e828257-07b5-478e-939d-8bf6addc112a@k30g2000hse.googlegroups.com> References: <3e828257-07b5-478e-939d-8bf6addc112a@k30g2000hse.googlegroups.com> Message-ID: <489A007B.5030503@timgolden.me.uk> LaundroMat wrote: > Hi - > > I'm trying to calculate unique hash values for binary files, > independent of their location and filename, and I was wondering > whether I'm going in the right direction. > > Basically, the hash values are calculated thusly: > > f = open('binaryfile.bin') > import hashlib > h = hashlib.sha1() > h.update(f.read()) > hash = h.hexdigest() > f.close() > > A quick try-out shows that effectively, after renaming a file, its > hash remains the same as it was before. > > I have my doubts however as to the usefulness of this. As f.read() > does not seem to read until the end of the file (for a 3.3MB file only > a string of 639 bytes is being returned, perhaps a 00-byte counts as > EOF?), is there a high danger for collusion? Guess: you're running on Windows? You need to open binary files by using open ("filename", "rb") to indicate that Windows shouldn't treat certain characters -- specifically character 26 -- as special. TJG From gminick at bzt.bzt Fri Aug 22 06:05:06 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Fri, 22 Aug 2008 10:05:06 +0000 (UTC) Subject: def X(l=[]): weirdness. Python bug ? References: <8824d$48ae83b2$18847a51$1995@news.chello.nl> <6h7fvbFjm6ogU2@mid.uni-berlin.de> Message-ID: On Fri, 22 Aug 2008 11:42:03 +0200, Diez B. Roggisch wrote: > It's amazing. I didn't analyse this properly, but IMHO this issue is the > single most asked question (or rather the effects in produces) on this list. > > Maybe we should get *really* explicit in > > http://docs.python.org/tut/node6.html#SECTION006710000000000000000 > > and > > http://docs.python.org/ref/function.html > > Big, red warnings, or some such. +1 Documenting this should also make it easier to understand the difference between mutable/immutable objects before one comes on c.l.py and asks about it. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From rajat.dudeja at aeroflex.com Thu Aug 14 11:37:06 2008 From: rajat.dudeja at aeroflex.com (Dudeja, Rajat) Date: Thu, 14 Aug 2008 11:37:06 -0400 Subject: How do I organize my Python application code? In-Reply-To: References: Message-ID: >>Fredrik Lundh wrote: >> That's all there is; there's no header files or declaration files or >> explicitly maintained object files etc; the program itself is just a >> bunch of Python files. >I would simply add that if your python script produces one or more output files (for example a text or graphic file) >you might want to have an 'output' directory in your project. >Some people use a 'src' directory, but that is not nearly as neccessary as in a complied language. Thanks Ken and Fredrik for your direction. Cheers, Rajat Notice: This e-mail is intended solely for use of the individual or entity to which it is addressed and may contain information that is proprietary, privileged, company confidential and/or exempt from disclosure under applicable law. If the reader is not the intended recipient or agent responsible for delivering the message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If this communication has been transmitted from a U.S. location it may also contain data subject to the International Traffic in Arms Regulations or U.S. Export Administration Regulations and cannot be disseminated, distributed or copied to foreign nationals, residing in the U.S. or abroad, without the prior approval of the U.S. Department of State or appropriate export licensing authority. If you have received this communication in error, please notify the sender by reply e-mail or collect telephone call and delete or destroy all copies of this e-mail message, any physical copies made of this e-mail message and/or any file attachment(s). From maric at aristote.info Wed Aug 13 21:19:00 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 14 Aug 2008 03:19:00 +0200 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: <76fd5acf0808131659i361d7fbdo595bebf57aeab317@mail.gmail.com> References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> <200808122240.22517.maric@aristote.info> <76fd5acf0808121415h41cc580bj85d96e648c54ab4b@mail.gmail.com> <200808140141.38909.maric@aristote.info> <76fd5acf0808131659i361d7fbdo595bebf57aeab317@mail.gmail.com> Message-ID: <48A38804.5060603@aristote.info> Calvin Spealman a ?crit : > On Wed, Aug 13, 2008 at 7:41 PM, Maric Michaud wrote: >> I was not aware of any "nested classes are unsupported" before and didn't >> consider nested classes as bad practice till now, even with the pickle >> limitation (not every class are intended to be pickled), more you didn't give >> any evidence or any pertinent quote of this and at least one of Guido in the >> above threads seems contradict you : >> http://mail.python.org/pipermail/python-dev/2002-November/029906.html > > Of course, I don't have to agree with Guido, neither do I, for sure. > but I don't really think > his comment there counts as some encouragement of the practice. It > also isn't an example that actually demonstrates the things people > misuse about nesting classes, although its definitely an example that > I think could be done much better without them, at all. > Yes this example is some sort of metalanguage using class statment in a derived way, It comes in mind sometimes by the fact there is no other way to extend the language to make DSL in python (perhaps easy extend will be popular one day, but I doubt). I did something like that before in an application and won't encourage anyone to do so. > The use of nested classes to define some hierarchical structure is > subject, at best. And, the examples I see aren't even hierarchical. > The nesting doesn't seem to gain them anything. As a matter of fact, > wouldn't that example be a lot more clear with one class and some > "Attribute" properties describing the structure? > > What rubs me the wrong way about nested classes is that they aren't > even "real" classes. That is, they aren't being used to instantiate > instances, but just as dummy scopes to hold some attributes. They are > abusing classes as property bags. > Here, I disagree, the helper classes example is good IMO, defining an Iterator as an inner class and referencing it by MyIterable.Iterator is good style. That said, I understood from your first post that python community in general will discourage nested classes as bad practice and consider them not supported by the language, statment for which I can't find or remember no evidence. >> BTW my concern was not really about nested classes but the asymetry between >> function scope and classes scope, there are at least two examples that come >> to my mind and for which I don't see good argument to keep the situation as >> it is. First is the very odd behavior of genexp, second is the dynamic type >> factory, I know it's not a big deal to in each case and can live with this, >> but these pieces of code fail unexpectedly while even a experimented python >> programmer would have thought they work at first glance, and the explanation >> of why they fail to a newcomer is not easy (specially for the first) >> >> (1) this fail only on the last line while it would have work well with >> listcomp and works well in a function definition >> class A(object) : >> l = range(5) >> m = list(a+b for a in l for b in range(5)) >> n = list(a+b for a in range(5) for b in l) > > I can admit that this behavior can be surprising, but it isn't > something I really see cropping up as a problem. How often do you see > that you need to have any kind of procedural behavior in a class body? > In other words, in all but rare cases, the order of the class body > lines shouldn't change the resulting class, but this example breaks > that expectation. > I wrote something like that a few months ago, and found it both simple concise and elegant : class test_suite1(test_suite) : roles = (role1, ...) actors = (actor1, ...) use_cases = [ (actor, role) for actor in actors for role in roles ] which I wrote at first tuple((actor, role) for ...) and came to the problem. Of course use_cases can be made a true generator, but in this particular case building the tuple/list together with the class is good enough. >> (2) This won't work as it would with nested functions, you need to build the >> new calss directly with type('dynamic', (object,), {"type_": type_}) >> >> def create_type(type_) : >> class dynamic(object) : >> type_ = type_ >> return dynamic > > This is simply completely invalid. That code at the beginning of any > body will _always_ raise either an UnboundLocalError or a NameError, > because you are assigning to the same name you are dereferencing. That > line will always be either an error or a no-op, anywhere it appears. > It has nothing to do with nesting of any sort. > Yes, of course, sorry, it should be : def create_type(t) : class dynamic(object) : type_ = t return dynamic but this work to my surprise ! I just thought the "t" in the class body would be looked up in global namespace. The design is that "free vars doesn't bind to class namespaces" not that "free vars of class namespaces bind to global namespace", my mistake. >> -- >> _____________ >> >> Maric Michaud >> -- >> http://mail.python.org/mailman/listinfo/python-list > > > From Edwin.Madari at VerizonWireless.com Thu Aug 14 21:02:19 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Thu, 14 Aug 2008 21:02:19 -0400 Subject: SOAPpy and ArrayOfString In-Reply-To: Message-ID: <20080815010231.8D4291E4007@bag.python.org> for someMethod(Field1 ArrayOf_xsd_string, other_parameters) a call someMethod( ['str1', 'str2', 'str3'], other_parameters) *works for me* with SOAPpy 0.12.0. yes sir it does. in PERL, let alone array types, even for simple types it was hard for me with all the '->', and '$' prefixing for objects and variables. I use following snippet to check arguments, and return types from a wsdl for each method. If any on them is not a simple type, check the wsdl manually for details of the data type. ==================================================== import os, sys, glob from SOAPpy import WSDL def checkwsdl(file): if os.path.isfile(file): print 'wsdl:%s' % file server = WSDL.Proxy(file) for ct, k in enumerate(server.methods.keys()): args =[] rets = [] callInfo = server.methods[k] for ct2, name in enumerate(callInfo.inparams): args.append('%s %s' % (name.name.encode(), name.type[1].encode())) for ct2, name in enumerate(callInfo.outparams): rets.append('%s %s' % (name.name.encode(), name.type[1].encode())) print '%s. %s(%s)\n\treturns(%s)' % ( ct+1, k.encode(), ',\n\t\t'.join(args), ',\n\t\t'.join(rets)) print if __name__ == '__main__' : args = sys.argv[1:] for arg in args: for file in glob.glob(arg): checkwsdl(file) ==================================================== Even though a method may be asking for an array, server may be accepting only up to a certain number of elements in the array. And check the data type for elements in the array. of course I had to tweak a couple of SOAPpy modules to accept long data type, and work from behind a firewall. hope that helps... thanks Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org]On Behalf Of annu miya Sent: Thursday, August 14, 2008 12:11 PM To: python-list at python.org Subject: SOAPpy and ArrayOfString Hi, In the article below you mention that you were succesful at doing this through perl. Would it be possible to send me the perl code? http://mail.python.org/pipermail/python-list/2007-January/423311.html Thank You Regards Sid The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jimgardener at gmail.com Thu Aug 28 13:01:42 2008 From: jimgardener at gmail.com (jimgardener) Date: Thu, 28 Aug 2008 10:01:42 -0700 (PDT) Subject: cannot find object instance References: <6b8a855f-8ff4-41f8-87f1-1b832368dd83@v16g2000prc.googlegroups.com> <48b6d3a1$0$27466$426a74cc@news.free.fr> Message-ID: On Aug 28, 9:35 pm, Bruno Desthuilliers wrote: Such a ping-pong between two classes is more often > than not a design smell. thanks Bruno,i understand my mistake..should have figured it out myself thanks again jim From info at thegrantinstitute.com Tue Aug 19 21:10:23 2008 From: info at thegrantinstitute.com (Anthony Jones) Date: 19 Aug 2008 18:10:23 -0700 Subject: Professional Grant Proposal Writing Workshop (September 2008: British Columbia Institute of Technology - Vancouver Campus) Message-ID: <20080819181022.1AC4026A075D7281@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Aug 15 13:19:21 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 15 Aug 2008 10:19:21 -0700 (PDT) Subject: negative numbers are not equal... References: Message-ID: On Aug 15, 8:56?am, Dan Lenski wrote: > On Thu, 14 Aug 2008 17:18:55 -0300, ariel ledesma wrote: > > hello guys > > > i just ran into this when comparing negative numbers, they start > > returning False from -6 down, but only when comparing with 'is' > > > ?>>> m = -5 > > ?>>> a = -5 > > ?>>> m is a > > True > > ?>>> m = -6 > > ?>>> a = -6 > > ?>>> m is a > > False > > ?>>> m == a > > True > > > i read that 'is' compares if they are really the same object, but i > > don't that's it because then why does -5 return True? of course i could > > only use == to compare, but still, what am i missing here? thanks in > > advance > > They also return False for positive numbers > 256. ?Try this: > ?>>> print [x for x in range(-10,260) if x is not x+1-1] > [-10, -9, -8, -7, -6, 257, 258, 259] > > There is a good explanation for this: the "is" operator checks for object > identity, not equality. ?Basically "a is m" asks, does the variable name > "a" reference the same memory location as the variable name "m"? > > For integers in the range of -5<=x<=256, Python pre-caches all of these > values, and whenever a variable takes on one of those values, it uses the > cached value. ?This is an optimization: it prevents the need to allocate > a new Python object for these very very common small integer values. > > For integer literals outside this range, a new Python object gets created > when they are assigned to variables, so a=500 followed by m=500 will > create new objects. > > The "is" operator just shows the effect of this caching. ?It's > unimportant for real code since you never care whether two numeric > variables refer to the same object (only important for complex data > structures where their storage may overlap)... only whether they are > equal or not. > > Dan Lenski > > (PS- The small integer pre-caching is described somewhere in the C API > docs.) It would be nice to put together a really canonical case of the use of the 'is' comparison. FTSOA for the sake of argument, when do you use it? Why is it even in the language? If you're iterating over a list, flagA= object() flagB= object() flagC= -10 listA= [ objectA, objectB, flagA, objectC, flagB, -10, objectD ] flags= [ listA, listB, listC ] for iA in listA: for flag in flags: if iA is flag: handle( iA ) This case actually misses handleC(). The solution is that the function that is returning '-10' cannot return -10, it has to return flagC. This can cause difficulties in cases when you're doing operations on flags. Worse, if flagC is nested somewhere, say moduleA.classB.flagC, you still have to work with that, not its value. From ivosh at ivosh.net Fri Aug 29 02:46:50 2008 From: ivosh at ivosh.net (Ivo Raisr) Date: Fri, 29 Aug 2008 08:46:50 +0200 Subject: Python-2.3.4 on OSF1 V4.0? Message-ID: <6055659e0808282346r2fcca861r21b5e09ce67d06e4@mail.gmail.com> Hi Edmond and any interested reader, I've successfully patched _socket extension of python 2.5.1 to build on OSF1 V4.0 with gcc 4.1.2. The following construct is put right after #include "Python.h" and #include "structmember.h": #define _POSIX_PII_SOCKET #define _LIBC_POLLUTION_H_ Ivosh Raisr From nytrokiss at gmail.com Sun Aug 24 14:48:20 2008 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 24 Aug 2008 11:48:20 -0700 Subject: Interrupt python thread In-Reply-To: References: Message-ID: <8a6b8e350808241148k496fcdf6hb6a938798d848b12@mail.gmail.com> Group all the threads in a list and call the stop method on all of them. On Sun, Aug 24, 2008 at 1:48 AM, BlueBird wrote: > Hi, > > I have a program with a master thread and several slave threads. > > Whenever an exception occurs, in the master thread or in one of the > slave threads, I would like to interrupt all the threads and the main > program. Threading API does not seem to provide a way to stop a > thread, is there anyway to achieve that ? > > The closest thing I found is thread.interrupt_main() but it's far from > perfect : > - it only allow to interrupt the main thread > - if the main thread is sleeping, it does not interrupt it (at least > on windows) > > cheers, > > Philippe > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Mon Aug 4 18:20:18 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 05 Aug 2008 08:20:18 +1000 Subject: What Python looks like References: Message-ID: <87ej54778d.fsf@benfinney.id.au> iu2 writes: > I'm curious, what did Python code look like to those of you who have > seen a bunch of Python code for the first time before knowing Python? To me it looked like the pseudo-code used for describing algorithms, allowing clear understanding and redesign of the algorithm before adding all the cruft "necessary" to make a real program from it. I was very impressed, therefore, that program code could be so clear and readable, and yet require so little computer-friendly cruft. > (I can tell, for example, that seeing perl for the first time looked > like C with many $$$, I could see "if" and "for" and "while" but they > were meaningless. Being already familiar with Bourne-style shell programs, Perl just looked to me like an even-more-baroque version of Bourne shell syntax. Not surprising, since that was one of its main inspirations. > Or Lisp for the first time looked like many words, no operators, how > could that make a program???) I had no referent with which to compare Lisp when I first saw it. I did wonder "if the program is so nicely indented anyway, why are all these parentheses necessary?" That was many years before I encountered Python :-) -- \ ?I see little commercial potential for the Internet for at | `\ least ten years.? ?Bill Gates, 1994 | _o__) | Ben Finney From matthias.blaesing at rwth-aachen.de Mon Aug 18 10:07:44 2008 From: matthias.blaesing at rwth-aachen.de (Matthias =?iso-8859-1?q?Bl=E4sing?=) Date: 18 Aug 2008 14:07:44 GMT Subject: Dropping privileges in python daemon References: Message-ID: Am Mon, 18 Aug 2008 14:33:27 +0200 schrieb David H?rdeman: > > I'm used from C programming to use setresuid() to change the real, > effective and saved uid in one go, and although the os module has some > of the set*uid() functions it doesn't seem to have setresuid(). no - python offers the posix function setuid. Have a look here: http://www.opengroup.org/onlinepubs/000095399/functions/setuid.html Without any further knowledge this should do everything you want from it and it is available from the posix and/or the os module. HTH Matthias From sjmachin at lexicon.net Wed Aug 6 17:36:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 6 Aug 2008 14:36:01 -0700 (PDT) Subject: Parsing of a file References: <760c7cd4-5a23-4e8e-801d-31670afd050b@l42g2000hsc.googlegroups.com> <91b5cd11-1bb6-4715-8964-85afc77862d1@1g2000pre.googlegroups.com> Message-ID: <7f838daa-399d-40ae-a6a8-4551b25e4c68@b30g2000prf.googlegroups.com> On Aug 7, 7:06 am, John Machin wrote: > On Aug 7, 6:02 am, Mike Driscoll wrote: > > > > > On Aug 6, 1:55 pm, Tommy Grav wrote: > > > > I have a file with the format > > > > Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames > > > 5 Set 1 > > > Field f31448: Ra=20:24:58.13 Dec=+79:39:43.9 MJD=53370.06811620 Frames > > > 5 Set 2 > > > Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames > > > 5 Set 3 > > > Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames > > > 5 Set 4 > > > Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames > > > 5 Set 5 > > > Field f30560: Ra=20:27:01.82 Dec=+74:47:50.3 MJD=53370.06860400 Frames > > > 5 Set 6 > > > Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames > > > 5 Set 7 > > > Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames > > > 5 Set 8 > > > Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames > > > 5 Set 9 > > > Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames > > > 5 Set 10 > > > > I would like to parse this file by extracting the field id, ra, dec > > > and mjd for each line. It is > > > not, however, certain that the width of each value of the field id, > > > ra, dec or mjd is the same > > > in each line. Is there a way to do this such that even if there was a > > > line where Ra=****** and > > > MJD=******** was swapped it would be parsed correctly? > > > > Cheers > > > Tommy > > > I'm sure Python can handle this. Try the PyParsing module or learn > > Python regular expression syntax. > > >http://pyparsing.wikispaces.com/ > > > You could probably do it very crudely by just iterating over each line > > and then using the string's find() method. > > Perhaps you and the OP could spend some time becoming familiar with > built-in functions and str methods. In particular, str.split is your > friend: > > C:\junk>type tommy_grav.py > # Look, Ma, no imports! > > guff = """\ > Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames > 5 Set 1 > Field f31448: MJD=53370.06811620123 Dec=+79:39:43.9 Ra=20:24:58.13 > Frames 5 Set > 2 > Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames > 5 Set 3 > Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames > 5 Set 4 > Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames > 5 Set 5 > > Field f30560: Ra=20:27:01.82 Dec=+74:47:50.3 MJD=53370.06860400 Frames > 5 Set 6 > Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames > 5 Set 7 > Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames > 5 Set 8 > Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames > 5 Set 9 > Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames > 5 Set 10 > > """ > > is_angle = { > 'ra': True, > 'dec': True, > 'mjd': False, > } > > def convert_angle(text): > deg, min, sec = map(float, text.split(':')) > return (sec / 60. + min) / 60. + deg > > def parse_line(line): > t = line.split() > assert t[0].lower() == 'field' > assert t[1].startswith('f') > assert t[1].endswith(':') > field_id = t[1].rstrip(':') > rdict = {} > for f in t[2:]: > parts = f.split('=') > if len(parts) == 2: > key = parts[0].lower() > value = parts[1] > assert key not in rdict > if is_angle[key]: > rvalue = convert_angle(value) > else: > rvalue = float(value) > rdict[key] = rvalue > return field_id, rdict['ra'], rdict['dec'], rdict['mjd'] > > for line in guff.splitlines(): > line = line.strip() > if not line: > continue > field_id, ra, dec, mjd = parse_line(line) > print field_id, ra, dec, mjd > > C:\junk>tommy_grav.py > f29227 20.3962611111 67.5 53370.0679769 > f31448 20.4161472222 79.6621944444 53370.0681162 > f31226 20.4126388889 78.4458888889 53370.0682386 > f31004 20.4181333333 77.2296944444 53370.0683602 > f30782 20.4310944444 76.0135 53370.0684821 > f30560 20.4505055556 74.7973055556 53370.068604 > f30338 20.4756527778 73.5811111111 53370.0687262 > f30116 20.5060277778 72.3648888889 53370.0688489 > f29894 20.5412611111 71.1486111111 53370.0689707 > f29672 20.5810805556 69.9323888889 53370.0690935 > > Cheers, > John Slightly less ugly: C:\junk>diff tommy_grav.py tommy_grav_2.py 18,23d17 < is_angle = { < 'ra': True, < 'dec': True, < 'mjd': False, < } < 27a22,27 > converter = { > 'ra': convert_angle, > 'dec': convert_angle, > 'mjd': float, > } > 41,44c41 < if is_angle[key]: < rvalue = convert_angle(value) < else: < rvalue = float(value) --- > rvalue = converter[key](value) From simon at mullis.co.uk Mon Aug 25 08:52:24 2008 From: simon at mullis.co.uk (Simon Mullis) Date: Mon, 25 Aug 2008 14:52:24 +0200 Subject: Equivalents of Ruby's "!" methods? Message-ID: <23d7e1bb0808250552r7d2b7097ye9e8777b4dcaa99c@mail.gmail.com> Hi All, Quick question, I can't seem to find the answer online (well, at the moment I think the answer is a simple "no" but I would like to confirm). Consider the following hash: h = { "1" : "a\r", "2" : "b\n" } In order to strip the dict values in Python I (think) I can only do something like: for k,v in h.items: h[k] = v.strip() While in Ruby - for the equivale dict/hash - I have the option of an in-place method: h.each_value { |v| val.strip! } Are there Python equivalents to the "!" methods in Ruby? The reason I ask is that I have some fairly complex data-structures and this would make my code alot cleaner... If this is not an accepted and pythonic way of doing things then please let me know... and I'll stop! Thanks in advance SM -- Simon Mullis _________________ simon at mullis.co.uk From vat.vjay10 at gmail.com Sun Aug 24 08:53:23 2008 From: vat.vjay10 at gmail.com (vat.vjay10 at gmail.com) Date: Sun, 24 Aug 2008 05:53:23 -0700 (PDT) Subject: Hai you looking Real Esate Agents India Message-ID: <2697bd8f-9dc6-405e-8243-513c3353ab18@b2g2000prf.googlegroups.com> http://www.moneymaking4.blogspot.com/ From andybak at gmail.com Tue Aug 12 06:41:46 2008 From: andybak at gmail.com (andybak) Date: Tue, 12 Aug 2008 03:41:46 -0700 (PDT) Subject: Jason Orendorff's path module Message-ID: Hi, I know this has been consigned to oblivion by the BDFL but I'm rather addicted to it's use. I notice the original site is no longer there. Has anyone got a cached copy of the page that I can host for posterity? Which rather makes me wonder - lot's of people liked this module or rather disliked os.path. Is there anything salvageable from the BDFL's objections worthy of a PEP? Andy From __peter__ at web.de Wed Aug 27 09:50:06 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 27 Aug 2008 15:50:06 +0200 Subject: finding out the number of rows in a CSV file [Resolved] References: <3aaa109e-9a7e-4d02-8af5-0161251d7678@t54g2000hsg.googlegroups.com> <0bc6097f-af52-4951-a413-e9a983df93c7@79g2000hsk.googlegroups.com> Message-ID: Jon Clements wrote: > On Aug 27, 12:54 pm, SimonPalmer wrote: >> after reading the file throughthe csv.reader for the length I cannot >> iterate over the rows. How do I reset the row iterator? > > If you're sure that the number of rows is always less than 200. Or 2000. Or 20000... Actually any number that doesn't make your machine fall into a coma will do. > Slightly modify Simon Brunning's example and do: > > rows = list( csv.reader(open('filename.csv')) ) > row_count = len(rows) > for row in rows: > # do something Peter From ethan at stoneleaf.us Thu Aug 7 15:14:06 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 07 Aug 2008 11:14:06 -0800 Subject: very newbie question In-Reply-To: <5F1D8E1D20CE4B7D9E874FED0AFFD677@Home> References: <5F1D8E1D20CE4B7D9E874FED0AFFD677@Home> Message-ID: <489B497E.1010603@stoneleaf.us> garywood wrote: > stuck on python for absolute beginners > chapter 6 > i actually done what i was supposed to do use the function ask_number > for guess a number > but for some reason it does not count correctly the number of tries > > # Guess My Number > # > # The computer picks a random number between 1 and 100 > # The player tries to guess it and the computer lets > # the player know if the guess is too high, too low > # or right on the money > > import random > > print "\tWelcome to 'Guess My Number'!" > print "\nI'm thinking of a number between 1 and 100." > print "Try to guess it in as few attempts as possible.\n" > > # set the initial values > > > > def ask_number(): > the_number = random.randrange(100) + 1 > guess = int(raw_input("Take a guess: ")) > tries = 1 > > > > > while (guess != the_number): > > > if (guess > the_number): > print "Lower..." > > else: > print "Higher..." > tries += 1 ^-- *not needed* > > > guess = int(raw_input("Take a guess: ")) > tries += 1 > > > > > ask_number() > > > > > print "You guessed it! The number was", the_number > print "And it only took you", tries, "tries!\n" > > raw_input("\n\nPress the enter key to exit.") > > > ------------------------------------------------------------------------ ~Ethan~ From tdelaney at avaya.com Thu Aug 7 19:20:45 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 8 Aug 2008 07:20:45 +0800 Subject: Psycho question In-Reply-To: Message-ID: David C. Ullrich wrote: > f: 0.0158488750458 > g: 0.000610113143921 > h: 0.00200295448303 > f: 0.0184948444366 > g: 0.000257015228271 > h: 0.00116610527039 I suspect you're hitting the point of diminishing returns with g, and any further investigations into optimisation are purely for fun and learning ;) Tim Delaney From ktenney at gmail.com Fri Aug 8 17:21:40 2008 From: ktenney at gmail.com (Kent Tenney) Date: Fri, 8 Aug 2008 21:21:40 +0000 (UTC) Subject: sending to an xterm References: <20080808205821.GJ23567@dragontoe.org> Message-ID: Derek Martin pizzashack.org> writes: > > On Fri, Aug 08, 2008 at 08:25:19PM +0000, Kent Tenney wrote: > > Howdy, > > > > I want to open an xterm, send it a command and have it execute it. > > You can't do that. xterm doesn't execute shell commands passed on > stdin... It can, however, execute one passed on the command line. > > Instead of just running xterm, you can run "xterm -e 'cmd foo bar'" > where cmd is the program to run and foo and bar are its arguments. > The problem is that as soon as the program exits, xterm will exit > also. > Sorry to reply before getting googly This appears to be a solution; xterm -e "ls; bash" http://www.linuxforums.org/forum/misc/115239-getting-prompt-after-xterm-e-command.html From notvalid2 at sbcglobal.net Thu Aug 28 18:05:51 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Thu, 28 Aug 2008 15:05:51 -0700 Subject: Python in a Nutshell -- Book vs Web Message-ID: I read an Amazon of Python in a Nutshell. The first edition is supposedly much like the web site. What web site? The second edition apparently adds more to the book than the web site. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From apardon at forel.vub.ac.be Mon Aug 4 04:56:52 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Aug 2008 08:56:52 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> <5a0b303a-8324-4eeb-a975-397371bf2875@b1g2000hsg.googlegroups.com> Message-ID: On 2008-08-01, Terry Reedy wrote: >> Nevertheless, I think this is probably the best example of the >> enhanced polymorphism of "if x" yet. I'm kind of surprised no one >> came up with it.) > > I think of Python code as 'generic' rather than 'polymorphic'. I am not > sure if that is a real difference or not, since I am a bit fuzzy on the > meaning of 'polymorphic' in this context. > > The generality of 'if x:' depends on the context. If x is defined as a > number by doc or previous code (or possibly even by subsequent code), > then 'if x:' is equivalent to 'if x != 0:'. At this point, it is a > stylistic argument which to use. > > But here is an example where 'if x:' is more generic. > > def solve(a,b): > 'a and b such that b/a exists' > if a: > return a/b > else: > raise ValueError('a not invertible, cannot solve' > > Now suppose we have a matrix class (2x2 for simplicity and realism). > Its __bool__ (3.0) method implements 'is non-singular'. As written > above, solve(mat,vec) works (with compatible mat and vec sizes), but it > would not with 'if a != 0:'. > > Of course, the issue goes away by not looking before the leap: > > def solve(a,b): > return a/b > # let callers deal with exceptions > or > try: > return a/b > except... > # raise customized error Maybe I'm going to be pedantic here, but I fear that your code won't work with matrices. The problem is that multiplication is not commutative with matrices. This means that matrices have two divisions a right and a left division. A far as I know the "/" operator usaly implements the left division while solving is done by using a right division. So your code will probably fail when applied to matrices. -- Antoon Pardon From steve at REMOVE-THIS-cybersource.com.au Sat Aug 23 04:16:59 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 23 Aug 2008 08:16:59 GMT Subject: setattr and getattr, when to use? References: <920d6a60-580d-4b89-8dfd-cd44b05676ae@25g2000hsx.googlegroups.com> Message-ID: <00bfc23f$0$20312$c3e8da3@news.astraweb.com> On Fri, 22 Aug 2008 20:50:17 -0700, maestro wrote: > Why are these functions there? Is it somehow more idiomatic to use than > to do obj.field ? Heavens no!!! Using setattr and getattr is *less* idiomatic. > Is there something you can with them that you can't by obj.field > reference? Absolutely. Consider: class Foo(object): pass foo = Foo() setattr(foo, "x y", 1) print getattr(foo, "x y") That's probably an abuse of setattr/getattr, but there are times where you might not know the name of the attribute until runtime, so you can't write foo.attr since you don't know what to write in place of attr. That's where setattr and getattr (as well as delattr and hasattr) come into play. -- Steven From fredrik at pythonware.com Sat Aug 30 08:20:47 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 30 Aug 2008 14:20:47 +0200 Subject: Advice on the style to use in imports In-Reply-To: <3f0d61c40808300512x1dcd5061t19ad7323b7ef15e9@mail.gmail.com> References: <3f0d61c40808300512x1dcd5061t19ad7323b7ef15e9@mail.gmail.com> Message-ID: Marco Bizzarri wrote: > I'm showing what I used in my current project, and will accept your > advices on how I should change them. > > The style is consistently the following: > > from package.subpackge.module import MyClass > > Is this an accepted way to write imports? According to what I > understood in articles, I don't think so. importing objects instead of the module (namespace) they live in can cause all sorts of aliasing and dependency issues. avoid unless you know exactly what you're doing. From steve at REMOVE-THIS-cybersource.com.au Sat Aug 9 00:22:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Aug 2008 04:22:02 GMT Subject: internet searching program References: <304d52cb-a8a8-46d5-81be-4eb01c73d479@26g2000hsk.googlegroups.com> Message-ID: <00ad1698$0$20318$c3e8da3@news.astraweb.com> On Fri, 08 Aug 2008 19:59:02 -0700, KillSwitch wrote: > Is it possible to make a program to search a site on the internet, then > get certain information from the web pages that match and display them? > Like, you would put in keywords to be searched for on youtube.com, then > it would search youtube.com, get the names of the videos, the links, and > the embed information? Or something like that. Search the Internet? Hmmm... I'm not sure, but I think Google does something quite like that, but I don't know if they do it with a computer program or an army of trained monkeys. -- Steven From paul.nospam at rudin.co.uk Sun Aug 24 13:21:55 2008 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Sun, 24 Aug 2008 18:21:55 +0100 Subject: Date Comparison and Manipulation Functions? References: Message-ID: <874p5apbv0.fsf@rudin.co.uk> "W. eWatson" writes: > Are there some date and time comparison functions that would compare, say, > > Is 10/05/05 later than 09/22/02? (or 02/09/22 format, yy/mm/dd) > Is 02/11/07 the same as 02/11/07? > > Is 14:05:18 after 22:02:51? (24 hour day is fine) > > How about the date after 02/28/04 is 02/29/04, or the date after > 09/30/08 is 10/01/08? > > How about is 03/03/04 20:10:08 after 03/07/03 14:00:00? Probably the > others above will suffice. http://docs.python.org/lib/module-datetime.html From gordyt at gmail.com Wed Aug 13 12:22:22 2008 From: gordyt at gmail.com (gordyt) Date: Wed, 13 Aug 2008 09:22:22 -0700 (PDT) Subject: datetime from uuid1 timestamp References: Message-ID: Howdy Kent, Interesting question! Give this a shot: import datetime import time import uuid # get offset in seconds between the UUID timestamp Epoch (1582-10-15) and # the Epoch used on this computer DTD_SECS_DELTA = (datetime.datetime(*time.gmtime(0)[0:3])- datetime.datetime(1582, 10, 15)).days * 86400 def uuid1_to_ts(u): """Return a datetime.datetime object that represents the timestamp portion of a uuid1. Parameters: u -- a type 1 uuid.UUID value Example usage: print uuid1_to_ts(uuid.uuid1()) """ secs_uuid1 = u.time / 1e7 secs_epoch = secs_uuid1 - DTD_SECS_DELTA return datetime.datetime.fromtimestamp(secs_epoch) --gordon From frankrentef at yahoo.com Thu Aug 7 14:56:53 2008 From: frankrentef at yahoo.com (frankrentef) Date: Thu, 7 Aug 2008 11:56:53 -0700 (PDT) Subject: Create a short way to save typing script over and over.... Message-ID: I have a statement "url = 'http://xyzserver/'" so in my code every time I need to use xyzserver I state "url +...." What I' m now trying to do is create a call to a login process. The script for the login process is below. I'd like to call "adminlogin" and not have to keep entering the same several lines of script each and everytime (I'm testing various login functions and rule changes.) I'm a newbie, can someone walk me through this? THNX #Login to ISeDeposit Admin ie.navigate (url + 'isweb/admin/default.aspx') ie.textBoxSet ('AdminLogin1:Username','Admin') ie.textBoxSet ('AdminLogin1:inputPassword','Password') ie.buttonClick ('AdminLogin1:btnLogin') From circularfunc at gmail.com Sun Aug 31 22:43:01 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 31 Aug 2008 19:43:01 -0700 (PDT) Subject: Some problems with classes References: Message-ID: <336b0d9e-2af8-45c1-b5b7-adb508fe7853@t54g2000hsg.googlegroups.com> class Animal(object): def __init__(self, name, weight): self.name = name self.weight = weight def speak(self): print "speak" class Vegetable(object): def __init__(self, name, volume): self.name = name self.volume = volume def split(self): print "tjoff" class Vegan(Animal, Vegetable): def __init__(self, name, attacks): self.name = name self.attacks = attacks From stefan_ml at behnel.de Tue Aug 26 02:28:20 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 26 Aug 2008 08:28:20 +0200 Subject: python xslt library In-Reply-To: References: Message-ID: <48B3A284.3040606@behnel.de> Owen Zhang wrote: > Can anyone recommand the best performance python xslt library? lxml. It's based on libxml2/libxslt. http://codespeak.net/lxml Stefan From gminick at nie.ma.takiego.adresu.w.sieci.pl Tue Aug 12 10:54:10 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Tue, 12 Aug 2008 14:54:10 +0000 (UTC) Subject: trying to use SOCK_RAW yields error " References: <3b701b38-9dd3-48f6-bdb0-c04fc9085008@x41g2000hsb.googlegroups.com> Message-ID: Dnia Tue, 12 Aug 2008 07:21:15 -0700 (PDT), Tzury Bar Yochay napisa?(a): > I changed as instructed: > server = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, > socket.getprotobyname('ip')) > > now I am getting: > > Traceback (most recent call last): > File "tcpsrv.py", line 15, in > server.bind((host,port)) > File "", line 1, in bind > socket.error: (19, 'No such device') What's the value of host variable? AFAIR it should be the name of the interface you want to bind to ('eth0', 'ppp0', whatever). -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From sjmachin at lexicon.net Mon Aug 4 05:34:43 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 4 Aug 2008 02:34:43 -0700 (PDT) Subject: Trying to fix Invalid CSV File References: <0427191c-d493-442d-ba26-94802bc6062b@v13g2000pro.googlegroups.com> <078f7aad-3bba-49b4-8978-18ac5bfaa6f7@r15g2000prd.googlegroups.com> <6bade254-5001-4ae2-a000-003b84437a76@w1g2000prk.googlegroups.com> Message-ID: On Aug 4, 6:15 pm, Ryan Rosario wrote: > On Aug 4, 1:01 am, John Machin wrote: > > > On Aug 4, 5:49 pm, Ryan Rosario wrote: > > > > Thanks Emile! Works almost perfectly, but is there some way I can > > > adapt this to quote fields that contain a comma in them? > > > You originally said "I have a very large CSV file that contains double > > quoted fields (since they contain commas)". Are you now saying that > > if a field contained a comma, you didn't wrap the field in quotes? Or > > is this a separate question unrelated to your original problem? > > I enclosed all text fields within quotes. The problem is that I have > quotes embedded inside those text fields as well and I did not double/ > escape them. Emile's snippet takes care of the escaping but it strips > the outer quotes from the text fields and if there are commas inside > the text field, the field is split into multiple fields. Of course, it > is possible that I am not using the snippet correctly I suppose. Without you actually showing how you are using it, I can only surmise: Emile's snippet is pushing it through the csv reading process, to demonstrate that his series of replaces works (on your *sole* example, at least). Note carefully his output for one line is a *list* of fields. The repr() of that list looks superficially like a line of csv input. It looks like you are csv-reading it a second time, using quotechar="'", after stripping off the enclosing []. If this guess is not correct, please show what you are actually doing. If (as you said) you require a fixed csv file, you need to read the bad file line by line, use Emile's chain of replaces, and write each fixed line out to the new file. From bearophileHUGS at lycos.com Sun Aug 17 18:24:06 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 17 Aug 2008 15:24:06 -0700 (PDT) Subject: like a "for loop" for a string References: <6bc8134c-fd89-4a98-8a99-813f41b26813@k30g2000hse.googlegroups.com> <58d6c42e-dbce-40f9-a962-e8543ba6f93e@v57g2000hse.googlegroups.com> <37e349e2-5089-4574-a7c3-19fef812bc70@l42g2000hsc.googlegroups.com> Message-ID: <1a8819f7-3eb4-41bd-bc9e-ae2aa03f0139@s50g2000hsb.googlegroups.com> MRAB: > If it was introduced into Python v3.x then wouldn't it have to be > called str.split in order to be consistent with xrange -> range? :-) xsplit may be a name fit for Python 2.6/2.7. Regarding Python 3.0 you may be right, but then when you want the list of parts you have to do: list(somestring.split()) While to count the number of parts on Python 3.0 this may suffice: sum(1 for part in somestring.split()) Unless you use a leniter() function that counts the lazy iterations (its functionality can be folded inside the len() too, like in some lazy languages). Most of the times I think a lazy splitting may suffice, so in Python 3.0 the eager version may be absent :-) Bye, bearophile From george.sakkis at gmail.com Mon Aug 11 16:11:42 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 11 Aug 2008 13:11:42 -0700 (PDT) Subject: ANN: papyros 0.2 Message-ID: I am pleased to announce papyros-0.2, the second alpha release of papyros: http://code.google.com/p/papyros/. Compared to the initial release 14 months ago, only the basic goal has remained the same; both the API and the internals have been thoroughly revamped. Some of the highlights are: - As simple as it gets: for most purposes, the API is reduced to a single method ("dispatcher.execute(tasks)"). - Easier task definition. - (Optional) ordered task execution and chunksize (inspired from pyprocessing). - A distributed group can now handle concurrently more than one independent task sequences: enables serving multiple clients. - Several bug fixes and performance improvements. About ----- Papyros is a small platform independent package for parallel processing. Currently two main implementations are provided for the same API: one using multiple threads and the other multiple processes on one or more hosts through Pyro (http://pyro.sourceforge.net/). From asmodai at in-nomine.org Wed Aug 13 07:51:50 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 13 Aug 2008 13:51:50 +0200 Subject: You advice please In-Reply-To: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> Message-ID: <20080813115150.GE87062@nexus.in-nomine.org> -On [20080813 13:16], Hussein B (hubaghdadi at gmail.com) wrote: >My friends are about to open a Ruby/Rails shop and they are asking me >to join them. I hope they are fully aware of the scaling problems RoR can have. >Why Python isn't getting this attention although is a much more mature >language and it is used by many big, big names? At least in my experience Python is getting more and more exposure. More job openings as well. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B A liar needs a good memory... From steve at REMOVE-THIS-cybersource.com.au Mon Aug 11 12:33:42 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Aug 2008 16:33:42 GMT Subject: eval or execute, is this the (most) correct way ? References: Message-ID: <00b06501$0$14351$c3e8da3@news.astraweb.com> On Mon, 11 Aug 2008 17:26:56 +0200, Stef Mientki wrote: > I'm trying to make an editor with an integrated Shell. ... > Is this the (most) correct / elegant way, or are there better solutions > ? The best solution is not to re-invent the wheel: "import code" is the way to emulate Python's interactive interpreter. Try running "python -m code" at a regular shell (not the Python shell, your operating system's shell). Doing a search of the file code.py, I don't find the string "eval" at all. My guess is that your approach is probably not the best way. -- Steven From cwitts at gmail.com Fri Aug 22 08:56:42 2008 From: cwitts at gmail.com (Chris) Date: Fri, 22 Aug 2008 05:56:42 -0700 (PDT) Subject: need help using enumerate ?? References: <3592f6a7-177f-4d1c-beed-69b72a0c2e43@i20g2000prf.googlegroups.com> Message-ID: On Aug 22, 1:14 pm, "Eric_Dex... at msn.com" wrote: > I am trying to take some data in file that looks like this > > command colnum_1 columnum_2 > > and look for the command and then cange the value in the collum(word) > number indicated. I am under > the impression I need enumerate but I am not sure what to do with it > any help would be nice. > > import sys > > parse1filerows = [] > csoundrows = [] > > filename = sys.argv[0] > number = sys.argv[1] > outfile = open('test.sco','w') > > infile = open(filename, 'r') > for line in infile: > csoundrows.append(line.split()) > parsefile = open('parsefile1.txt', 'r') > for line in parsefile: > parsefile1rows.append(line.split()) > for row in csoundrows: > for prow in parsefile1rows: > test = 0 > if parsefile1[prow][0] in csoundrow[row]: > for pcol in parsefile1[prow]: > if test == 1: > csoundrows[row][int(pcol)] = str(int(csoundrows[row] > [int(pcol)] + number) > for row in csoundrows: > for word in rows: > outfile.write(row) Rather confusing code there and non-functional. You never close your file handles, when finished with a file use the .close() method sys.argv[0] <-- the first element is the name of your .py file and not the first argument you supply. When iterating over a list like csoundrows you don't need to do for row in csoundrows: if ... in csoundrow[row]: # This will try to use 'row' as an index but rather if ... in row: Now, this is how I intepretted your question. from sys import argv, exit if len(argv) != 3: """Ensure the correct number of arguments are supplied""" exit('Incorrect number of arguments.') try: """Checks if the Input file exists and exits if open fails.""" inFile = open(argv[1], 'rb') except IOError: exit('Input file does not exist.') if not argv[2].isdigit(): """Argument #2 needs to be a number""" exit('Column number is not numerical.') idx = int(argv[2]) outFile = open('test.sco', 'wb') """Assuming your data in the parse file was a set of key, value pairs to be used for replacement in the input file. Just splitting on the basic space and assigning the first element as the key and the rest of the string as the value to be used for replacement. """ replaceData = {} for line in open('replacementInstructions.txt', 'rb'): key = line.strip().split(' ')[0] value = line.strip().split(' ')[1:] replaceData[key] = value """Iterate over your input file, split the line into it's component parts and then lookup if the first element 'command' is contained in the replacement data and if so change the data. If you want all input to be saved into your output file, just dedent the 'outFile.write' line by one level and then all data will be saved. """ for line in inFile: record = line.strip().split(' ') if record[0] in parseRows: record[idx] = parseRows[record[0]] outFile.write('%s\n' % ' '.join(record) ) inFile.close() outFile.close() From fetchinson at googlemail.com Thu Aug 14 23:38:05 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 14 Aug 2008 20:38:05 -0700 Subject: =?ISO-8859-1?Q?Re:_Don=B4t_find_HTMLgen?= In-Reply-To: <121682ff-1bfe-44db-a038-e764f26f012f@d77g2000hsb.googlegroups.com> References: <121682ff-1bfe-44db-a038-e764f26f012f@d77g2000hsb.googlegroups.com> Message-ID: > Good day Mr. Guido, excuse my poor english. > > I am looking for HTMLgen module but not to find this, the link > referenced in www.python.org it does not exist. > > I have need to develop in cgi and would want to do it of the possible > traditional form but, i like any module for my help. Since gentoo and debian (I think) were packaging it you can get it from their package repositories. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From ironfroggy at gmail.com Tue Aug 12 02:59:36 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Tue, 12 Aug 2008 02:59:36 -0400 Subject: How to iterate a sequence, with skipping the first item? In-Reply-To: References: Message-ID: <76fd5acf0808112359y4708c85ej38b74a413bf867bd@mail.gmail.com> i = iter(container.iterChildren()) i.next() for x in i: ... On Tue, Aug 12, 2008 at 2:51 AM, ray wrote: > A container object provides a method that returns an iterator object. > I need to iterate the sequence with that iterator, but need to skip > the first item. I can only iterate the whole sequence with: > for x in container.iterChildren(): > How to skip the first item? It seems that it's a simple question. > Could somebody help me? Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From raashid_hbk at yahoo.com Sun Aug 17 14:35:14 2008 From: raashid_hbk at yahoo.com (raashid bhatt) Date: Sun, 17 Aug 2008 11:35:14 -0700 (PDT) Subject: how to call API Functions in python References: <46c57206-49a8-48b1-966f-2beab4ac433e@w24g2000prd.googlegroups.com> <51d09a98-685f-4fbd-86df-c3eca9d5e309@o40g2000prn.googlegroups.com> Message-ID: On Aug 17, 11:27?am, Wojtek Walczak wrote: > On Sun, 17 Aug 2008 11:22:52 -0700 (PDT), raashid bhatt wrote: > >> > how to call API Functions in python > > >> The same way as you'd call any other function, of course. ?What API are > >> you referring to? > > i am talking about WINAPI > > I am not a Windows guy, but maybe ctypes module will be helpful > for you. > > -- > Regards, > Wojtek Walczak,http://www.stud.umk.pl/~wojtekwa/ Thanks a lot man That is what i wanted to know From gminick at bzt.bzt Mon Aug 25 09:36:40 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Mon, 25 Aug 2008 13:36:40 +0000 (UTC) Subject: passing arguments to exec References: <53975d0c-7a7d-47c3-9cd7-64f80672bb50@j1g2000prb.googlegroups.com> Message-ID: On Mon, 25 Aug 2008 06:31:53 -0700 (PDT), Alexandru Mosoi wrote: > i want to execute a python script using exec open('script.py'). how do > I pass arguments? Take a look at subprocess module. It comes with a set of examples. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From Ross at no.thanks.spammers Wed Aug 27 16:21:03 2008 From: Ross at no.thanks.spammers (RgeeK) Date: Wed, 27 Aug 2008 16:21:03 -0400 Subject: Global var access in imported modules? Message-ID: <48b5b72f$1@news.alcatel.com> I have a main module doStuff.py and another module utility.py. At the start of doStuff.py I call import utility.py Then I also proceed to initiallize some global variables sName = "" Then I create a class, some methods etc. In one of the methods I assign a value to my variable sName. Then I call a function from within my utility.py file: utility.makeOne(stuff) Within my utility.py file, I define the makeOne function. But I want to use that same global variable "sName" In utility.py I have tried to indicate that I'm using the global "sName" through the statement: global sName But when I go to use the variable it still gives me an error: NameError: global name 'sName' is not defined I thought perhaps I need to indicate 'globality' in my main module, so before I initiallized sName in doStuff.py I added: global sName But it doesn't help me. I had this issue before and resolved it by declaring the variable global in the sub-module utility.py, but then I needed to reference it in my main module with a prefix: utility.sName = "" It's more verbose,and defining globals in a submodule seems backward. But also, what if I need to access "sName" in another imported module, say "otherstuff.py"? I would do my "import otherstuff" call in my main module, but would I have to put an "import utility" into the otherstuff.py file? Is there some way I can define globals in my main module, and have them accessible in all my imported submodule? As you can see I'm a little unsure about the global handling in a multi-module environment. Any suggestions appreciated. I've read http://docs.python.org/ref/naming.html but it hasn't enlightened me on this one. From mensanator at aol.com Sat Aug 9 23:28:44 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 9 Aug 2008 20:28:44 -0700 (PDT) Subject: The wrong approach to things References: <0c435465-b769-45b9-8c6e-57d57abc5c31@j33g2000pri.googlegroups.com> Message-ID: On Aug 9, 9:20?pm, teh_sAbEr wrote: > Ok, so this isn't necessarily a programming issue, but anyways. I've > managed to write that random wallpaper changer i've been wanting to > make, but i've run into a little problem. According to the MS > Knowledge Base, SystemParametersInfo() can't take a .jpg file as an > argument when changing the wallpaper (it doesn't work, i've tried it), > only .bmps so i'm stuck converting one of my many wallpapers from .jpg > to .bmp, passing that to SystemParametersInfo(), and deleting the > previous .bmp so that i don't have any duplicates. The problem with > this is that other members of my family use this computer too, and > they sometimes set the desktop wallpaper to some other, usually funny > picture they've got stored on the HD, and when I run this little > script it'll delete whatever the current wallpaper is, regardless of > whether its one of mine or not. Any suggestions on how to work around > this problem? Why not rename the file instead of deleting it? > > #random wallpaper changer! > import win32gui #use this to change the wallpaper. > import os > import os.path > import random > import Image > SPI_SETDESKWALLPAPER = 20 ?#It took me WAY too long to find them. > SPI_GETDESKWALLPAPER = 115 #I should keep these handy. > > def RandomlySelectWallpaper(filePaths): > ? ? CurrentWallpaper = > win32gui.SystemParametersInfo(SPI_GETDESKWALLPAPER) > ? ? while True: > ? ? ? ? index = random.randint(0,len(filePaths)-1) > ? ? ? ? RandomlySelectedWallpaper = filePaths[index] > ? ? ? ? if RandomlySelectedWallpaper <> CurrentWallpaper: > ? ? ? ? ? ? break > ? ? print RandomlySelectedWallpaper > ? ? return RandomlySelectedWallpaper #it should be a string... > > def ChangeDesktopWallpaper(RandomlySelectedWallpaper): > ? ? #so the RIGHT way to do this would be to use > ? ? #win32gui.SystemParametersInfo() to change the wallpaper. > ? ? #1) we convert the image to .bmp. > ? ? #Delete the old wallpaper, actual delete occurs after new > wallpaper has been set. > ? ? pathToCurrentWall = > win32gui.SystemParametersInfo(SPI_GETDESKWALLPAPER) > ? ? root,extension = os.path.splitext(RandomlySelectedWallpaper) > ? ? newFileName = root + '.bmp' > ? ? print "Wallpaper to delete: ", pathToCurrentWall > ? ? try: > ? ? ? ? #every so often something goes wrong at this stage in the > script > ? ? ? ? #and I can't figure out what. Something raises an IOError. > ? ? ? ? Image.open(RandomlySelectedWallpaper).save(newFileName) > ? ? ? ? print "File saved!" > ? ? except IOError: > ? ? ? ? print "Error while converting, please check filepath and > permissions." > ? ? ? ? print "Program will restart in an attempt to generate a > correct wallpaper." > ? ? ? ? Main() > ? ? win32gui.SystemParametersInfo(SPI_SETDESKWALLPAPER,newFileName, > 1+2) > ? ? print "Removing: ", pathToCurrentWall > ? ? os.remove(pathToCurrentWall) > > def Main(): > ? ? #woot. > ? ? listOfWallpaperPaths = GenerateListOfWallpapers() > ? ? RandomlySelectedWall = > RandomlySelectWallpaper(listOfWallpaperPaths) > ? ? ChangeDesktopWallpaper(RandomlySelectedWall) > > Main() From ggpolo at gmail.com Thu Aug 28 17:04:25 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 28 Aug 2008 18:04:25 -0300 Subject: Negative regular expressions (searching for "i" not inside command) In-Reply-To: References: Message-ID: On Thu, Aug 28, 2008 at 5:04 PM, Bart Kastermans wrote: > I have a file in which I am searching for the letter "i" (actually > a bit more general than that, arbitrary regular expressions could > occur) as long as it does not occur inside an expression that matches > \\.+?\b (something started by a backslash and including the word that > follows). > > More concrete example, I have the string "\sin(i)" and I want to match > the argument, but not the i in \sin. > > Can this be achieved by combining the regular expressions? I do not > know the right terminology involved, therefore my searching on the > Internet has not led to any results. Try searching again with the "lookahead" term, or "negative lookahead". > > I can achieve something like this by searching for all i and then > throwing away those i that are inside such expressions. I am now just > wondering if these two steps can be combined into one. > > Best, > Bart > -- > http://www.bartk.nl/ > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From vijayakumar.subburaj at gmail.com Tue Aug 5 08:58:37 2008 From: vijayakumar.subburaj at gmail.com (v4vijayakumar) Date: Tue, 5 Aug 2008 05:58:37 -0700 (PDT) Subject: More Datastore Examples Please Message-ID: Google appengine datastore is not very clear, and I couldn't get much from API documents. It would be very helpful if there are some more detailed documents with examples. Django provides very good documentation, but I don't know how much it is compatible with google appengine. Google appengine examples are not using datastore extensively, so this is also not helping much in modeling datastore. wiki.py is using low level APIs, this looks simple but couldn't find any documentation for this. Web search is also not giving anything useful. Can anyone please provide me some URLs where I can find some datastore examples, articles, etc. Thanks in advance. -- posted the same on google-appengine group. cross posting here. http://groups.google.com/group/google-appengine/browse_thread/thread/ae9ba26893c2854d From rstarkov at gmail.com Sat Aug 23 08:05:02 2008 From: rstarkov at gmail.com (rs387) Date: Sat, 23 Aug 2008 05:05:02 -0700 (PDT) Subject: Odd behaviour on importing variable from module Message-ID: <1af3c163-0563-4528-8f63-1ddeff9d19bd@56g2000hsm.googlegroups.com> Hi, I've found the following behaviour on importing a variable from a module somewhat odd. The behaviour is identical in Python 2.5 and 3.0b2. In summary, here's what happens. I have a module, oddmodule.py (below), that defines a variable, OddVariable, by assigning a value A to it. The file I execute, mainfile.py, imports and re-binds OddVariable to a value B. I have two test modules which import the OddVariable in two different ways, one via "import oddmodule" and another via "from oddmodule import OddVariable". The weird behaviour is that by importing using the former syntax, I can see OddVariable bound to B (as expected), but the latter syntax sees it bound A. Is this the intended behaviour? Am I misunderstanding what is going on here? Source code: <<>> print("Importing oddmodule") OddVariable = ["not", "initialized"] def OddFunction(): print(" OddVariable from oddmodule.OddFunction:", OddVariable) <<>> import oddmodule import testmodule1 import testmodule2 print("Initializing OddVariable") oddmodule.OddVariable = ["some", "list"] print() testmodule2.DoTest() print() testmodule1.DoTest() <<>> from oddmodule import OddVariable, OddFunction def DoTest(): print("STARTING testmodule1.DoTest") print(" OddVariable from testmodule1:", OddVariable) OddFunction() print("FINISHED testmodule1.DoTest") <<>> import oddmodule def DoTest(): print("STARTING testmodule2.DoTest") print(" OddVariable from testmodule2:", oddmodule.OddVariable) oddmodule.OddFunction() print("FINISHED testmodule2.DoTest") OUTPUT: Importing oddmodule Initializing OddVariable STARTING testmodule2.DoTest OddVariable from testmodule2: ['some', 'list'] OddVariable from oddmodule.OddFunction: ['some', 'list'] FINISHED testmodule2.DoTest STARTING testmodule1.DoTest OddVariable from testmodule1: ['not', 'initialized'] !!! OLD VALUE !!! OddVariable from oddmodule.OddFunction: ['some', 'list'] FINISHED testmodule1.DoTest Many thanks, Roman From casey.mcginty at gmail.com Wed Aug 27 04:21:37 2008 From: casey.mcginty at gmail.com (Casey) Date: Wed, 27 Aug 2008 01:21:37 -0700 (PDT) Subject: Usual practice: running/testing modules in a package References: <827c7ee5-fad1-4a8c-8724-d6504c91be6d@w1g2000prk.googlegroups.com> Message-ID: <63d32551-7d94-4ab9-9c06-2bd2c8b8e0b8@a3g2000prm.googlegroups.com> On Aug 12, 9:57?pm, alito wrote: > > A wrapper on the level up works: > > ~/python$ cat importercaller.py > from testpackage import config > config.hello() > > ~/python$ python importercaller.py > hello > > So, how do I run these modules without writing a wrapper script for > each one? I just ran into this problem trying to run a package from a local directory. I agree creating another script just to import the local package is a bad solution. Without another option, I would recommend using a Makefile and creating a target to import the package and kickoff the execution: hello: python -c 'from testpackage import config; config.hello()' and then "make hello" to execute the command. From brtzsnr at gmail.com Wed Aug 27 07:58:09 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Wed, 27 Aug 2008 04:58:09 -0700 (PDT) Subject: use of Queue References: <39824ccb-7e35-4ef4-a150-692af64c0ba5@j1g2000prb.googlegroups.com> <7a862160-e64f-4563-8834-50b0ff6087a1@d45g2000hsc.googlegroups.com> Message-ID: On Aug 27, 2:54?pm, Jeff wrote: > Queue raises an Empty exception when there are no items left in the > queue. ?Put the q.get() call in a try block and exit in the except > block. Wrong. What if producer takes a long time to produce an item? Consumers will find the queue empty and exit instead of waiting. > You can also use a condition variable to signal threads to terminate. This is the solution I want to avoid because it duplicates Queue's functionality. I prefer having a clean solution with nice design to hacking Queue class. From ndbecker2 at gmail.com Fri Aug 8 09:50:42 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 08 Aug 2008 09:50:42 -0400 Subject: bbfreeze problem Message-ID: Any ideas on this? bb-freeze test5-coded-pre.py WARNING: found xml.sax in multiple directories. Assuming it's a namespace package. (found in /usr/lib64/python2.5/site-packages/_xmlplus/sax, /usr/lib64/python2.5/xml/sax) *** applied recipe_matplotlib: using the backend_qt4agg matplotlib backend *** applied *** applied *** applied *** applied SKIPPING: SharedLibrary('libgthread-2.0.so.0',) SKIPPING: SharedLibrary('libglib-2.0.so.0',) *** applied *** applied ================================================== The following eggs are being used: Numeric 24.2 (/usr/lib64/python2.5/site-packages/Numeric) configobj 4.5.2 (/usr/lib/python2.5/site-packages/configobj-4.5.2-py2.5.egg) matplotlib 0.91.2 (/usr/lib/python2.5/site-packages/matplotlib-0.91.2-py2.5- linux-x86_64.egg) setuptools 0.6c8 (/usr/lib/python2.5/site-packages/setuptools-0.6c8-py2.5.egg) ================================================== /usr/lib64/python2.5/site-packages/Numeric looks like a development egg. need to run setup.py bdist_egg Traceback (most recent call last): File "/usr/bin/bb-freeze", line 8, in load_entry_point('bbfreeze==0.96.2', 'console_scripts', 'bb-freeze')() File "/usr/lib/python2.5/site-packages/bbfreeze-0.96.2-py2.5-linux- x86_64.egg/bbfreeze/__init__.py", line 18, in main f() File "/usr/lib/python2.5/site-packages/bbfreeze-0.96.2-py2.5-linux- x86_64.egg/bbfreeze/freezer.py", line 516, in __call__ analyzer.copy(self.distdir) File "/usr/lib/python2.5/site-packages/bbfreeze-0.96.2-py2.5-linux- x86_64.egg/bbfreeze/freezer.py", line 138, in copy eggutil.copyDistribution(x, destdir) File "/usr/lib/python2.5/site-packages/bbfreeze-0.96.2-py2.5-linux- x86_64.egg/bbfreeze/eggutil.py", line 132, in copyDistribution raise RuntimeError("setup.py not found for development egg") RuntimeError: setup.py not found for development egg I don't think I'm using matplotlib, don't understand what dragged it in (python -v on my script does _not_ show any matplotlib) From sharon.kim96 at gmail.com Mon Aug 25 12:00:08 2008 From: sharon.kim96 at gmail.com (sharon k) Date: Tue, 26 Aug 2008 00:00:08 +0800 Subject: newbie question In-Reply-To: <00783B36-B09D-40EA-9543-18911CA24C11@uos.de> References: <00783B36-B09D-40EA-9543-18911CA24C11@uos.de> Message-ID: much thanks, your instructions are clear, problem solved! :) On Mon, Aug 25, 2008 at 11:43 PM, Manuel Ebert wrote: > Hi sharon, > > the problem is here that > a = 12,123 > will actually create a tuple with two elements (namely 12 and 123): > >> a = 12,123 > >> a > (12, 123) > > Converting this to a string yields '(12, 123)', which is not what you want > (sounds confusing, bit soon you'll see how many amazing things can be done > like this :-) > > Try: > >> a = "12,123" > >> a = int(a.replace(',', '')) > > I don't know the urllib, but I suppose if you use it to fetch content from > a web page it will return strings anyway. > > > On Aug 25, 2008, at 5:14 PM, sharon k wrote: > > >> >> thank you for your prompt reply. >> >> sorry seems i run into another problem, as follow; >> >> >>> a = 12,123 >> >>> b = str(a) >> >>> c = int(b.replace(',', '')) >> Traceback (most recent call last): >> File "", line 1, in >> ValueError: invalid literal for int() with base 10: '(12 123)' >> >> the comma has become an empty space, it cannot be converted to an integer. >> i try the above in a winxp python command line. >> >> >> On Mon, Aug 25, 2008 at 10:48 PM, Gerhard H?ring wrote: >> sharon k wrote: >> hi all, >> >> i am new to python. >> > >> i fetch a webpage with urllib, extract a few numbers in a format as >> follow; >> >> 10,884 >> 24,068 >> >> my question is how to remove the comma between the number, since i have to >> add them up later. >> >> Strings have a replace method. Calling replace(",", "") on the string will >> do the trick here. >> >> -- Gerhard >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Sun Aug 24 02:59:55 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 24 Aug 2008 08:59:55 +0200 Subject: Imports awareness in Imported modules problem In-Reply-To: <538050a90808231529s61855330r1ec68048847ef241@mail.gmail.com> References: <538050a90808231529s61855330r1ec68048847ef241@mail.gmail.com> Message-ID: Mohamed Yousef wrote: > why am i doing this in the first place > I'm in the process of a medium project where imports of modules start > to make a jungle and i wanted all needed imports to be in a single > file (namely __init__.py) > and then all imports are made once and other modules feel it Python doesn't use a global namespace -- importing a given module into one module doesn't make it visible everywhere else (and trust me, this is a very good thing). (it uses a global module cache, though, so it's only the first import that actually loads the module) > my goal is basically making W() aware of the re module when called > from A to do that, add "import re" to the top of the C module. see this page for a little more on Python's import mechanism: http://effbot.org/zone/import-confusion.htm From paul at boddie.org.uk Wed Aug 13 12:20:00 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 13 Aug 2008 09:20:00 -0700 (PDT) Subject: xcompile patch for python 2.5.2? References: Message-ID: <17d846b0-14fd-4eb6-b0eb-b940b1033a7e@k7g2000hsd.googlegroups.com> On 12 Aug, 19:30, "Stephen Cattaneo" wrote: > > A friend of mine is attempting to cross compile python 2.5.2 onto a > MIPS64 box. He is asking if there is a cross compile patch for 2.5.2. > Do any of you know where He might find such a thing? Try here: http://bugs.python.org/issue1597850 http://bugs.python.org/issue1006238 http://bugs.python.org/issue848910 http://bugs.python.org/issue1115 Some related bugs (not patches): http://bugs.python.org/issue1760089 It wasn't completely straightforward searching the tracker for "cross- compilation", given an apparent lack of certain typical search features which would facilitate the query, but searching for "cross" and doing searches in the page managed to pull up some results. I'm sure this topic has been covered in the newsgroup/list before, however. Paul From deets at nospam.web.de Tue Aug 26 16:54:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Aug 2008 22:54:23 +0200 Subject: Using Python to shared memory resources between Linux and Windows In-Reply-To: References: Message-ID: <6hj8rvFmlbhkU1@mid.uni-berlin.de> Blubaugh, David A. schrieb: > To All, To whom else if I may ask? > I was wondering if it was possible to utilize python to share a memory > resource between a linux and windows system?? It should be stated that > both the Linux (CENTOS 5) and windows are physically located on the same > computer. Is any of this possible? No, not as that. You can use IPC-mechanisums such as XMLRPC, CORBA or Pyro. But software such as VMWare or VirtualBox tries hard to *not* let guest and host os influence each other. Diez From Lie.1296 at gmail.com Wed Aug 6 05:33:21 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 6 Aug 2008 02:33:21 -0700 (PDT) Subject: Print statement isn't showing up? References: <496954360808050909m103fe08ve1b544ca4d289b40@mail.gmail.com> Message-ID: <3ff28b29-5234-4668-bdeb-0d025e60f0d5@q5g2000prf.googlegroups.com> On Aug 6, 2:28?am, "Timothy Grant" wrote: > On Tue, Aug 5, 2008 at 9:09 AM, Robert Dailey wrote: > > Hi, > > > I have the following code: > > > def ReplaceExternalWithCopy( localDir, remoteDir ): > > ? ? print "Removing external local directory:", localDir > > ? ? rmdirs( localDir ) > > ? ? vfxrepo.copy( remoteDir, localDir ) > > > I noticed that the print statement above does not show up before > > vfxrepo.copy() is called. the copy() function (as well as the rmdirs() > > function) are very long file-system calls that take up to 5 minutes. I > > should see a print statement before these are executed, but I do not. > > Instead it shows up *after* the last 2 lines of code have completed. Is > > there something broken about this? > > My guess is that the output is getting buffered and the buffer doesn't > get flushed until sometime after the function executes. > > -- > Stand Fast, > tjg. [Timothy Grant] Are you calling this function from inside, say, doctests-watched comments. From duncan.booth at invalid.invalid Mon Aug 11 13:53:19 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Aug 2008 17:53:19 GMT Subject: dict.update() useful or not? References: <00b06f78$0$14351$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > dict1.update(dict2) is of course equivalent to this code: > > for key, value in dict2.iteritems(): > dict1[key] = value > > Note that it replaces values in dict1 with the value taken from dict2. I > don't know about other people, but I more often want to keep the values > in dict1 regardless of what's in dict2, and only add items from dict2 if > it is new key. Like this: > > for key, value in dict2.iteritems(): > if not dict1.has_key(key): > dict1[key] = value > If you don't actually need to mutate dict1 in-place then just use update for this: d = dict(dict2) d.update(dict1) dict1 = d > There's the faintest of code smells to me. I would prefer to write > something like this: > > def create_request(url, headers): > headers.update(DEFAULT_HEADERS) > req = urllib2.Request(url, None, headers) > # ... > return req > > but of course this second example does the Wrong Thing, replacing > explicit headers with default values. There's a second code smell with that: even if it did what you want it isn't nice to mutate the parameter passed in as headers. What if the caller wants to reuse the headers again for another call? Much nicer just to do: def create_request(url, headers): hdrs = dict(DEFAULT_HEADERS) hdrs.update(headers) req = urllib2.Request(url, None, hdrs) # ... return req From wannymahoots at gmail.com Tue Aug 19 09:29:35 2008 From: wannymahoots at gmail.com (wannymahoots) Date: Tue, 19 Aug 2008 06:29:35 -0700 (PDT) Subject: optparse escaping control characters References: <4001fcc2-e595-4bd6-9baf-c71db3761d36@m3g2000hsc.googlegroups.com> <00bac3a3$0$20315$c3e8da3@news.astraweb.com> Message-ID: <1c780994-b5bc-48c1-90c5-c691e4897d42@56g2000hsm.googlegroups.com> Thanks for all the responses! From support.desk.ipg at gmail.com Mon Aug 11 15:18:26 2008 From: support.desk.ipg at gmail.com (Support Desk) Date: Mon, 11 Aug 2008 14:18:26 -0500 Subject: SSH utility In-Reply-To: References: Message-ID: <018801c8fbe7$09ec5700$a601a8c0@office.ipglobal.net> What about pexpect? http://www.noah.org/wiki/Pexpect -----Original Message----- From: Alan Franzoni [mailto:alan.franzoni.xyz at gmail.com] Sent: Monday, August 11, 2008 5:41 AM To: python-list at python.org Subject: Re: SSH utility James Brady was kind enough to say: > Hi all, > I'm looking for a python library that lets me execute shell commands > on remote machines. > > I've tried a few SSH utilities so far: paramiko, PySSH and pssh; > unfortunately all been unreliable, and repeated questions on their > respective mailing lists haven't been answered... Twisted conch seems to be your last chance :-) -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From emile at fenx.com Fri Aug 8 16:59:08 2008 From: emile at fenx.com (Emile van Sebille) Date: Fri, 08 Aug 2008 13:59:08 -0700 Subject: I need a Python mentor In-Reply-To: References: Message-ID: A. Joseph wrote: > *Please the first message i sent out contain error, i`m very very sorry.* > > > Hello everybody, i`m new to this list. I was programming in PHP before, > so just of recent I started learning python. I need someone who I can be > giving me some assignment based on the chapter I read in the book, and > tell person will sometime review my code and tell me if it well structured. > > > > Can you be my mentor? > > Abah Josep > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list Try the tutor list... http://mail.python.org/mailman/listinfo/tutor Emile From keshet1 at umbc.edu Fri Aug 22 10:42:13 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Fri, 22 Aug 2008 10:42:13 -0400 Subject: 'While' question Message-ID: <48AED045.7080001@umbc.edu> Thanks. I tried to use 'for' instead of 'while' as both of you suggested. It's running well as my previous version but breaks completely instead of just skipping the empty file. I suspect the reason is that this part is inside another 'for' so it stops everything. I just want to it to break only one 'for', that is go back to 5th line in the example code (directory C has one empty file): receptors = ['A', 'B', 'C'] for x in receptors: print x for i in range(3): for r in (7, 9, 11, 13, 15, 17): f = open('c:/Linux/Dock_method_validation/%s/validation/ligand_ran_line_%s_%sA_secondary_scored.mol2' %(x,i,r), 'r') line = f.readline()[:-1] out_file = open('c:/Linux/Dock_method_validation/%s/validation/pockets.out' %(x),'a') out_file.write('%s ' %i) out_file.write('%s ' %r) # skip to scores j=0 for line in f: line = line.rstrip() if "PRIMARY" not in line: j += 1 if j == 20: break else: for line in f: if "TRIPOS" not in line: line = line.rstrip() out_file.write(line) else: break f.close() out_file.close() Any suggestions as for how to control the "extent of break"? should I do something else instead? Thank you! From dwbear75 at gmail.com Fri Aug 22 12:55:05 2008 From: dwbear75 at gmail.com (DwBear75) Date: Fri, 22 Aug 2008 09:55:05 -0700 (PDT) Subject: rules of thumb for cross os code Message-ID: <76c97ae9-2ca0-4419-8630-c7cf6159811a@v16g2000prc.googlegroups.com> I am considering using python as a replacement for a lot of bash scripting that I have been doing. I would like to be as cross platform as possible, writing scripts for both windows and linux. Are there any guides are general rules of thumb on 1) keeping code os independant 2) nifty lambda's or other things to create functions fit for the environment 3) capturing return codes of other executables called from python; ie use os.system, or popen? or ? From zancudero at gmail.com Tue Aug 5 08:54:51 2008 From: zancudero at gmail.com (Alexei Zankevich) Date: Tue, 5 Aug 2008 15:54:51 +0300 Subject: regex question In-Reply-To: References: <6fqqovFcq6bmU1@mid.uni-berlin.de> Message-ID: <7df72c080808050554w7fb1f0a9p53ca5aa4b21c559b@mail.gmail.com> =) Indeed. But it will replace all dots including ordinary strings instead of numbers only. On Tue, Aug 5, 2008 at 3:23 PM, Jeff wrote: > On Aug 5, 7:10 am, Marc 'BlackJack' Rintsch wrote: > > On Tue, 05 Aug 2008 11:39:36 +0100, Fred Mangusta wrote: > > > In other words I'd like to replace all the instances of a '.' character > > > with something (say nothing at all) when the '.' is representing a > > > decimal separator. E.g. > > > > > 500.675 ----> 500675 > > > > > but also > > > > > 1.000.456.344 ----> 1000456344 > > > > > I don't care about the fact the the resulting number is difficult to > > > read: as long as it remains a series of digits it's ok: the important > > > thing is to get rid of the period, because I want to keep it only where > > > it marks the end of a sentence. > > > > > I was trying to do like this > > > > > s=re.sub("[(\d+)(\.)(\d+)]","... ",s) > > > > > but I don't know much about regular expressions, and don't know how to > > > get the two groups of numbers and join them in the sub. Moreover doing > > > like this I only match things like "345.000" and not "1.000.000". > > > > > What's the correct approach? > > > > In [13]: re.sub(r'(\d)\.(\d)', r'\1\2', '1.000.456.344') > > Out[13]: '1000456344' > > > > Ciao, > > Marc 'BlackJack' Rintsch > > Even faster: > > '1.000.456.344'.replace('.', '') => '1000456344' > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From FettManChu at gmail.com Fri Aug 29 08:42:46 2008 From: FettManChu at gmail.com (Fett) Date: Fri, 29 Aug 2008 05:42:46 -0700 (PDT) Subject: eval() == evil? --- How to use it safely? References: <7x4p54zlh2.fsf@ruckus.brouhaha.com> Message-ID: On Aug 28, 7:57?pm, Paul Rubin wrote: So long story short: if I am expecting a dictionary of strings, I should make a parser that only accepts a dictionary of strings then. There is no safe way to use an existing construct. That is what I was afraid of. I know I will have to deal with the possibility of bad data, but considering my use (an acronym legend for a database), and the fact that the site I plan to use should be secure, these issues should be minimal. The users should be able to spot any obvious false data, and restoring it should be simple. Many thanks to all of you for your alarmist remarks. I certainly don't want to, in any way, put my clients computers at risk by providing unsafe code. From straton at lampsacos.demon.co.uk Sun Aug 31 06:19:19 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Sun, 31 Aug 2008 11:19:19 +0100 Subject: Writing to ms excel In-Reply-To: <167fdb5f-e788-4ec9-ad41-369a41c00356@a2g2000prm.googlegroups.com> References: <56aeb3cd-1e37-4242-aefe-8a33452d61a2@q26g2000prq.googlegroups.com> <3msjb412b55hf4i00fvs3gto8lt6kv05na@4ax.com> <167fdb5f-e788-4ec9-ad41-369a41c00356@a2g2000prm.googlegroups.com> Message-ID: John Machin wrote: > On Aug 31, 11:32 am, Marin Brkic wrote: >> Is there a way to access google >> groups through a similiar interface program as a newsreader. > > I don't know (question has never arisen before). > >> Never >> used them before, and getting a lot of messages to my email every day >> does not sound very appealing to me. > > Either (1) you have not looked at the messages at the link that I gave > you or (2) your idea of "a lot of messages" every day differs wildly > from mine. Email alternatives are (a) one message per posting (b) > daily digest (c) none (use your web browser). > > HTH, > John I use thunderbird for private email, mailing lists and newsgroups. It is easy enough to set up filters to divert messages from specific mailing lists to their own directory. Is this adequate for your needs ? (You do get the whole message, not just the header ) From gagsl-py2 at yahoo.com.ar Tue Aug 5 02:40:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 05 Aug 2008 03:40:58 -0300 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> <12072cbe-139a-430f-81aa-b64bc31b43e5@e39g2000hsf.googlegroups.com> <87zlny8cdg.fsf@nokile.rath.org> Message-ID: En Thu, 31 Jul 2008 09:30:19 -0300, Nikolaus Rath escribi?: > oj writes: >> On Jul 31, 11:37?am, Nikolaus Rath wrote: >>> So why does Python distinguish between e.g. the type 'int' and the >>> class 'myclass'? Why can't I say that 'int' is a class and 'myclass' >>> is a type? >> >> I might be wrong here, but I think the point is that there is no >> distinction. A class (lets call it SomeClass for this example) is an >> object of type 'type', and an instance of a class is an object of type >> 'SomeClass'. > > But there seems to be a distinction: > >>>> class int_class(object): > ... pass > ... >>>> int_class > >>>> int > > [...] > If there is no distinction, how does the Python interpreter know when > to print 'class' and when to print 'type'? If it helps you to understand the issue, in Python 3.0 that difference is gone - the word "class" is used on both cases. See http://bugs.python.org/issue2565 -- Gabriel Genellina From sjmachin at lexicon.net Mon Aug 18 03:33:57 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 18 Aug 2008 00:33:57 -0700 (PDT) Subject: How to delete a line with re? References: Message-ID: <7b23ef27-fb02-414c-aed4-a62795833551@b38g2000prf.googlegroups.com> On Aug 18, 4:22?pm, Peter Otten <__pete... at web.de> wrote: > Peng Yu wrote: > > I want to delete the line with abc in the following program. But the > > following program does not do what I want. Can somebody let me know > > how to do it? > > file="""abcd > > efg > > hijk > > lmn > > """ > > > regex = re.compile("^abcd$", re.MULTILINE) > > print regex.sub('', file), > > What /do/ you want? If you want to remove the trailing newline > > regex = re.compile("^abcd$\n?", re.MULTILINE) > > might work. > Not only might work, but does work, including covering the corner cases where the abcd line is immediately followed by (1) an empty line (2) no newline then end-of-file. It is also more elegant [yes, even regular expressions can be elegant] than what I came up with (see below). Hint for the OP: repr() is your friend. >>> import re >>> src="""abcd ... efg ... abcd ... ... hijk ... abcd""" >>> expected = """efg ... ... hijk ... """ >>> print repr(src) 'abcd\nefg\nabcd\n\nhijk\nabcd' >>> print repr(expected) 'efg\n\nhijk\n' >>> for pattern in ["^abcd$\n?", r"^abcd(\n|\Z)"]: ... regex = re.compile(pattern, re.MULTILINE) ... actual = regex.sub('', src) ... print repr(actual) ... print actual == expected ... 'efg\n\nhijk\n' True 'efg\n\nhijk\n' True >>> Cheers, John From castironpi at gmail.com Sat Aug 9 14:58:57 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 9 Aug 2008 11:58:57 -0700 (PDT) Subject: Fastest way to store ints and floats on disk References: <489B41CE.8080909@shopzeus.com> Message-ID: <1ad14df7-09ea-4b1d-8fac-3025bdd2d522@f63g2000hsf.googlegroups.com> On Aug 7, 2:27?pm, "M.-A. Lemburg" wrote: > On 2008-08-07 20:41, Laszlo Nagy wrote: > > > > > > > ?Hi, > > > I'm working on a pivot table. I would like to write it in Python. I > > know, I should be doing that in C, but I would like to create a cross > > platform version which can deal with smaller databases (not more than a > > million facts). > > > The data is first imported from a csv file: the user selects which > > columns contain dimension and measure data (and which columns to > > ignore). In the next step I would like to build up a database that is > > efficient enough to be used for making pivot tables. Here is my idea for > > the database: > > > Original CSV file with column header and values: > > > "Color","Year","Make","Price","VMax" > > Yellow,2000,Ferrari,100000,254 > > Blue,2003,Volvo,50000,210 > > > Using the GUI, it is converted to this: > > > dimensions = [ > > ? ?{ 'name':'Color', 'colindex:0, 'values':[ 'Red', 'Blue', 'Green', > > 'Yellow' ], }, > > ? ?{ 'name':'Year', colindex:1, 'values':[ > > 1995,1999,2000,2001,2002,2003,2007 ], }, > > ? ?{ 'name':'Make', colindex:2, 'value':[ 'Ferrari', 'Volvo', 'Ford', > > 'Lamborgini' ], }, > > ] > > measures = [ > > ? ?{ 'name', 'Price', 'colindex':3 }, > > ? ?{ 'name', 'Vmax', 'colindex':4 }, > > ] > > facts = [ > > ? ?( (3,2,0),(100000.0,254.0) ?), # ( dimension_value_indexes, > > measure_values ) > > ? ?( (1,5,1),(50000.0,210.0) ), > > ? .... # Some million rows or less > > ] > > > The core of the idea is that, when using a relatively small number of > > possible values for each dimension, the facts table becomes > > significantly smaller and easier to process. (Processing the facts would > > be: iterate over facts, filter out some of them, create statistical > > values of the measures, grouped by dimensions.) > > > The facts table cannot be kept in memory because it is too big. I need > > to store it on disk, be able to read incrementally, and make statistics. > > In most cases, the "statistic" will be simple sum of the measures, and > > counting the number of facts affected. To be effective, reading the > > facts from disk should not involve complex conversions. For this reason, > > storing in CSV or XML or any textual format would be bad. I'm thinking > > about a binary format, but how can I interface that with Python? > > > I already looked at: > > > - xdrlib, which throws me DeprecationWarning when I store some integers > > - struct which uses format string for each read operation, I'm concerned > > about its speed > > > What else can I use? > > ?>>> import marshal > ?>>> marshal.dump(1, open('test.db', 'wb')) > ?>>> marshal.load(open('test.db', 'rb')) > 1 > > It also very fast at dumping/loading lists, tuples, dictionaries, > floats, etc. Depending on how hard-core you want to be, store the int, float, string, and long C structures directly to disk, at a given offset. Either use fixed-length strings, or implement (or find) a memory manager. Anyone have a good alloc-realloc-free library, C or Python? From alexnbryan at gmail.com Fri Aug 29 17:38:20 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Fri, 29 Aug 2008 16:38:20 -0500 Subject: Google License Keys for pyGoogle Message-ID: <473EBAC0-3227-428A-8AA6-489D5A006D14@gmail.com> I know this isn't the right mailing list, but it saves me the hassle of signing up for another one if someone on here knows. I have never used pyGoogle before, and I just read that google isn't giving out license keys anymore? If that is the case, can I still get pygoogle to work another way? if you know anything please help me out! From wgwigw at gmail.com Wed Aug 20 22:57:39 2008 From: wgwigw at gmail.com (momobear) Date: Wed, 20 Aug 2008 19:57:39 -0700 (PDT) Subject: what's wrong with www.planetpython.org? Message-ID: <05cddf90-f72b-487b-82df-a52eccdaec68@i20g2000prf.googlegroups.com> hi, Does anyone know why the www.planetpython.org could not be connected recently? thanks. From fredrik at pythonware.com Wed Aug 13 11:39:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Aug 2008 17:39:34 +0200 Subject: You advice please In-Reply-To: <48A2FBAC.3000103@wiggly.org> References: <20080813110444.7b48ddbc.darcy@druid.net> <76fd5acf0808130811y7d7d6584m721096295a72af98@mail.gmail.com> <48A2FBAC.3000103@wiggly.org> Message-ID: Nigel Rantor wrote: > Throwaway comments like yours that are pithy, emotional and devoid of > any factual content are just the kind of thing that makes lists such as > this less useful than they could be. Oh, please. It's a fact that Python advocacy is a lot more low-key than the advocacy of certain potentially competing technologies. It's always been that way. Too many Europeans involved, most likely. > Have you read this list? > > I would suggest your comment indicates not. This list is a Python forum. Calvin (who's a long time contributor to this forum, which you would have known if you'd actually followed the list for some time) was talking about the real world. From notvalid2 at sbcglobal.net Sat Aug 23 02:10:42 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Fri, 22 Aug 2008 23:10:42 -0700 Subject: Filling in Degrees in a Circle (Astronomy) In-Reply-To: References: Message-ID: Maric Michaud wrote: > Le Saturday 23 August 2008 01:12:48 W. eWatson, vous avez ?crit : >> The other night I surveyed a site for astronomical use by measuring the >> altitude (0-90 degrees above the horizon) and az (azimuth, 0 degrees north >> clockwise around the site to 360 degrees, almost north again) of obstacles, >> trees. My purpose was to feed this profile of obstacles (trees) to an >> astronomy program that would then account for not sighting objects below >> the trees. >> >> When I got around to entering them into the program by a file, I found it >> required the alt at 360 azimuth points in order from 0 to 360 (same as 0). >> Instead I have about 25 points, and expected the program to be able to do >> simple linear interpolation between those. >> >> Is there some simple operational device in Python that would allow me to >> create an array (vector) of 360 points from my data by interpolating >> between azimuth points when necessary? All my data I rounded to the nearest >> integer. Maybe there's an interpolation operator? >> >> As an example, supposed I had made 3 observations: (0,0) (180,45) and >> (360,0). I would want some thing like (note the slope of the line from 0 to >> 179 is 45/180 or 0.25): >> alt: 0, 0.25, 0.50, 0.75, ... 44.75, 45.0 >> az : 0, 1, 2, 3, 180 >> >> Of course, I don't need the az. > > Not sure I got it, but is that fulfill your specs ? > >>>> [20]: def interpolate(a, b) : > slope = float(b[1] - a[1]) / (b[0] - a[0]) > return [ slope * float(i) for i in xrange(b[0]-a[0] + 1) ] > ....: > >>>> [23]: interpolate((0, 0), (180, 45)) > ...[23]: > [0.0, > 0.25, > 0.5, > 0.75, > .... > 44.5, > 44.75, > 45.0] > >>>> [29]: interpolate((80, 20), (180, 45)) > [0.0, > 0.25, > 0.5, > 0.75, > 1.0, > 1.25, > ... > 24.5, > 24.75, > 25.0] > > > Yes, the interpolation part looks right, but the tricky part is to be able to go through the list and find where one needs to generate all the missing az angles. A chunk of my data is in a post above yours. Here's a more revealing set of data where four data points are known: az el 0 10 4 14 (slope is 1) 12 30 (slope is 2) 15 15 (slope is -5) 16 points need to be generated, 0 to 15, representing 15 degrees around the circle. So, I'm doing this in my head, one would get 0 10 (slope is 1) 1 11 2 12 3 13 4 14 5 16 (slope is 2) 6 18 7 18 ... 12 30 13 25 14 20 15 15 I use Python occasionally, and starting up requires some effort, but I've finally decided to take a go at this. I'm working on this now, but my knowledge of python needs refreshing. Right now I have a file of all the az,el data I've collected, and I'd like to open it with Python for XP. However, Python doesn't like this: junkfile = open('c:\tmp\junkpythonfile','w') I get junkfile = open('c:\tmp\junkpythonfile','w') IOError: [Errno 2] No such file or directory: 'c:\tmp\\junkpythonfile' This problematic segment is just a hack of a similar statement which has the same problem and a much longer path. I suspect the problem is with the back slash. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From fredrik at pythonware.com Sun Aug 17 15:37:40 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 17 Aug 2008 21:37:40 +0200 Subject: like a "for loop" for a string In-Reply-To: <19022155.post@talk.nabble.com> References: <19022098.post@talk.nabble.com> <19022155.post@talk.nabble.com> Message-ID: Alexnb wrote: > Ya just an example, to print the numbers 1-5 Sorry, I still don't have the slightest idea what you expect the code to do. >>> But I am wondering is there a way to something like this: >>> >>> funString = "string string string non-string non-string string" >>> and >>> for "string" in funString: >>> print something >>> >>> I know you can't do that; but, is there a way do do something similar >>> that >>> gets the same result? >> >> you seem to have forgotten to specify the result. or did you mean that >> the above should print 1-5? From daniel.watrous at gmail.com Wed Aug 27 13:41:25 2008 From: daniel.watrous at gmail.com (Daniel) Date: Wed, 27 Aug 2008 10:41:25 -0700 (PDT) Subject: problem with packages and path References: <8c1351f9-d349-4c0c-97a4-024c9472bff3@z11g2000prl.googlegroups.com> <2c0bf7a4-16d2-43ca-9f7e-fce000fa626a@34g2000hsh.googlegroups.com> Message-ID: <736acf59-d6e1-40cd-8b56-496fce6cee26@n38g2000prl.googlegroups.com> On Aug 27, 11:00?am, Paul Boddie wrote: > On 27 Aug, 18:44, Daniel wrote: > > > > > I'm writing some unit tests for my python software which uses > > packages. ?Here is the basic structure: > > > mypackage > > [...] > > > ? unittests > > ? ? __init__.py > > ? ? alltests.py > > ? ? test1.py > > ? ? test2.py > > > within alltests.py I would expect to be able to "import > > mypackage.unittests.test1". ?In fact within PyScripter this works as > > expected. ?However, when I execute the code from the command line, I > > get the following error: > > > ImportError: No module named mypackage.unittests.test1 > > One thing to note: if you are running alltests.py directly (which you > don't mention explicitly) then even if you do so from the directory > containing the root of the package hierarchy (mypackage), it will be > the directory containing alltests.py (unittests) which will appear on > the PYTHONPATH/sys.path. Sometimes it's easy to take this behaviour > for granted when running programs. > > A question: what happens if you prepend the directory containing the > root of package hierarchy to sys.path using insert (at element 0) > rather than append? > > Paul I changed it to 'sys.path.insert(0, newpath)', as you suggest, but it doesn't fix the error. I did notice that the directory containing the file alltests.py ends up in the path. I've also noticed that (in WinXP at least) the sys.path modification inserts a '..' in the path, rather than the full path to 'mypackage'. I'm not sure if this makes a difference, but it seems like I should be able to add either '..' or 'path/to/mypackage' to the path and have it find my packages. Any more suggestions? From lists at svrinformatica.it Thu Aug 21 06:56:33 2008 From: lists at svrinformatica.it (Mailing List SVR) Date: Thu, 21 Aug 2008 12:56:33 +0200 Subject: Distinguish file and folder on ftp site In-Reply-To: References: <1218700228.7851.1.camel@localhost.localdomain> Message-ID: <1219316193.8260.1.camel@localhost.localdomain> Il giorno gio, 14/08/2008 alle 10.08 +0200, Fredrik Lundh ha scritto: > Mailing List SVR wrote: > > > is there a simple way to do this? > > > > ftplib seems unable to distinguish between files and dir, a mimetype > > check would be good, > > the FTP protocol doesn't specify the format for the output from the LIST > command, so you have to use some heuristics; see e.g. the code in > > http://svn.python.org/projects/python/trunk/Tools/scripts/ftpmirror.py > > or use a wrapper for Dan Bernstein's ftpparse library (requires a C > compiler): > > http://cr.yp.to/ftpparse.html > http://c0re.23.nu/c0de/ftpparsemodule/ > http://effbot.org/downloads/#ftpparse > ftpparse seems broken, I found ftputil as the best solution, thanks Nicola > Not sure what you mean by "mimetype"; that has nothing to do with > directories vs. files, afaik. > > > > -- > http://mail.python.org/mailman/listinfo/python-list From samuel.morhaim at gmail.com Wed Aug 13 18:30:40 2008 From: samuel.morhaim at gmail.com (Samuel Morhaim) Date: Wed, 13 Aug 2008 18:30:40 -0400 Subject: Can't use DB name with dashes using pymssql ??? In-Reply-To: <65c3648d0808131354x333a7e0cica29217a26f4ce42@mail.gmail.com> References: <65c3648d0808131354x333a7e0cica29217a26f4ce42@mail.gmail.com> Message-ID: <65c3648d0808131530w29728a78ib646dde89481e656@mail.gmail.com> I believe there is a bug in Python.. _mssql ... I am not too familiar with Python yet, but after adding several breakpoints and watching the variable, the last step of pymssql.py is # open the connection con = _mssql.connect(dbhost, dbuser, dbpasswd) con.select_db(dbbase) At this point the contents of dbbase is "Gcare4UI-B6_3_dev" (no quotes)... however, the immediate error is that "Gcare4UI" does not exist. Again removing the DASH from Gcare4UI-B6_3_dev and turning it into Gcare4UIB6_3_dev results in error that can't find DB Gcare4UIB6_3_dev (of course because the DB without the - doesnt exist... ) please help... thanks. On Wed, Aug 13, 2008 at 4:54 PM, Samuel Morhaim wrote: > I tried: > > import sys > import pymssql > > db = 'Gcare4UI-B6_3_dev' > > conn = pymssql.connect (host = "localhost", > user = "myname", > password = "mypassword", > database = db) > > > > And this returns an error saying > Could not locate entry in sysdatabases for database 'Gcare4UI'. No entry > found with that name. > > It is not reading the db name after the Dash... if i remove the dash from > the db to see what happens, it shows this obvious error, because it doesnt > exist... i was just making sure the problem was with the dash > > Could not locate entry in sysdatabases for database 'Gcare4UIB6_3_dev'. No > entry found with that name. > > Anyone had this problem? > > Thanks. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Aug 21 11:40:41 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 21 Aug 2008 17:40:41 +0200 Subject: semantics of the |= operator References: <16f69c9c-386f-41a3-852a-cd482327fc2d@c58g2000hsc.googlegroups.com> Message-ID: <6h5glcFitoeuU1@mid.uni-berlin.de> akva wrote: > Hi All, > > what's the exact semantics of the |= operator in python? > It seems that a |= d is not always equivalent to a = a | d > > For example let's consider the following code: > > def foo(s): > s = s | set([10]) > > def bar(s): > s |= set([10]) > > s = set([1,2]) > > foo(s) > print s # prints set([1, 2]) > > bar(s) > print s # prints set([1, 2, 10]) > > So it appears that inside bar function the |= operator modifies the > value of s in place rather than creates a new value. Yes. That's the exact purpose of the in-place operators when they deal with mutable objects. What else did you expect? Now of course this behaves different: def foo(x): x += 1 y = 100 foo(y) print y will result in y still being 100, as the value 101 that is bound to x inside foo is *not* re-bound to the name y in the outer scope. This is because numbers (and strings and tuples) are immutables, and thus the operation won't modify the 100 in place to become 101, instead return a new object. Diez From wuwei23 at gmail.com Fri Aug 1 01:16:10 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 31 Jul 2008 22:16:10 -0700 (PDT) Subject: how to split text into lines? References: <7ed81072-aaf1-4e06-98b5-e6fa94268cbd@r66g2000hsg.googlegroups.com> Message-ID: <99ec6d87-e204-4ffe-a573-a8e681a072f0@q5g2000prf.googlegroups.com> Chris wrote: > or what about 'string'.splitlines(True) as that retains newline > characters. ;) Okay, you win :) Man, you'd think with the ease of object introspection I'd have at least looked at its docstring :) Cheers, Chris! From gagsl-py2 at yahoo.com.ar Wed Aug 20 05:09:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 20 Aug 2008 06:09:18 -0300 Subject: IDLE issue References: <73045cca0808200056r68a015c0sd41365627ddc1298@mail.gmail.com> Message-ID: En Wed, 20 Aug 2008 04:56:32 -0300, aditya shukla escribi?: > I found something interesting while working in idle.I have windows vista > and > python2.5 > > if i do > import subprocess > proc > =subprocess.Popen('cmd.exe',stdin=subprocess.PIPE,stdout=subprocess.PIPE) > output = proc.communicate('dir\n')[0] > print repr(output) > > This dosen't work in idle Works fine for me, using Windows XP If you're pasting those lines directly over the shell window, beware of this bug: http://bugs.python.org/issue3559 -- Gabriel Genellina From josephtys86 at googlemail.com Sat Aug 9 12:19:42 2008 From: josephtys86 at googlemail.com (josephtys86 at googlemail.com) Date: Sat, 9 Aug 2008 09:19:42 -0700 (PDT) Subject: Extract string from log file References: Message-ID: <5ae1a663-cd2c-4419-a046-9739d927cf9d@p31g2000prf.googlegroups.com> On Aug 9, 11:22?pm, Edwin.Mad... at VerizonWireless.com wrote: > from each line separate out url and request parts. split the request into key-value pairs, use urllib to unquote key-value pairs......as show below... > > import urllib > line = "GET /stat.gif?stat=v&c=F-Secure&v=1.1%20Build%2014231&s=av%7BNorton%20360%20%28Symantec%20Corporation%29+69%3B%7Dsw%7BNorton%20360%20%28Symantec%20Corporation%29+69%3B%7Dfw%7BNorton%20360%20%28Symantec%20Corporation%29+5%3B%7Dv%7BMicrosoft%20Windows%20XP+insecure%3BMicrosoft%20Windows%20XP%20Professional+f%3B26027%3B26447%3B26003%3B22452%3B%7D&r=0.9496 HTTP/1.1" > words = line.split() > for word in words: > if word.find('?') >= 0: > ? ? ? ? req = word[word.find('?') + 1:] > ? ? ? kwds = req.split('&') > ? ? ? for kv in kwds: > ? ? ? ? print urllib.unquote(kv) > > stat=v > c=F-Secure > v=1.1 Build 14231 > s=av{Norton 360 (Symantec Corporation)+69;}sw{Norton 360 (Symantec Corporation)+69;}fw{Norton 360 (Symantec Corporation)+5;}v{Microsoft Windows XP+insecure;Microsoft Windows XP Professional+f;26027;26447;26003;22452;} > r=0.9496 > > good luck > Edwin > > -----Original Message----- > From: python-list-bounces+edwin.madari=verizonwireless.... at python.org > > [mailto:python-list-bounces+edwin.madari=verizonwireless.... at python.org] > On Behalf Of josephty... at googlemail.com > Sent: Saturday, August 09, 2008 10:48 AM > To: python-l... at python.org > Subject: Extract string from log file > > 203.114.10.66 - - [01/Aug/2008:05:41:21 +0300] "GET /stat.gif? > stat=v&c=F-Secure&v=1.1%20Build%2014231&s=av%7BNorton > %20360%20%28Symantec%20Corporation%29+69%3B%7Dsw%7BNorton > %20360%20%28Symantec%20Corporation%29+69%3B%7Dfw%7BNorton > %20360%20%28Symantec%20Corporation%29+5%3B%7Dv%7BMicrosoft%20Windows > %20XP+insecure%3BMicrosoft%20Windows%20XP%20Professional+f > %3B26027%3B26447%3B26003%3B22452%3B%7D&r=0.9496 HTTP/1.1" 200 43 > "http://dfstage1.f-secure.com/fshc/1.1/release/devbw/1.1.14231/ > card.html" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; > SV1; .NET CLR 2.0.50727)" > > does anyone know how can i extract certain string from this log file > using regular expression in python or using XML. can teach me. > --http://mail.python.org/mailman/listinfo/python-list > > The information contained in this message and any attachment may be > proprietary, confidential, and privileged or subject to the work > product doctrine and thus protected from disclosure. ?If the reader > of this message is not the intended recipient, or an employee or > agent responsible for delivering this message to the intended > recipient, you are hereby notified that any dissemination, > distribution or copying of this communication is strictly prohibited. > If you have received this communication in error, please notify me > immediately by replying to this message and deleting it and all > copies and backups thereof. ?Thank you. > > do you mind to explain further. based on the source code that you gave me. what will it output. i wonder. Sorry i am new to string extraction. i do understand your python coding. the only thing i don't understand is this part. for word in words: if word.find('?') >= 0: req = word[word.find('?') + 1:] kwds = req.split('&') for kv in kwds: print urllib.unquote(kv) what does this code do? anyway, is this code automatic. what i mean is can it extract the string everytime when a new log file is being output by the sever? From emile at fenx.com Tue Aug 26 15:23:27 2008 From: emile at fenx.com (Emile van Sebille) Date: Tue, 26 Aug 2008 12:23:27 -0700 Subject: Renaming Excel Spreadsheets In-Reply-To: References: Message-ID: Greg Lindstrom wrote: > Hello, > > I am working with Python to create Excel spreadsheets and have run into > a couple of problems I hope you can help me with. > > First...are there any bindings/libraries into Open Office? > > Now, back to Excel. > > --> Does anyone know a way to create N worksheets? By default, 3 are > created, but I would like more. > > --> Is it possible to rename a worksheet inside of the workbook (change > "Sheet1" to "July 08", for example). Here's some code from years back that adds sheets to a workbook and then renames them. Sheets = [["SlsSrce",None,1], ["SalesReps",None,1], ["Control",None,1]] replist = [] for k in repkeys: if k in currentReps: replist.append([k, reps[k]]) Sheets.append(['Rep-%s' % k, None, 1]) def WorkBookSetup(Sheets): # xl.Visible = 1 wbi = xl.Workbooks.Add() wbi.Activate() sheetcount = xl.Sheets.Count index = 0 for name, ref, nextline in Sheets: if index >= sheetcount: wbi.Sheets.Add() index = index + 1 index = 0 for name, ref, nextline in Sheets: wbi.Sheets[index].Name = name Sheets[index][1] = wbi.Sheets[index] index = index + 1 return wbi HTH, Emile From blog335 at watchesblog.cn Wed Aug 27 23:34:06 2008 From: blog335 at watchesblog.cn (blog335 at watchesblog.cn) Date: Wed, 27 Aug 2008 20:34:06 -0700 (PDT) Subject: A Lange & Sohne Grand Lange 1 Watches: Quality A Lange & Sohne Discount Watches Message-ID: <049b20ff-d68f-4b54-b44d-8cb4c4a1a6d2@p31g2000prf.googlegroups.com> A Lange & Sohne Grand Lange 1 Watches: Quality A Lange & Sohne Discount Watches Quality A Lange & Sohne Grand Lange 1 Watches http://a-lange-sohne-watches.pxhelp.com/a-lange-sohne-grand-lange-1.html Thank you for choosing http://www.pxhelp.com/ Discount A Lange & Sohne Watches http://a-lange-sohne-watches.pxhelp.com/ We guarantee our A Lange & Sohne Grand Lange 1 Watches and A Lange & Sohne Grand Lange 1 Luxury Watches aren't just a simple imitation. We use the same fine materials and technology that the original does. Each A Lange & Sohne Grand Lange 1 Watch produced is examined carefully by our quality test department and every watch is inspected again before being moved out from our warehouse. It is our heartfelt desire that you do experience the joy of shopping when buying one of our A Lange & Sohne Watches at our site http://www.pxhelp.com/ . We guarantee high quality and favorable price we offer. Best service you will receive from us. Any question please contact with us, we are happy to service for you. A Lange & Sohne Grand Lange 1 Watches Items : A Lange & Sohne Grand Lange 1 Luminous Mens Watch 115.029 http://a-lange-sohne-watches.pxhelp.com/A-Lange-Sohne-wristwatch-19.html A Lange & Sohne Grand Lange 1 Mens Watch 115.031 http://a-lange-sohne-watches.pxhelp.com/A-Lange-Sohne-wristwatch-20.html A Lange & Sohne Grand Lange 1 Mens Watch 115.021 http://a-lange-sohne-watches.pxhelp.com/A-Lange-Sohne-wristwatch-21.html A Lange & Sohne Grand Lange 1 Mens Watch 115.032 http://a-lange-sohne-watches.pxhelp.com/A-Lange-Sohne-wristwatch-22.html A Lange & Sohne Grand Lange 1 Mens Watch 115.022 http://a-lange-sohne-watches.pxhelp.com/A-Lange-Sohne-wristwatch-23.html A Lange & Sohne Grand Lange 1 Mens Watch 115.025 http://a-lange-sohne-watches.pxhelp.com/A-Lange-Sohne-wristwatch-35.html A Lange & Sohne Grand Lange 1 Mens Watch 115.026 http://a-lange-sohne-watches.pxhelp.com/A-Lange-Sohne-wristwatch-36.html From nospam at invalid.com Wed Aug 6 20:05:02 2008 From: nospam at invalid.com (Jack) Date: Wed, 6 Aug 2008 17:05:02 -0700 Subject: benchmark Message-ID: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> I know one benchmark doesn't mean much but it's still disappointing to see Python as one of the slowest languages in the test: http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy/ From me at jonbowlas.com Tue Aug 12 08:19:00 2008 From: me at jonbowlas.com (Jon Bowlas) Date: Tue, 12 Aug 2008 13:19:00 +0100 Subject: Help counting the total number of dictionaries inside a list that contain a specified key value In-Reply-To: <8d37bc060808120506n5e94819cp42b99c048bffc903@mail.gmail.com> References: <8d37bc060808120409r70fb5469kb56186b812dcc434@mail.gmail.com> <8d37bc060808120506n5e94819cp42b99c048bffc903@mail.gmail.com> Message-ID: <8d37bc060808120519n7f7cefban136469c49265391a@mail.gmail.com> Hrmm, any ideas why I'd be getting 'SyntaxError: invalid syntax' for both of these? > sum(u'Level 2 Courses' in dct for dct in yourlist) > q = set(['1']); print q, sum(d.get('level') in q for d in thelist) The error occurs at the 'for' I'm afraid I can't use Peters suggestion as I'm using python 2.3 and it doesn't have the collection module. Thanks anyway. Cheers Jon 2008/8/12 Jon Bowlas : > Many thanks for all your reponses, much appreciated. > > I'll get back to you on which is the best for me. > > BTW - yes John thats exactly what I wanted. > > Cheers > > Jon > > Jon Bowlas wrote: >> For example I'd like to kow how many dictionaries there are with a >> level 1, 2 , 23 & 3 etc. How would one go about achieveing this? >> >> Hope someone can help. > > sum(u'Level 2 Courses' in dct for dct in yourlist) > > Christian > > 2008/8/12 Jon Bowlas : >> Hi All, >> >> I have the following list containing dictionaries and I would like to >> be able to count the total number of dictionaries I have that contain >> a certain value set for the 'level' key: >> >> [{'mod_title': u'Introduction to Human Anatomy', 'level': u'1', >> 'modcode': u'ANAT1003', 'deptleveltext': u'', 'deptlevelheader': >> u'Level 1 Courses', 'subj_code': u'AE'}, {'mod_title': u'Developmental >> Neurobiology', 'level': u'2', 'modcode': u'ANAT2008', 'deptleveltext': >> u'', 'deptlevelheader': u'Level 2 Courses', 'subj_code': u'AE'}, >> {'mod_title': u'Human Neuroanatomy', 'level': u'2', 'modcode': >> u'ANAT2010', 'deptleveltext': u'', 'deptlevelheader': u'Level 2 >> Courses', 'subj_code': u'AE'}, {'mod_title': u'Human Anatomy and >> Embryology', 'level': u'2', 'modcode': u'ANAT2050', 'deptleveltext': >> u'', 'deptlevelheader': u'Level 2 Courses', 'subj_code': u'AE'}, >> {'mod_title': u'Ethics of Fertility and Embryo Research', 'level': >> u'2', 'modcode': u'ANAT2099', 'deptleveltext': u'', 'deptlevelheader': >> u'Level 2 Courses', 'subj_code': u'AE'}, {'mod_title': u"Man's Place >> in Nature 1750-1900", 'level': u'23', 'modcode': u'HMED3001', >> 'deptleveltext': u'', 'deptlevelheader': u'Level 2/3 Courses', >> 'subj_code': u'AE'}, {'mod_title': u'Medicine, Disease and Society, >> Antiquity to Renaissance ', 'level': u'23', 'modcode': u'HMED3003', >> 'deptleveltext': u'', 'deptlevelheader': u'Level 2/3 Courses', >> 'subj_code': u'AE'}, {'mod_title': u'Madness and Society', 'level': >> u'23', 'modcode': u'HMED3004', 'deptleveltext': u'', >> 'deptlevelheader': u'Level 2/3 Courses', 'subj_code': u'AE'}] >> >> For example I'd like to kow how many dictionaries there are with a >> level 1, 2 , 23 & 3 etc. How would one go about achieveing this? >> >> Hope someone can help. >> >> Cheers >> >> Jon >> > From cs at zip.com.au Mon Aug 4 00:10:38 2008 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 4 Aug 2008 14:10:38 +1000 Subject: Teething troubles with Python on a Mac In-Reply-To: Message-ID: <20080804041038.GA25764@cskk.homeip.net> On 03Aug2008 23:14, Avinash Vora wrote: >> You will likely cause more problems updating the system python than >> managing the two separate installations. > > That's sadly worrying. It shouldn't be. It is often useful to have multiple versions of stuff installed. Replacing the system stuff means playing in the vendor/distributor's namespace, and you may expect they to cheerfully and freely tread all over your changes if something in Software Update wants to. By keeping a separate Python install you know you are not damaging the system, and the system will not damage you. Personally I use python 2.5 from the macports stuff, which installs to /opt/local. Neatly out of the way. It's all very easy. >> OSX relies on the version of python they ship. > > I think that helps my point--there *are* bug fixes between major > versions despite the new language changes, and that can really only be a > good thing. No, it does not help your point. The OS may rely on a _bug_! It is best to keep the OS and the stuff it uses pristine, because the two parts are shaped to fit each other. They work now, and you're changing something that works. Whether an "upgrade" changes a bug or a feature is irrelevant - it changes behaviour. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Zombies don't get pumped. - Jake, in rec.climbing From dullrich at sprynet.com Tue Aug 5 14:28:26 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 05 Aug 2008 13:28:26 -0500 Subject: Psycho question Message-ID: Just heard about Psycho. I've often wondered why someone doesn't make something that does exactly what Psycho does - keen. Silly question: It's correct, is it not, that Psycho doesn't actually modify the Python installation, except by adding a module or two (so that code not using Psycho is absolutely unaffected)? Thanks, -- David C. Ullrich From adityashukla1983 at gmail.com Tue Aug 19 21:06:13 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Tue, 19 Aug 2008 20:06:13 -0500 Subject: Subprocess module question. Message-ID: <73045cca0808191806r1277669fyba9299451e62a7a5@mail.gmail.com> Hello folks, I am using windows vista and i am trying to communicate with various processes. so when i do import subprocess proc=subprocess.Popen('cmd.exe') --This opens the command prompt But when i do proc=subprocess.Popen('netscan.exe') it gives an error Traceback (most recent call last): File "", line 1, in proc =subprocess.Popen('netscan.exe') File "C:\Python25\lib\subprocess.py", line 594, in __init__ errread, errwrite) File "C:\Python25\lib\subprocess.py", line 816, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified However "netscan.exe" is present on my system. Some please explain why does this happens? Thanks in advance Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From arkanes at gmail.com Tue Aug 26 12:59:15 2008 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 26 Aug 2008 11:59:15 -0500 Subject: Are dictionaries the same as hashtables? In-Reply-To: References: <20080826074338.GB10162@marcher.name> Message-ID: <4866bea60808260959g2162f982yf43dab073cb3a97d@mail.gmail.com> On Tue, Aug 26, 2008 at 11:12 AM, Fredrik Lundh wrote: > Martin Marcher wrote: > >>> Are dictionaries the same as hashtables? >> >> Yes, but there is nothing in there that does sane collision handling >> like making a list instead of simply overwriting. > > are you sure you know what "collision handling" means in this context? I think the confusion comes from thinking that dictionaries are (really) hash tables and thus that things like collision handling are exposed to the user of the data structure. In this sense, no, dictionaries are *not* hash tables. They are mappings of keys to values, and they use hash tables as part of their implementation. From raashid_hbk at yahoo.com Sun Aug 17 14:00:10 2008 From: raashid_hbk at yahoo.com (raashid bhatt) Date: Sun, 17 Aug 2008 11:00:10 -0700 (PDT) Subject: how to call API Functions in python Message-ID: <46c57206-49a8-48b1-966f-2beab4ac433e@w24g2000prd.googlegroups.com> how to call API Functions in python From nytrokiss at gmail.com Thu Aug 21 13:14:37 2008 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 21 Aug 2008 10:14:37 -0700 Subject: Read PDF content In-Reply-To: References: Message-ID: <8a6b8e350808211014h216adc76g9e17f0d86941244b@mail.gmail.com> You can also use pdflib http://www.pdflib.com/download/pdflib-family/pdflib-7/ On Thu, Aug 21, 2008 at 6:47 AM, William Purcell wrote: > Sorry, this last email was meant to be to the list. > > On Thu, Aug 21, 2008 at 8:41 AM, William Purcell < > williamhpurcell at gmail.com> wrote: > >> I have been trying to do the same thing. Here is something I came up with, >> although it's not completely dependent on Python. It requires pdftotext to >> be installed. If your on a linux box, I think it comes in xpdf-utils but I'm >> not comletely sure. Anyway, install pdftotext and then you could use this >> function: >> >> ---------------------------------------------------------------------------- >> import os >> >> def readpdf(filepath): >> cmd = 'pdftotext -layout %s -'%(filepath,) >> lines=os.popen(cmd).readlines() >> return lines >> >> ---------------------------------------------------------------------------- >> I would like to find something totally Python, but this has worked for me >> in a pinch. >> -Bill >> >> >> On Thu, Aug 21, 2008 at 5:00 AM, AON LAZIO wrote: >> >>> Hi, Guys. >>> I am trying to extract the PDF file content(to get the specific >>> information) using python. I already tried pyPdf with no success. >>> Anyone has suggestions? >>> Thanks in advance. >>> >>> Aonlazio >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexnbryan at gmail.com Sun Aug 17 14:22:37 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sun, 17 Aug 2008 11:22:37 -0700 (PDT) Subject: like a "for loop" for a string Message-ID: <19022098.post@talk.nabble.com> Okay, so lets say you have a list: funList = [1,2,3,4,5] and you do: for x in funList: print x this will print 1-5 But I am wondering is there a way to something like this: funString = "string string string non-string non-string string" and for "string" in funString: print something I know you can't do that; but, is there a way do do something similar that gets the same result? -- View this message in context: http://www.nabble.com/like-a-%22for-loop%22-for-a-string-tp19022098p19022098.html Sent from the Python - python-list mailing list archive at Nabble.com. From soid.exe at gmail.com Sat Aug 23 18:20:39 2008 From: soid.exe at gmail.com (Grigory Temchenko) Date: Sat, 23 Aug 2008 15:20:39 -0700 (PDT) Subject: How to know a top directory? References: <2.2.32.20080823112859.0112cedc@pop.xs4all.nl> Message-ID: <6c830468-f9e8-4b65-a138-f994f521986b@n38g2000prl.googlegroups.com> On Aug 23, 5:24?am, Fredrik Lundh wrote: > Michiel Overtoom wrote: > >> I have path "/this/is/path" and I wanna get "/this/is". > >> Also I want to use it as platform independent. If I want to pass "c: > >> \that\path" then I need to get "c:\that". > > > import os > > print os.path.split("/home/user/motoom")[0] > > print os.path.split("c:\\prj\\techniques\\python")[0] > > in this case, os.path.dirname() is more convenient. > > Thanks a lot! From enleverlesX.XmcX at XmclaveauX.com Sun Aug 24 00:51:47 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sun, 24 Aug 2008 06:51:47 +0200 Subject: Launch an application and continue the script's execution In-Reply-To: References: <898271.89410.qm@web37504.mail.mud.yahoo.com> Message-ID: <48b0eb42$0$854$ba4acef3@news.orange.fr> Hi ! Replace: os.startfile("launch_trace.bat") by os.startfile('start "" cmd /c launch_trace.bat') and "le tour est jou?". @-salutations -- Michel Claveau From thudfoo at opensuse.us Sun Aug 3 17:48:47 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Sun, 3 Aug 2008 14:48:47 -0700 Subject: very large dictionary In-Reply-To: References: <5c5e6d6e-04ef-4340-963f-d3825875b32c@e39g2000hsf.googlegroups.com> <6fftjvFb7ktoU2@mid.uni-berlin.de> Message-ID: <3d881a310808031448j5ade69f3k188cd7c92c8172ce@mail.gmail.com> On 3 Aug 2008 20:40:02 GMT, Jorgen Grahn wrote: > On 3 Aug 2008 20:36:33 GMT, Jorgen Grahn wrote: > > On Fri, 1 Aug 2008 01:05:07 -0700 (PDT), Simon Strobl wrote: > > ... > > >> If there is no other way to do it, I will have to learn how to use > >> databases in Python. > > > > If you use Berkeley DB ("import bsddb"), you don't have to learn much. > > These databases look very much like dictionaries string:string, only > > they are disk-backed. > > > ... all of which Sean pointed out elsewhere in the thread. > > Oh well. I guess pointing it out twice doesn't hurt. bsddb has been > very pleasant to work with for me. I normally avoid database > programming like the plague. > > 13.4 shelve -- Python object persistence A ``shelf'' is a persistent, dictionary-like object. The difference with ``dbm'' databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects -- anything that the pickle module can handle. This includes most class instances, recursive data types, and objects containing lots of shared sub-objects. The keys are ordinary strings.... [...] From timothy.grant at gmail.com Thu Aug 28 02:18:07 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Wed, 27 Aug 2008 23:18:07 -0700 Subject: Wild Card String Comparison In-Reply-To: <9kqtk.19193$cW3.1799@nlpi064.nbdc.sbc.com> References: <9kqtk.19193$cW3.1799@nlpi064.nbdc.sbc.com> Message-ID: On Wed, Aug 27, 2008 at 10:00 PM, W. eWatson wrote: > Timothy Grant wrote: >> >> On Wed, Aug 27, 2008 at 8:49 PM, W. eWatson >> wrote: >>> >>> Is it possible to do a search for a wild card string in another string. >>> For >>> example, I'd like to find "v*.dat" in a string called bingo. v must be >>> matched against only the first character in bingo, and not simply found >>> somewhere in bingo, as might be the case for "*v*.dat". >>> -- >>> Wayne Watson (Watson Adventures, Prop., Nevada City, CA) >>> >>> (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) >>> Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet >>> >>> Web Page: >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> Is this what you're looking for? >> > What's this? > ----------------- >> >> Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16) >> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin >> Type "help", "copyright", "credits" or "license" for more information. >>>>> >>>>> x = 'the quick brown fox' > > ------------------ >>>>> >>>>> 'the' in x >> >> True >>>>> >>>>> 'qui' in x >> >> True >>>>> >>>>> 'jumped' in x >> >> False >> >> If that doesn't meet your needs you may want to look at the re >> module. But if you can avoid re's your likely better off. > > re module?? >> >> > There are no wild cards in your examples. * is one wild card symbol? > begin*end means find "begin" followed by any string of characters until it > find the three letters "end". > > "begin here now but end it" should find "begin here now but end" > "beginning of the end is the title of a book" should find "beginning of the > end" > "b egin but end this now" should find nothing. > > > -- > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > Web Page: > -- > http://mail.python.org/mailman/listinfo/python-list > you definitely need the re module then. -- Stand Fast, tjg. [Timothy Grant] From gmkasi at gmail.com Tue Aug 12 06:53:58 2008 From: gmkasi at gmail.com (black) Date: Tue, 12 Aug 2008 03:53:58 -0700 (PDT) Subject: you having special Message-ID: <5d8f0d35-24f7-4416-bc6b-240500452e07@r15g2000prh.googlegroups.com> you having special open it ******************************************************************************************* http://www.AWSurveys.com/HomeMain.cfm?RefID=Maruthakasi G ************ From deets at nospam.web.de Thu Aug 14 07:11:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 14 Aug 2008 13:11:26 +0200 Subject: Fixed-length text file to database script References: Message-ID: <6gii8rFfm052U1@mid.uni-berlin.de> Stacey wrote: > Hi Guys, > > I'm new to Python (mostly) and I'm wanting to use it for a new project > I'm faced with. > > I have a machine (PLC) that is dumping its test results into a > fixed-length text file. I need to pull this data into a database > (MySQL most likely) so that I can access it with Crystal Reports to > create daily reports for my engineers. > > I've been reading the Python manual for about a week now and I'm > learning a lot. Unfortunately, I was given a deadline today that I > cannot meet without a little help. > > I need to know how to write a script that will DAILY pull this text > file into a MySQL database. > > Can anyone show me how to do this? Show us code & data, and we show you how to improve the code. Or would you be able to write the script with the above information? Diez From grahn+nntp at snipabacken.se Sun Aug 3 15:46:37 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 3 Aug 2008 19:46:37 GMT Subject: Using two pythons in an application References: Message-ID: On Sun, 03 Aug 2008 14:01:49 -0400, Allen wrote: > I'm in the process of developing an application that will use Python for > a scripting support. In light of the upcoming changes to Python, I was > wondering if it is possible to link to and use two different versions of > Python so that in the future, scripts could be migrated to the new > version, and older scripts would still work as well. If so are there > any code examples of this. I cannot answer that, sorry. But if I were you, I'd pick a current, stable Python version for my application, and stop worrying for now. If there is a new, incompatible Python version (I assume you're talking about Py3k?) these things will happen: - people around the world will decide to migrate - people will gain experience with migrating Python code - Python 2.x will start to look obsolete - things like Linux distributions and web hosting companies will stop offering Python 2.x - you will be forced (for practical reasons, or to avoid looking silly) to migrate your application (and break old scripts) All this will happen *slowly* -- I believe so slowly that you will have plenty of time to act later. And your users (or whoever has to deal with the scripts) will not be alone; lots of people will sit around migrating old Python code. (Caveat: I don't know much about the Py3k transition, just about other cases like that. Killing off an old language dialect takes time!) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From bearophileHUGS at lycos.com Sat Aug 30 13:01:25 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 30 Aug 2008 10:01:25 -0700 (PDT) Subject: Most pythonic way of weighted random selection References: Message-ID: Manuel Ebert, this may be related/useful: http://code.activestate.com/recipes/498229/ Note that numpy has a bisection method/function that are probably quite faster. Bye, bearophile From gagsl-py2 at yahoo.com.ar Tue Aug 19 23:26:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 20 Aug 2008 00:26:28 -0300 Subject: Python Query: Related to locking a resource in a multithreaded environment References: <48AB17C3.80408@gmx.de> Message-ID: En Tue, 19 Aug 2008 15:58:11 -0300, Nils Oliver Kr?ger escribi?: > My approach what be to write one class for reading and writing to the > configuration and make that class thread-safe using the RLock. > > Then you create one and only one instance of this class and let all your > threads use (not import) that one instance. > > You could achieve that "one and only one" either by having a main > program which creates the instance and pass the reference to each thread > via its __init__ or you implement the Configuration class as a singleton > like this: > > class Singleton(object): [...] >Add your methods for accessing as instance methods to this class and get > the same instance of this class in each thread by calling > Singleton.getInstance(). Singleton.getInstance() is so "javaistic"... :) Actually there is no need for all of that; just define the RLock at the global scope in a module. Don't feel bad by using a "global" name - remember that a Python module acts as a named singleton. Defining an object at module scope is equivalent to defining an instance attribute in your Singleton class. -- Gabriel Genellina From fredrik at pythonware.com Thu Aug 14 04:37:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 10:37:11 +0200 Subject: How do I organize my Python application code? In-Reply-To: References: Message-ID: Dudeja, Rajat wrote: > And my problem is that I don't have an understanding of how the code in > Python is generally organized, in case my code spans multiple files, > modules, etc. I've been using C/C++ althrough my life on Linux and > Visaul Studio, so the way their code is organized in a group of header > files, source files, etc, I'm looking for a similar way in Python way or > an approach to organize my python GUI application code? A Python program consists of a script file (the py file you run to start the program), and usually one or more additional module files (py files that you import). The latter can be organized in packages, where appropriate. There's also a search path (sys.path) that you can modify in various ways (including from within the program) if you want to fetch modules from different locations. That's all there is; there's no header files or declaration files or explicitly maintained object files etc; the program itself is just a bunch of Python files. To learn more about this, the "modules" section in the tutorial is a good start: http://docs.python.org/tut/node8.html Looking at the structure of a few existing projects might also be helpful. From benjamin.kaplan at case.edu Fri Aug 22 18:41:51 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 22 Aug 2008 18:41:51 -0400 Subject: >> and << operators? In-Reply-To: References: Message-ID: On Fri, Aug 22, 2008 at 6:30 PM, defn noob wrote: > What does >> and << do? > > Googling on them and they are just ignored... > > -- > http://docs.python.org/lib/bitstring-ops.html > > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From coolman.guron at gmail.com Sun Aug 3 02:12:27 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Sat, 2 Aug 2008 23:12:27 -0700 (PDT) Subject: why goes the time change after import statement ? References: <011a92b4-b911-4f63-9339-be46b48d5f76@v1g2000pra.googlegroups.com> <6ae5acd5-3d5d-4e81-af2f-a32a9c833122@y38g2000hsy.googlegroups.com> Message-ID: <4bcdd104-21d2-46a6-8ffa-1d3eaa46c617@a8g2000prf.googlegroups.com> On Aug 3, 1:46 am, Paul Hankin wrote: > On Aug 2, 10:35 pm, binaryjesus wrote: > > > > > hi i am working on a S3 project and facing a really weird problem! > > take a look at the following import statements and the time output > > > >>> import time > > >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) > > > 'Sat, 02 Aug 2008 20:21:56 GMT' > > > # OK > > > >>> import pygtk > > >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) > > > 'Sat, 02 Aug 2008 20:22:04 GMT' > > > # OK > > > >>> import gtk > > >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) > > > 'Sat, 02 Aug 2008 08:22:11 PM GMT' > > > # HOW THE HELL THIS HAPPEN ??? not DATE_RFC2822 format gmt time ! > > Reading the manual page for strftime --http://docs.python.org/lib/module-time.html > -- says that '%X' is the locale's appropriate time representation, so > obviously gtk is adjusting your locale. Perhaps use a formatting > string that doesn't depend on the locale: '%H:%M:%S' instead of '%X' > seems to give your preferred format. > > -- > Paul Hankin ok that explain it. but what command does gtk runs that it sets the default behaviour of strfime() to that ? From kyosohma at gmail.com Thu Aug 7 16:14:18 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 7 Aug 2008 13:14:18 -0700 (PDT) Subject: wxPython pop--up ("could not retrieve information...") References: Message-ID: On Aug 7, 1:36?pm, mistersulu wrote: > Hi all: > > I'm using a wx.ListView object with a multi-threaded wxPython app. > The list is dynamically generated and accessed across two or more > threads. ?In spite of the fact that I have checks to see if an item at > a given index is in the list and the entire set of logic is contained > within a try: except: block I periodically get pop-up windows stating > "Could not retrieve information for list control item X" when I try to > change or access the list items. > > I searched the web and groups for similar posts but can't find any > solutions. > > My question is: > > Is there a setting somewhere in wxPython to either disable these pop- > up messages or a semaphore or event locking method to enable cross- > thread access to a listview object? > > Thanks in advance, > sulu Accessing the GUI's main thread in wxPython (and most other GUI toolkits) is a no-no. wxPython does provide a few thread-safe methods, such as wx.CallAfter and wx.PostEvent. Otherwise you'll end up blocking the GUI's main thread and the GUI will become unresponsive. Check out Frank's link for one way to deal with this issue or download the wxPython demo and check the threaded demo out. http://wxpython.org/download.php Also, I recommend joining the wxPython user's mailing list. They're are a lot of nice people there and you'll learn a lot. http://wxpython.org/maillist.php Mike From gminick at nie.ma.takiego.adresu.w.sieci.pl Tue Aug 12 09:03:28 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Tue, 12 Aug 2008 13:03:28 +0000 (UTC) Subject: trying to use SOCK_RAW yields error " References: <3b701b38-9dd3-48f6-bdb0-c04fc9085008@x41g2000hsb.googlegroups.com> Message-ID: Dnia Tue, 12 Aug 2008 05:40:36 -0700 (PDT), Tzury Bar Yochay napisa?(a): Hi, > server = socket.socket(socket.AF_INET, socket.SOCK_RAW, > socket.getprotobyname('ip')) ... > Does anybody have used socket.SOCK_RAW in the past? When using SOCK_RAW, the family should be AF_PACKET, not AF_INET. Note that you need root privileges to do so. -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From wuwei23 at gmail.com Tue Aug 26 22:55:45 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 26 Aug 2008 19:55:45 -0700 (PDT) Subject: Python and database unittests References: Message-ID: <485093c5-a0f5-482e-b8fd-3cdd119020d1@r15g2000prd.googlegroups.com> Daniel wrote: > Does anyone know about a module that acts as a database stub for > python unittests? It's not database-specific, but the Mock module should help you here: http://python-mock.sourceforge.net/ There's even an example on that page for mocking a database. From mathieu.prevot at ens.fr Fri Aug 8 04:03:31 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Fri, 8 Aug 2008 10:03:31 +0200 Subject: kill thread In-Reply-To: <704879e6-1b21-4c91-99ce-f10e3866c8da@a8g2000prf.googlegroups.com> References: <704879e6-1b21-4c91-99ce-f10e3866c8da@a8g2000prf.googlegroups.com> Message-ID: <3e473cc60808080103y43a0593ev80fb7db198d55608@mail.gmail.com> 2008/8/8 Miki : > Hello, > >> I have a threading.Thread class with a "for i in range(1,50)" loop >> within. When it runs and I do ^C, I have the error [1] as many as >> loops. I would like to catch this exception (and if possible do some >> cleanup like in C pthreads) so the program finishes cleanly. Where and >> how can I do this ? in __run__ ? __init__ ? a try/except stuff ? > You can have a try/except KeyboardException around the thread code. > > HTH, > -- > Miki Of course, but I don't know where. I placed this inside loop, within called functions from the loop, I still have the problem. Mathieu From egbert.bouwman at hccnet.nl Sun Aug 3 05:26:19 2008 From: egbert.bouwman at hccnet.nl (egbert) Date: Sun, 3 Aug 2008 11:26:19 +0200 Subject: current week / weeks in year - best practice In-Reply-To: References: <6fdur9Fb0nvuU1@mid.uni-berlin.de> <2ac30ca6-554a-4b40-bdb8-a61f2311ab24@l42g2000hsc.googlegroups.com> Message-ID: <20080803092619.GA4148@hccnet.nl> On Sat, Aug 02, 2008 at 07:46:49PM -0700, Dennis Lee Bieber wrote: > > What is the meaning of ? e. -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From wuwei23 at gmail.com Fri Aug 8 03:08:03 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 8 Aug 2008 00:08:03 -0700 (PDT) Subject: benchmark References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> <4b4e4efb-4bb7-485d-a124-2e253356fca5@v1g2000pra.googlegroups.com> Message-ID: On Aug 8, 2:49?pm, Dhananjay wrote: > Is it that a question of time and effort, > or is there something that doesn't make it appropriate to python ? I don't think I've ever seen anyone who has raised concerns about the speed of python actually offer to contribute to resolving it, so I'm guessing it's the former. From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 20 05:11:29 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 20 Aug 2008 11:11:29 +0200 Subject: adding properties dynamically (how to?) In-Reply-To: <4cc8605c-9bc5-4cae-a995-7df85e683241@r15g2000prh.googlegroups.com> References: <4d8a0f68-f388-4127-b2ae-fc879690faf4@a70g2000hsh.googlegroups.com> <4cc8605c-9bc5-4cae-a995-7df85e683241@r15g2000prh.googlegroups.com> Message-ID: <48abdfb5$0$15608$426a34cc@news.free.fr> Rafe a ?crit : (snip) > > You can dynamically add properties to a class The OP was asking for *per instance* properties... > just before returning > the > instance using __new__(): > > class AClass(object): > def __new__(cls): > > setattr(cls,"propName", property(fget = ..., > fset = ..., > fdel = ..., > doc = ...) ) > > obj = super(AClass, cls).__new__(cls) > return obj Very bad idea IMHO. __new__ is called on each instanciation, which means the above code will uselessly modify the class each time you create an instance of it, overwriting the same properties again and again and again. If what you want is to automagically add properties (or whatever type of attributes) to a class and/or it's subclass, you'd be better using a custom metaclass. From bryanandedna at gmail.com Sun Aug 3 07:56:07 2008 From: bryanandedna at gmail.com (Huuuze) Date: Sun, 3 Aug 2008 04:56:07 -0700 (PDT) Subject: HELP with PIL and grainy text Message-ID: <73b859cc-50a0-4c2f-b067-bf757e7d48f8@f63g2000hsf.googlegroups.com> I could really use some help. Please take a look at the following image: http://img227.imageshack.us/img227/1346/grainynn3.png As you can see, the text in the image is fairly grainy. To get to that point, I converted an ArialBold TTF to a BDF using otf2bdf (http://crl.nmsu.edu/~mleisher/ttf2bdf.html) and then I used pilfont utility (http://www.pythonware.com/library/pil/handbook/pilfont.htm) to convert the file into a .PIL and .PBM file. I'd expect the font to be smooth, but no such luck. Any idea what could be happening here? For what it's worth, I'm using a Mac (OSX 10.5.4). Here is the PIL code as well: >> import Image, ImageDraw, ImageFont >> font = ImageFont.load("Arial.pil") >> im = Image.open("../images/image.png") >> dr = ImageDraw.Draw(im) >> dr.text((79,34), "Successfully used the Python Image Library", font=font) >> im.save("../images/grainy.png", "PNG") From pavlovevidence at gmail.com Fri Aug 15 11:03:23 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 15 Aug 2008 08:03:23 -0700 (PDT) Subject: negative numbers are not equal... References: <48A4932F.4010302@gmail.com> Message-ID: On Aug 14, 4:42?pm, Christian Heimes wrote: > Integers > between -5 and +256 are singletons as are some other objects like > strings with one element or empty tuples. Not quite. Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 'A' >>> b = "%c" % a >>> a 'A' >>> b 'A' >>> a is b False > You must not rely on the > optimization. Good advice. Carl Banks From fredrik at pythonware.com Wed Aug 13 04:27:07 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Aug 2008 10:27:07 +0200 Subject: PIL (etc etc etc) on OS X In-Reply-To: References: <489379A7.5060009@codebykevin.com> Message-ID: David C. Ullrich wrote: > Thanks. Sorry to be so dumb - yes, it's perfectly reasonable > for eff to assume that people using PIL are programmers. well, my only assumption is that people building PIL from basic building blocks must have some understanding of how that's done on their specific platform (and I don't have that knowledge myself for all platforms). And OS X can be something of a mess; search for "OS X" in the image-sig archives for a lot more on this. From steve at REMOVE-THIS-cybersource.com.au Thu Aug 14 00:34:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2008 04:34:55 GMT Subject: Using Timer or Scheduler in a Class References: Message-ID: <00b3b0f8$0$14351$c3e8da3@news.astraweb.com> Hi Justin, Does Professor Battersea know you're using his gmail account? *wink* On Wed, 13 Aug 2008 23:16:12 -0400, Prof. William Battersea wrote: > I'd like a class method to fire every n seconds. > > I tried this: > > class Timed: > def.__init__(self): > self.t = Timer(3, self.dothing) > def.start(self): > self.t.start() > > def.dothing(self): > print "Doing Thing" > > s = new Timed() > s.start() This can't be your actual code, because "s = new Timed()" gives a SyntaxError. So does "def.start(self)" etc. Also, what's Timer? > And: > > class Scheduled: > def.__init__(self): > self.s = sched.scheduler(time.time, time.sleep) > self.s.enter(3, 1, self.sync, ()) > > def.start(self): > self.t.start() > > def.dothing(self): > print "Syncing" > > s = new Scheduled() > s.start() When I fix the syntax errors and try to run the above code, I get this: AttributeError: Scheduled instance has no attribute 'sync' That's only the first of a number of errors. You waste our time when you post code that doesn't run. Very few people will bother spending the time and effort to fix your code if you don't respect their time, and those that do will rub your nose in the fact that you're wasting their time. > Both run once and end. I'm obviously missing something here. Let's start with some code that actually does run: >>> class Scheduled: ... def __init__(self): ... self.s = sched.scheduler(time.time, time.sleep) ... self.s.enter(3, 1, self.dothing, ()) ... def start(self): ... self.s.run() ... self.s.enter(3, 1, self.dothing, ()) ... self.start() ... def dothing(self): ... print "Syncing" ... >>> s = Scheduled() >>> s.start() Syncing Syncing Syncing Traceback (most recent call last): File "", line 1, in File "", line 8, in start File "", line 8, in start File "", line 8, in start File "", line 6, in start File "/usr/lib/python2.5/sched.py", line 108, in run delayfunc(time - now) KeyboardInterrupt This will run until you interrupt it (as I did) or you run out of space on the stack due to recursion. I imagine this is probably not the best way to do what you want. Hint for further explorations: the scheduler keeps a queue of events. If the queue becomes empty, it stops. You only need to restart the scheduler with run() if it stopped, otherwise it keeps going. -- Steven From thomasmallen at gmail.com Wed Aug 13 15:46:33 2008 From: thomasmallen at gmail.com (tmallen) Date: Wed, 13 Aug 2008 12:46:33 -0700 (PDT) Subject: An FTP Client...My first real program! References: <228e4214-01cf-4152-acdb-3743594f0581@e53g2000hsa.googlegroups.com> Message-ID: <89beabc9-52e2-46ea-9e6d-da5ca77bfafe@x35g2000hsb.googlegroups.com> On Aug 13, 3:27?pm, tmallen wrote: > Here's the code:http://pastebin.com/m21dfcc19 > > What could be improved? The script feels clumsy, and I have no > experience refactoring Python code. This will eventually be a GUI FTP > client. I'm mainly looking for design advice... Note that all it does right now is store account info and connect to the host, listing the contents of the pwd. Anonymous connections work, and the script is functionally sound. From tjreedy at udel.edu Mon Aug 25 12:36:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 25 Aug 2008 12:36:09 -0400 Subject: Python String Immutability Broken! In-Reply-To: <48B28F7A.9030006@seehart.com> References: <000b01c906f1$a493bb80$0d00a8c0@hendrik> <48B28F7A.9030006@seehart.com> Message-ID: Ken Seehart wrote: > Hendrik van Rooyen wrote: >> >> ... >> >> Actually, I am not complaining - I am asking for advice on the side >> effects of what I am doing, which is replacing a bunch of bits >> in what is essentially an output bit field with the corresponding >> input bits at the same addresses read back from a simulated i/o >> bus structure. And I would also like to know if there is a better >> way of doing this. >> > Yes, there is a better way. Use a character array instead of a string. > > http://python.net/crew/theller/ctypes/tutorial.html#arrays Which essentially is the bytearray type of 3.0. From luismi2050 at yahoo.es Tue Aug 26 11:25:53 2008 From: luismi2050 at yahoo.es (luismi) Date: Tue, 26 Aug 2008 08:25:53 -0700 (PDT) Subject: python portable installation? Message-ID: <00a851cf-4ca7-4d7e-b116-b3eda7b6a092@k36g2000pri.googlegroups.com> Hi, I have searched the online manuals, faqs and forums, but i haven't found a satisfactory explanation ... most probably my fault ;) I have found 2 projects, one commercial and another free, that deal with the installation and running of python code on portable/removable devices, my questions are: (1) Is this scenario not yet contemplated in the official releases, and (2) Why is such a big issue? Will appreciate your comments, Thanks in advance Luismi From riccardo at infis.univ.trieste.it Sat Aug 2 11:25:28 2008 From: riccardo at infis.univ.trieste.it (Riccardo Di Meo) Date: Sat, 02 Aug 2008 17:25:28 +0200 Subject: embedded python doesn't like socket.accept() and SegFaults Message-ID: <48947C68.7030604@infis.univ.trieste.it> Hi everyone, I'm practicing with embedding python into C code and i have encountered a very strange problem: I'm unable to call the "accept" method of a (correctly created) server socket without receiving a "Segmentation fault" (inside the PyObject_CallMethod). My code to be correct (at least it's correct enough for me to call .getsockname(), .fileno() and other methods without problems), I'm pretty new to this thing though, therefore I'm confident I'm doing something very dumb. Here is the C code: ------ extending.c #include PyObject *new_server(long port) { PyObject *pName,*pModule; PyObject *pFunction,*pArg; PyObject *pTuple,*pValue; // Import the module pName = PyString_FromString("extending"); pModule = PyImport_Import(pName); Py_DECREF(pName); // Get the function pFunction = PyObject_GetAttrString(pModule, "server_socket"); // Module not needed anymore Py_DECREF(pModule); // Build the arguments pArg=PyInt_FromLong(port); pTuple=PyTuple_New(1); PyTuple_SET_ITEM(pTuple,0,pArg); // Call the function pValue = PyObject_CallObject(pFunction, pTuple); // Release the references Py_DECREF(pFunction); Py_DECREF(pTuple); if(pValue==NULL) printf("Error: server socket not created!\n"); return pValue; } PyObject *accept(PyObject *server) { PyObject *pValue; // Code fails here (it does NOT return NULL: just crashes!) // Note that other calls work fine (e.g. fileno, getsockname ecc) pValue = PyObject_CallMethod(server, "accept", NULL); return pValue; } int main(int argc,char *argv[]) { PyObject *server,*connection; // Boot python Py_Initialize(); PySys_SetArgv(argc, argv); // Create the server server=new_server(23000); // Print it PyObject_Print(server,stderr,0); fprintf(stderr,"\n"); // Wait for a connection connection=accept(server); // See what we got PyObject_Print(connection,stderr,0); fprintf(stderr,"\n"); // We are done, hint the gc. Py_DECREF(connection); Py_DECREF(server); Py_Finalize(); return 0; } ---------- and this is the python script: ---------- extending.py import socket def server_socket(port): s=socket.socket() s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True) s.bind(("0.0.0.0",port)) s.listen(10) return s ------------ as already mentioned, replacing the "accept" string with "fileno" or something else doesn't crash the interpreter. Another thing worth mentioning, is that even inserting a s.accept() call in the python script (before the return) makes the bug appear (it doesn't seems related to my use of the PyObject_CallMethod function, then). I have tried posting the problem in IRC, searching google (no good matches) and debugging the code (however I'm afraid i don't have the python-lib with debugging syms. compiled in, therefore it was quite a useless attempt...). Any help about the code would be appreciated (even unrelated to the issue at hand: im quite new to this "embedding thing" and therefore i gladly accept hints). Thank you for your attention, Riccardo Di Meo PS: I'm also new to Usenet: is it fine to post the code in the body of the mail as i did (since it was small, i dared: however I'd like to know the correct etiquette)? From straton at lampsacos.demon.co.uk Fri Aug 29 05:09:20 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 29 Aug 2008 10:09:20 +0100 Subject: [1,2,3] exactly same as [1,2,3,] ? In-Reply-To: References: Message-ID: mh at pixar.com wrote: > x=[1,2,3] > and > x=[1,2,3,] > > are exactly the same, right? > > I'm generating some python data, and it's less error prone > to not treat the last element specially, but I want to be > sure I'm generating an equivalent data structure. > > Many TIA! > Mark > >>> x=[1,2,3,] >>> repr(x) [1,2,3] From paulo.jpinto at gmail.com Tue Aug 5 10:21:00 2008 From: paulo.jpinto at gmail.com (paulo.jpinto at gmail.com) Date: Tue, 5 Aug 2008 07:21:00 -0700 (PDT) Subject: interpreter vs. compiled References: <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <4rl294duo83eujnq6tjbk215mavpl87o9r@4ax.com> <43f519dd-6763-4cc0-a6d2-1e671da54c2c@d45g2000hsc.googlegroups.com> <1fdd10ae-581c-428d-9268-8fca8b99aff4@2g2000hsn.googlegroups.com> Message-ID: <5f742714-1d29-467e-82fe-d88253542657@79g2000hsk.googlegroups.com> On Aug 3, 1:26?am, castironpi wrote: > On Aug 2, 2:02 pm, Tim Roberts wrote: > > > castironpi wrote: > > > >And furthermore, I think I'm getting > > >confused about what exactly constitutes an interpreter: it is whether > > >there is a process that runs product instructions, or the product > > >instructions can run standalone. ?I would take 'compiler' to mean, > > >something that outputs an .EXE executable binary file, and I don't > > >just mean bundling up the python.exe executable with a file. > > > OK, let me give MY definition. ?I freely grant that my definition might be > > different from anyone elses, but perhaps this will help you understand the > > basis for my arguments. > > I understand that we're having a disagreement about terminology. ?I > further don't understand exactly what JIT languages are, so I can't > agree on that either. > > I will observe the certain amount of corporate hype behind, and worker > base morale riding on, the notion that JIT technology compiles code. > I suspect it's an exaggeration, not outright false, but I can't prove > it until I tell you what instructions run, one right after another, on > a concrete architecture I've held in my hand, like the x86 die. ?Nor > can I thoroughly believe that it's true either, though, until its > creators have told me what instructions they are. ?So I'll proclaim > ignorance and await facts... or consistent stories about them. > > > If I run three different CPython programs, the bytes of machine language > > that get executed are come from the same place: python24.dll. ?My user > > programs are just data. ?That, in my mind, makes the CPython implementation > > an interpreter. > > > If I compile and run three different C programs, the bytes of machine > > language will be come from three different places. ?That, in my mind, makes > > my C implementation a compiler. > > True. ?I agree on the facts and the terms. > > > If I compile and run three different C# programs, the JIT compiler makes > > new machine language for each one. ?The bytes of machine language will come > > from three different places. ?That, in my mind, makes the C# implementation > > a compiler. > > > If I compile and run three different IronPython programs, the JIT compiler > > makes new machine language for each one. ?The bytes of machine language > > will come from three different places. ?That, in my mind, makes the > > IronPython implementation a compiler. > > I don't know enough to attest to these for a fact, and you haven't > given enough details to corroborate them as facts. ?But when you do, > I'll be able to take and learn your terms for them (not that I will, > of course, but I can). > > > All four of those scenarios require run-time library support. ?Even the C > > progam does not run on its own. > > I disagree with this, if the C program is statically linked -- the OS > copies the binary (.EXE) from disk into memory, then jumps to a > specific offset in that block / address space. ?It runs all its own > bytes, then jumps back to an OS-specified point of return of control. > For the other three, though, this is true. > > > Execution starts in the run-time library, > > which sets up an environment before jumping to "main". ?The C# and > > IronPython situations are the same; it's just that there's more processing > > going on before jumping to "main". > > I want to give a concrete example of 'generating machine code' per se > (as such). > > I run this program: > > bin= open( 'abinary.exe', 'w' ) > bin.write( '\x09\x0f\x00\x00' ) > for x in range( 10 ): > ? ?bin.write( '\x04\xA0' + chr( x ) + '\x00' ) > bin.write( '\x01\x20\x00\x00' ) > > It outputs to 'abinary.exe': > > \x09\x0f\x00\x00 > \x04\xa0\x00\x00 > \x04\xa0\x01\x00 > \x04\xa0\x02\x00 > \x04\xa0\x03\x00 > \x04\xa0\x04\x00 > \x04\xa0\x05\x00 > \x04\xa0\x06\x00 > \x04\xa0\x07\x00 > \x04\xa0\x08\x00 > \x04\xa0\x09\x00 > \x01\x20\x00\x00 > > Which is 12 bytes long and runs in a millisecond. ?What it does is set > a memory address to successive integers 0..9, then yields. ?Due to the > nature of program flow control, while it runs its first steps on any > x86 machine, the yield only succeeds if on Windows 98+, and crashes > the machine, or otherwise loses control if not. ?(That part depends on > those OSses.) > > I can try something similar dynamically. > > char* mem= alloc( 48 ) > setpermission( mem, EXECUTE ) > memcpy( mem+ 0, "\x09\x0f\x00\x00", 4 ) > for( int x= 0; x< 10; ++x ) { > ? ?memcpy( mem+ 4* (x+ 1 ), '\x04\xA0\x00\x00', 4 ) > ? ?mem[ 4* (x+ 1 )+ 3 ]= (char) x > memcpy( mem+ 44, '\x01\x20\x00\x01', 4 ) > setjump > goto mem > > Which with some imagination produces the contents of 'abinary.exe' > above (one difference, last word) in a memory block, at address 'mem', > then jumps to it, which then jumps back, and then exits. > > I'll compare a C complation to the first example, 'abinary.exe', and a > JIT compilation to the second example, 'char* mem'. ?If the comparison > isn't accurate, say how, because these are places I can start from... > (yes, that is, instead of just repeating the claims). > > When does a JIT do this, and what does it do in the meantime? The JIT works like an assembler/linker that writes to memory. It will load the file(s) containing the bytecode and generate the required assembly instructions into memory. In the case there are dependencies to other modules, they will be loaded as well, and compiled. Then the linker will take care that cross references between modules are correct, like memory addresses and branch targets. A clever JIT might add instrumentation points, so that it can rewrite the code using profile guided optimizations, this means generating optimized code using as input the program behaviour. This makes JIT code usually faster than normal compiled code. Although normal native code is able to start executing faster, it only targets a specific set of processors. JIT code is independent of the processor, and a good JIT implementation is able to explore the processor better than a direct native compiler. There is however the time penalty on program startup. -- Paulo From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 13 08:40:24 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 13 Aug 2008 14:40:24 +0200 Subject: You advice please In-Reply-To: References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> Message-ID: <48a2d62b$0$3732$426a74cc@news.free.fr> ?lvaro G. Vicario a ?crit : > Hussein B escribi?: >> The sad fact (at least to me), Ruby is getting a lot of attention >> these days. >> Why Python isn't getting this attention although is a much more mature >> language and it is used by many big, big names? >> And do I dare to say it is much more charming? > > The opinion of a PHP developer who's playing with Python as well: > > I've come across Python almost everywhere. Many programs I use (or I've > evaluated) are written in Python or use it for scripting: source control > software (Subversion, Bazaar, Mercurial), IDEs (Komodo Edit), popular > web applications (Zope, Trac)... If you're looking for a script for > admin tasks your search results will probably contain something in > Python. If you want to build a Firefox extension you'll find a *.py file > sitting around. > > But I've never came across a Ruby app. Sure, I know Ruby exists and > people are very enthusiastic about it (though they often mistake it with > Ruby on Rails), but that's all. Redmine is a nice alternative to Trac. And Twitter is certainly a well-known app too. (Yes, RoR apps in both cases...). > Ruby is popular among bloggers but I'm not sure whether it's popular > among developers. Almost as much as Python, I'd say. But both languages fight for the same niches in languages/techno ecosystem, and Python, being older, tend to get more visibility. From vedrandekovic at yahoo.com Thu Aug 7 03:25:10 2008 From: vedrandekovic at yahoo.com (vedrandekovic at yahoo.com) Date: Thu, 7 Aug 2008 00:25:10 -0700 (PDT) Subject: .cpp to .pyd Message-ID: Hello, I want to build my C++ (.cpp) script to (.pyd) like this: http://en.wikibooks.org/wiki/Python_Programming/Extending_with_C%2B%2B I have installed "Microsoft Visual studio .NET 2003" and "Boost Python" and then after I run my setup script: python setup.py build I get this error: running build running build_ext building 'hello' extension D:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\cl.exe /c / nologo /Ox /MD /W3 /GX /DNDEBUG -IC:\Panda3D-1.5.2\python\include -IC: \Panda3D-1.5.2\pytho n\PC /Tphellomodule.cpp /Fobuild\temp.win32-2.5\Release \hellomodule.obj hellomodule.cpp hellomodule.cpp(9) : fatal error C1083: Cannot open include file: 'boost/python/ module.hpp': No such file or directory error: command '"D:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\cl.e xe"' failed with exit status 2 I think that my MS visual studio cannot find "boost python", if that's the problem then can you tell me how can I solve it. This is very begginer question,but I can't find answer nowhere, and I don't have any expirience with Microsoft products. Sorry for my bad english! Regards, Veki From __peter__ at web.de Wed Aug 27 13:35:51 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 27 Aug 2008 19:35:51 +0200 Subject: finding out the number of rows in a CSV file [Resolved] References: <3aaa109e-9a7e-4d02-8af5-0161251d7678@t54g2000hsg.googlegroups.com> <0bc6097f-af52-4951-a413-e9a983df93c7@79g2000hsk.googlegroups.com> Message-ID: John S wrote: > [OP] Jon Clements wrote: >> On Aug 27, 12:54 pm, SimonPalmer wrote: >>> after reading the file throughthe csv.reader for the length I cannot >>> iterate over the rows. How do I reset the row iterator? > > A CSV file is just a text file. Don't use csv.reader for counting rows > -- it's overkill. You can just read the file normally, counting lines > (lines == rows). Wrong. A field may have embedded newlines: >>> import csv >>> csv.writer(open("tmp.csv", "w")).writerow(["a" + "\n"*10 + "b"]) >>> sum(1 for row in csv.reader(open("tmp.csv"))) 1 >>> sum(1 for line in open("tmp.csv")) 11 Peter From sjmachin at lexicon.net Fri Aug 22 18:22:26 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 22 Aug 2008 15:22:26 -0700 (PDT) Subject: codecs, csv issues References: <8aafd67e-6633-4371-a880-805d07089400@k37g2000hsf.googlegroups.com> Message-ID: <12c6f5a0-544f-4121-a520-28de61b08a8a@v16g2000prc.googlegroups.com> On Aug 22, 11:52 pm, George Sakkis wrote: > I'm trying to use codecs.open() and I see two issues when I pass > encoding='utf8': > > 1) Newlines are hardcoded to LINEFEED (ascii 10) instead of the > platform-specific byte(s). > > import codecs > f = codecs.open('tmp.txt', 'w', encoding='utf8') > s = u'\u0391\u03b8\u03ae\u03bd\u03b1' > print >> f, s > print >> f, s > f.close() This is documented behaviour: """ Note Files are always opened in binary mode, even if no binary mode was specified. This is done to avoid data loss due to encodings using 8- bit values. This means that no automatic conversion of '\n' is done on reading and writing. """ From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 27 07:32:26 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 27 Aug 2008 13:32:26 +0200 Subject: Decorators using instance variables In-Reply-To: References: Message-ID: <48b53b13$0$1052$426a74cc@news.free.fr> Robert Kaplan a ?crit : > > > Bruno Desthuilliers a ?crit : > > <...> > >> 2/ don't bother reading anything from someone named 'castironpi', it's >> one of our currently active resident troll, and he is worse than >> clueless. >> > > Actually, I found his response to the point, his sample code helpful, > and his solution similar to yours. This _sometimes_ happens, yes, and that's why you just shouldn't trust him : unless you have a good knowledge of the topic, you just can't tell whether his answer is ok or total rubbish. From deets at nospam.web.de Fri Aug 29 12:59:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 29 Aug 2008 18:59:53 +0200 Subject: Python graphics question:pixel scrolling References: Message-ID: <6hqo8vFnnqcjU1@mid.uni-berlin.de> Raymond Luxury-Yacht wrote: > To learn python, I've been trying to write a simple graphics program > which displays a 1D cellular automaton's evolution. The last time I > wrote this program, it was in C for a CGA adaptor (!) in which the > display was mapped to two interlaced blocks of memory, and scrolling > up two lines of pixels was very simple and very smooth. The code > below works, and uses pygame for the graphics. But the scrolling is > quite flickery when using large windows. I'm sure that the code > contains various neophyte python errors, and I'd appreciate any > comments on that, but my main question is how I ought to have coded it > in order to have the scrolling be smooth. I did see a comment on a > pygame site saying that pygrame should not be used for side-scrollers, > to which this is similar. Is there a better way with python? You need to to double-buffering. Just as in the old days... http://www.pygame.org/docs/tut/intro/intro.html Look for pygame.display.flip() Diez From gminick at bzt.bzt Wed Aug 20 11:22:16 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 20 Aug 2008 15:22:16 +0000 (UTC) Subject: subprocess seems to "detach" / ignore wait() References: Message-ID: On Wed, 20 Aug 2008 15:09:11 +0200, Mathieu Prevot wrote: > flog = open(logfile, 'w') > fpid = open(pidfile, 'w') > try: > child = Popen(cmd.split(), stderr=flog) > print "Server running [PID %s]"%(child.pid) > fpid.write(child.pid) What happens if you change: fpid.write(child.pid) into: fpid.write('%d\n' % (child.pid)) I think that the problem here is that fpid.write() fails silently (probably TypeError), because it takes string as its first argument, not integer. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From mensanator at aol.com Sat Aug 9 11:19:07 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 9 Aug 2008 08:19:07 -0700 (PDT) Subject: How to round a floating point to nearest 10? References: Message-ID: On Aug 9, 6:31?am, Will Rocisky wrote: > I want my 76.1 to be rounded to decimal 80 and 74.9 to decimal 70. > How can I achieve that? >>> print '%.0e' % 74.9 7e+01 >>> print '%.0e' % 76.1 8e+01 From lists at cheimes.de Tue Aug 5 19:09:19 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 06 Aug 2008 01:09:19 +0200 Subject: Finding IP address of localhost via socket API (or other API) In-Reply-To: <38c9cdb10808051450q3912f70evdae9fd61950e09d2@mail.gmail.com> References: <38c9cdb10808051450q3912f70evdae9fd61950e09d2@mail.gmail.com> Message-ID: David York wrote: > How do I find out my machine's IP address as visible to the outside world? > Thanks a lot. Most modern routers home routers support the IGD part of UPnP (http://en.wikipedia.org/wiki/Internet_Gateway_Device_Protocol). You can use an UPnP client software to query the router for its WAN IP, connection state and upload / download speed. You may even be able to modify the port forwarding rules with UPnP. I suggest Miniupnpc, because it has nice Python bindungs. Another option is dyndns.org. You can register a new DDNS host, update it with a DDNS client and then query the IP with socket.gethostbyname(). Most modern routers have a builtin DDNS client, too. Christian From Edwin.Madari at VerizonWireless.com Wed Aug 6 22:21:38 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Wed, 6 Aug 2008 22:21:38 -0400 Subject: A question about string and float number In-Reply-To: Message-ID: <20080807022149.088391E400D@bag.python.org> type(s) == type(float()) -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org]On Behalf Of Wei Guo Sent: Wednesday, August 06, 2008 9:23 PM To: python-list at python.org Subject: A question about string and float number Hi all, I am new of python. Could anyone help me a question as below? Is there any function that can judge a string s is a float number or not? FOr example, if s = '1.232' or s='1e+10', then it returns true, otherwise, it will return false. isdigit() in string doesn't work. float() will throw an exception and I just need true or false as result. Thanks a lot in advance, Wei The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From danielk at featherbrain.net Sat Aug 9 08:42:53 2008 From: danielk at featherbrain.net (Daniel Klein) Date: Sat, 09 Aug 2008 08:42:53 -0400 Subject: How to round a floating point to nearest 10? References: Message-ID: On Sat, 9 Aug 2008 04:31:38 -0700 (PDT), Will Rocisky wrote: >I want my 76.1 to be rounded to decimal 80 and 74.9 to decimal 70. >How can I achieve that? >>> for n in (74.9, 76.1): print int((n+5)/10)*10 70 80 Dan From lfrogerscobalt at gmail.com Tue Aug 26 20:10:07 2008 From: lfrogerscobalt at gmail.com (Albertos) Date: Tue, 26 Aug 2008 17:10:07 -0700 (PDT) Subject: Free huge source codes collection Message-ID: Hello, I've collected huge source codes collection of any kinds : work with text files, database, GUI etc. You can download it here http://freactor.com/get.php?file=Python From bdesth.quelquechose at free.quelquepart.fr Tue Aug 19 14:51:20 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 19 Aug 2008 20:51:20 +0200 Subject: AOP in Python In-Reply-To: References: Message-ID: <48ab321a$0$28448$426a74cc@news.free.fr> Hussein B a ?crit : > Hey, > AOP is build in Groovy language via many means, does Python support > AOP out of the box without the need for such tools: > http://pythonsource.com/open-source/aspect-oriented-frameworks > Thanks. See the use of @decorators in most Python frameworks. When functions are first-class citizens, "AOP" starts to look like a kludgy workaround... From steve at REMOVE-THIS-cybersource.com.au Wed Aug 20 14:04:37 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2008 18:04:37 GMT Subject: Bizarre method keyword-arg bug. References: <73104fb9-3f05-445e-83e6-2b1939316f15@d77g2000hsb.googlegroups.com> <00b981ba$0$20315$c3e8da3@news.astraweb.com> Message-ID: <00bc578e$0$20315$c3e8da3@news.astraweb.com> On Wed, 20 Aug 2008 13:09:21 -0400, Robert Brown wrote: > In any case, chances are high that Lisp's way of handling default > arguments would have been changed had it been shown to cause performance > problems. But nobody is suggesting that it would cause performance problems in *Lisp*. It might, or it might not. Who cares? We're not talking about Lisp, we're talking about *Python*, and evaluating default arguments every time the function is called would certainly cause a performance hit in Python. -- Steven From grante at visi.com Fri Aug 29 10:45:00 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 29 Aug 2008 09:45:00 -0500 Subject: [1,2,3] exactly same as [1,2,3,] ? References: Message-ID: On 2008-08-29, Roy Smith wrote: > Exactly. This is one of those little pieces of syntactic > sugar which makes python so nice to work with. The > alternative is (in C, for example) abominations like this: > > const char* l[] = {"foo" > , "bar" > , "baz" > }; > > and even those are not quite as good because you still have to > special-case the first entry. It's probably a spec violation, but I've never seen a C compiler that objected to a comma after the last item in an initializer list. (At least not at the warning levels I use, which tend to be on the picky side.) -- Grant Edwards grante Yow! There's enough money at here to buy 5000 cans of visi.com Noodle-Roni! From ken at seehart.com Mon Aug 25 06:54:50 2008 From: ken at seehart.com (Ken Seehart) Date: Mon, 25 Aug 2008 03:54:50 -0700 Subject: Python String Immutability Broken! In-Reply-To: <000b01c906f1$a493bb80$0d00a8c0@hendrik> References: <000b01c906f1$a493bb80$0d00a8c0@hendrik> Message-ID: <48B28F7A.9030006@seehart.com> Hendrik van Rooyen wrote: > > ... > > Actually, I am not complaining - I am asking for advice on the side > effects of what I am doing, which is replacing a bunch of bits > in what is essentially an output bit field with the corresponding > input bits at the same addresses read back from a simulated i/o > bus structure. And I would also like to know if there is a better > way of doing this. > Yes, there is a better way. Use a character array instead of a string. http://python.net/crew/theller/ctypes/tutorial.html#arrays > ... - Ken From richardjones at optushome.com.au Sun Aug 31 22:51:45 2008 From: richardjones at optushome.com.au (Richard Jones) Date: Mon, 1 Sep 2008 12:51:45 +1000 Subject: Roundup Issue Tracker version 1.4.6 released Message-ID: <200809011251.46126.richardjones@optushome.com.au> I'm proud to release version 1.4.6 of Roundup. 1.4.6 is a bugfix release: - Fix bug introduced in 1.4.5 in RDBMS full-text indexing - Make URL matching code less matchy If you're upgrading from an older version of Roundup you *must* follow the "Software Upgrade" guidelines given in the maintenance documentation. Roundup requires python 2.3 or later for correct operation. To give Roundup a try, just download (see below), unpack and run:: roundup-demo Release info and download page: http://cheeseshop.python.org/pypi/roundup Source and documentation is available at the website: http://roundup.sourceforge.net/ Mailing lists - the place to ask questions: http://sourceforge.net/mail/?group_id=31577 About Roundup ============= Roundup is a simple-to-use and -install issue-tracking system with command-line, web and e-mail interfaces. It is based on the winning design from Ka-Ping Yee in the Software Carpentry "Track" design competition. Note: Ping is not responsible for this project. The contact for this project is richard at users.sourceforge.net. Roundup manages a number of issues (with flexible properties such as "description", "priority", and so on) and provides the ability to: (a) submit new issues, (b) find and edit existing issues, and (c) discuss issues with other participants. The system will facilitate communication among the participants by managing discussions and notifying interested parties when issues are edited. One of the major design goals for Roundup that it be simple to get going. Roundup is therefore usable "out of the box" with any python 2.3+ installation. It doesn't even need to be "installed" to be operational, though a disutils-based install script is provided. It comes with two issue tracker templates (a classic bug/feature tracker and a minimal skeleton) and four database back-ends (anydbm, sqlite, mysql and postgresql). From timr at probo.com Sat Aug 2 15:07:19 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 02 Aug 2008 19:07:19 GMT Subject: Newbie Python questions References: <12p2941fee0nnimqmraqt9cm1vml7ra2kt@4ax.com> <706f52bb-c206-4021-9a2f-2e52f6e3429b@u6g2000prc.googlegroups.com> Message-ID: binaryjesus wrote: > >One great open source GUI package that you left out is GTK ie. pygtk. >i cant compare it with wx as i have never used it but isay its much >better than QT. > >Anyway for ur q if u want to compair qt n wx. QT should be faster coz >it has a better documentation. Holy moly, did you send this from your cell phone? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From deets at nospam.web.de Wed Aug 27 05:06:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 27 Aug 2008 11:06:27 +0200 Subject: Inspecting the Instance Vars in a class/object - How? References: <1efcc029-17cc-4d5e-b70b-2a2e25dfd214@k36g2000pri.googlegroups.com> Message-ID: <6hkjpiFmjjevU1@mid.uni-berlin.de> BrendanC wrote: > I'm trying to understand reflection/introspection in Python. How can I > identify the the type of attribute (e.g. instance var) in a class? > The following returns all the class attributes (methods and instance > vars). > > However I'm interested in identifying the type of value for each case > - (e.g. I'd like to identify the instance variables separately). (The > Inspect module has an ismethod method, but not an isinstancevariable > method). Because there is no such thing, as it is not a *type*. It's a question on where the value is stored. Every *instance* has a dictionary holding it's data. You can normally access it using __dict__. But it's not "pure" in the sense that only the variables you created yourself are contained. It also contains the reference to the class. On the class, there is also a __dict__, which contains the method-descriptors and class-variables. In the face of multi-inheritance, things get even more complicated, as then the values are acquired through MRO-lookup. > e.g. In the following example I'd like to extract the class vars > strvar and intNum and ignore the methods/other attribute types. > > What is the best way to do this? > > class test: > # Dummy Class for reflection testing > strVar = '1234' > intNum = 0 > > def nullmethod(): > pass > > def addmethod(self,v1, v2): > v = v1 + v2 > return v > > if __name__ == "__main__": > mytest = test() > for key in dir(mytest): > value = getattr(object, key) > print 'Key: %s ; Value %s ' % (str(key) ,str(value)) if name in mytest.__dict__: print "instance variable" From ptmcg at austin.rr.com Mon Aug 18 10:59:07 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 18 Aug 2008 07:59:07 -0700 (PDT) Subject: Good python equivalent to C goto References: <48a744b6$0$299$7a628cd7@news.club-internet.fr> Message-ID: On Aug 17, 1:09?pm, Matthew Fitzgibbons wrote: > Kurien Mathew wrote: > > Hello, > > > Any suggestions on a good python equivalent for the following C code: > > > while (loopCondition) > > { > > ? ? if (condition1) > > ? ? ? ? goto next; > > ? ? if (condition2) > > ? ? ? ? goto next; > > ? ? if (condition3) > > ? ? ? ? goto next; > > ? ? stmt1; > > ? ? stmt2; > > next: > > ? ? stmt3; > > ? ? stmt4; > > ?} > > > Thanks > > Kurien > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I would not be too happy if I saw C code like that in my repository. > This is equivalent: > > while (loopCondition) { > ? ? ?if (!(condition1 || condition2 || condition3)) { > ? ? ? ? ?stmt1; > ? ? ? ? ?stmt2; > ? ? ?} > ? ? ?stmt3; > ? ? ?stmt4; > > } > > In Python: > > while (loopCondition): > ? ? ?if not (condition1 or condition2 or condition3): > ? ? ? ? ?stmt1 > ? ? ? ? ?stmt2 > ? ? ?stmt3 > ? ? ?stmt4 > > If stmt3 and stmt4 are error cleanup code, I would use try/finally. > > while loopCondition: > ? ? ?try: > ? ? ? ? ?if condition1: > ? ? ? ? ? ? ?raise Error1() > ? ? ? ? ?if condition2: > ? ? ? ? ? ? ?raise Error2() > ? ? ? ? ?if condition3: > ? ? ? ? ? ? ?raise Error3() > ? ? ? ? ?stmt1 > ? ? ? ? ?stmt2 > ? ? ?finally: > ? ? ? ? ?stmt3 > ? ? ? ? ?stmt4 > > This will also bail out of the loop on and exception and the exception > will get to the next level. If you don't want that to happen, put an > appropriate except block before the finally. > > -Matt- Hide quoted text - > > - Show quoted text - Close, but there is no reason for the conditions to raise anything, they can just use the continue statement: i = 20 while i > 0: try: if i % 2: continue if i % 3: continue print i, "is even and a multiple of 3" finally: i -= 1 Prints: 18 is even and a multiple of 3 12 is even and a multiple of 3 6 is even and a multiple of 3 I think this is closest to the OP's stated requirements. -- Paul From fredrik at pythonware.com Sat Aug 23 18:28:55 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 24 Aug 2008 00:28:55 +0200 Subject: dropwhile question In-Reply-To: References: <84bdef3c0808231454v3e6f347eucae1f7abeabe193d@mail.gmail.com> Message-ID: Fredrik Lundh wrote: > maybe you meant to use itertools.ifilter? > > >>> help(itertools.ifilter) > Help on class ifilter in module itertools: > > class ifilter(__builtin__.object) > | ifilter(function or None, sequence) --> ifilter object > | > | Return those items of sequence for which function(item) is true. > | If function is None, return the items that are true. > > >>> list(itertools.ifilter(lambda x: x<5,range(10))) > [0, 1, 2, 3, 4] > >>> list(itertools.ifilter(lambda x: 2 [3, 4] or, more likely, ifilterfalse: >>> list(itertools.ifilterfalse(lambda x: x<5,range(10))) [5, 6, 7, 8, 9] >>> list(itertools.ifilterfalse(lambda x: 2 From jr9445 at ATT.COM Wed Aug 6 14:01:49 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Wed, 6 Aug 2008 13:01:49 -0500 Subject: Monitor and compare two log files in real time In-Reply-To: <6f11115b-6f19-4ca4-97e6-0a0781ed617c@b30g2000prf.googlegroups.com> References: <6f11115b-6f19-4ca4-97e6-0a0781ed617c@b30g2000prf.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of m > Sent: Wednesday, August 06, 2008 1:25 PM > To: python-list at python.org > Subject: Monitor and compare two log files in real time > > I have a script I would like to write but I am not sure of where to > start / approach. Perhaps someone could help direct me in the right > direction. Any advice is appreciated. > > I would like to write a python script that monitors two log files. > If a certain string, lets say string1 shows up in logfile-A, I want to > check if that same string shows up in log file-B within 8 minutes. If > it does not show up within 8 minutes, send an email ( using sendmail > or postfix). > > Do you have any suggestions? > -- Google on "python tail" to get a python implementation of the unix tail command. The rest should be easy. http://code.activestate.com/recipes/157035/ ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA622 From mtobis at gmail.com Sun Aug 31 23:03:04 2008 From: mtobis at gmail.com (Michael Tobis) Date: Sun, 31 Aug 2008 20:03:04 -0700 (PDT) Subject: How Compute # of Days between Two Dates? References: Message-ID: <28c7258c-4522-4fce-b68e-1fa0cf227237@a70g2000hsh.googlegroups.com> from datetime import datetime # batteries included today = datetime.now() xmas = datetime(today.year,12,25) if (xmas - today).days > 1: print "%d days until Christmas" % (xmas - today).days else: print "Merry Christmas!" From jeremy+complangpython at jeremysanders.net Fri Aug 8 08:43:08 2008 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Fri, 08 Aug 2008 13:43:08 +0100 Subject: random numbers according to user defined distribution ?? References: Message-ID: Alex wrote: > I wonder if it is possible in python to produce random numbers > according to a user defined distribution? > Unfortunately the random module does not contain the distribution I > need :-( Have you looked at the numpy random number module? It seems to have quite a lot of distributions. See help(numpy.random). Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From saptarshi.guha at gmail.com Sat Aug 16 23:31:02 2008 From: saptarshi.guha at gmail.com (sapsi) Date: Sat, 16 Aug 2008 20:31:02 -0700 (PDT) Subject: sqlite empty inserts References: <9c28ccd0-ba04-4e21-8cbb-ff8959c4801e@m44g2000hsc.googlegroups.com> <72373c22-33dc-45dd-aea7-b31e36ac6169@b1g2000hsg.googlegroups.com> Message-ID: <2b8a6d90-4b1b-4a68-a6cc-c3f031c2ac44@y38g2000hsy.googlegroups.com> On Aug 16, 11:20?am, Peter Otten <__pete... at web.de> wrote: > sapsi wrote: > > [please don't top-post] > > > > > Thank you for the tip, you're absolutely right.I;m getting an > > exception ?that the name must not be null. However, this is some debug > > output > > --- logging.debug(" %s %s %s" % ?(vdbname, foldername,where_query)) > > OUTPUT: TestVDB test_b title regexp 'tit' > > --- print ?vdbname.__class__, > > foldername.__class__,where_query.__class__ > > OUTPUT: > > > --- self.cursor.execute( "insert into __saved_query__(vdb_name, > > query_table_name, query) values (?,?,?)", (vdbname, > > foldername,where_query)) > > > OUTPUT: __saved_query__.vdb_name may not be NULL > > > I honestly don't get it!. Why should this occur? > > Because vbdname is None? > > Seriously, it's hard for us to tell what's going on without the relevant > code. If you don't provide enough context you are on your own. > > Peter Actualy, vdbname is not none. I checked the value before entering. I found out that by closing the connection and reopening after creating VIEW solved the problem. Not a nice solution but it works and not a hassle given the low frequency of the operation. Regards Saptarshi --code self.cursor.execute( "insert into __smartfolder__ values (?,?,?,?)", (vdbname, foldername,where_query,hrform)) self.conn.commit() self.cursor.execute("CREATE VIEW %s AS %s" % (foldername, query) ) self.conn.close() self.connect_to_db() --- If i didn't close and reopen, the second time i try inserting i get the aforementioned error From daniel.watrous at gmail.com Tue Aug 26 17:35:20 2008 From: daniel.watrous at gmail.com (Daniel) Date: Tue, 26 Aug 2008 14:35:20 -0700 (PDT) Subject: Python and database unittests Message-ID: Hello, I'm writing an application that interacts with a database. As I think about how to write the unittests, I want them to be able to run without actually having to access a live database. The pattern that best describes this is here: http://martinfowler.com/eaaCatalog/serviceStub.html I have found http://qualitylabs.org/pdbseed/, which helps with unittests for a live database. This isn't what I'm after. Does anyone know about a module that acts as a database stub for python unittests? Thanks, Daniel From steve at REMOVE-THIS-cybersource.com.au Mon Aug 4 18:52:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2008 22:52:43 GMT Subject: very large dictionary References: <5c5e6d6e-04ef-4340-963f-d3825875b32c@e39g2000hsf.googlegroups.com> <6fftjvFb7ktoU2@mid.uni-berlin.de> <60FCF960-D1CD-4885-9F46-B5D7B798A9FF@gmail.com> <20080803224254.GG11163@tuva.opensoft.se> <6b690d0c-d817-4582-9dd1-9309b2d5cda1@e39g2000hsf.googlegroups.com> Message-ID: <00a78388$0$20302$c3e8da3@news.astraweb.com> On Mon, 04 Aug 2008 07:02:16 -0700, Simon Strobl wrote: > I created a python file that contained the dictionary. The size of this > file was 6.8GB. Ah, that's what I thought you had done. That's not a dictionary. That's a text file containing the Python code to create a dictionary. My guess is that a 7GB text file will require significantly more memory once converted to an actual dictionary: in my earlier post, I estimated about 5GB for pointers. Total size of the dictionary is impossible to estimate accurately without more information, but I'd guess that 10GB or 20GB wouldn't be unreasonable. Have you considered that the operating system imposes per-process limits on memory usage? You say that your server has 128 GB of memory, but that doesn't mean the OS will make anything like that available. And I don't know how to even start estimating how much temporary memory is required to parse and build such an enormous Python program. Not only is it a 7GB program, but it is 7GB in one statement. > I thought it would be practical not to create the > dictionary from a text file each time I needed it. I.e. I thought > loading the .pyc-file should be faster. Yet, Python failed to create a > .pyc-file Probably a good example of premature optimization. Out of curiosity, how long does it take to create it from a text file? -- Steven From eliben at gmail.com Thu Aug 21 08:33:15 2008 From: eliben at gmail.com (eliben) Date: Thu, 21 Aug 2008 05:33:15 -0700 (PDT) Subject: exception handling in complex Python programs References: <00bd3cc9$0$20315$c3e8da3@news.astraweb.com> Message-ID: <5ed98500-9b5e-4d2e-b34f-b20c946025f8@z72g2000hsb.googlegroups.com> > >http://eli.thegreenplace.net/2008/08/21/robust-exception-handling/ > > Just a few random points. You say: > > "Exceptions are better than returning error status codes. Some languages > (like Python) leave you with no choice as the whole language core and > standard libraries throw exceptions." > > Of course you have a choice. Your function can return anything you want: > Of course. I didn't mean that the language prohibits returning error codes, just that you can't use it without employing exception handling. I've fixed the wording to make it clearer. > You also wrote: > > "Exceptions exist for exceptional situations: unanticipated events that > are not a part of normal execution." > > Exceptions can and often are anticipated. E.g. if you write code that > opens a URL, you better anticipate that the server might reject your > connection. You better expect to be asked for a cookie, or > authentication. If you check for robots.txt, you better expect that it > might not exist. That's all normal execution. This is a point I'm not 100% in accord with. I still think that exceptions are for exceptional situations. I've removed the word "unanticipated" though, because it probably has no place in that sentence. However, I think that if one of your valid execution paths is w/o robots.txt, you should not use an exception to check whether it's there. This indeed uses the "bad side" of exceptions, splitting the exetution to two paths. Check if robots.txt is there. If it is, open it. If you can't open it, *that* is an exception, but if it's just not there, well it's part of your application logic. I believe this isn't against EAFP. I'm not sure I'm making the distinction clear here, it's a fine point. > > "When a programmer calls str.find('substring') he doesn?t expect an > exception to be thrown if the substring isn?t found." > > But if he called str.index() then he does expect an exception to be > thrown, just like for list.index() and dict[key] can raise exceptions. > They are neither bugs nor unexpected. > But why are there two versions that are the same except for the behavior in case it wasn't found ? My wishful imagination is precisely because of the reasons I've named. If you *know* it's there, use .index() - then, if it fails, it's an exception, but if a part of your logic is finding an item that might be missing, use a special value because you want to keep the logic in a single path. > "When used for flow-control, exceptions are like goto. There might be a > few esoteric cases in which they?re appropriate, but 99.99% of the time > they are not." > > I strongly disagree. try...except is like break or continue. Yes, it > breaks the linear flow of control, but not in a wild, dangerous way like > goto. > try...except can 'exit' to several 'catch points', unlike break/ continue. Furthermore, try...except can bring execution to another hierarchy level if it's not caught where it's thrown, so it's much more like goto in these senses. To find where the execution may go you'll find yourself searhching for the exception name over your source files, looking for the exception class name in some "except" clause. Sounds like looking for a goto label. P.S. Thanks a lot for taking the time to comment Eli From malaclypse2 at gmail.com Tue Aug 12 11:04:24 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 12 Aug 2008 11:04:24 -0400 Subject: python interpreter In-Reply-To: <29e59f7a-af87-40b4-9c5e-58abe1a28721@t1g2000pra.googlegroups.com> References: <29e59f7a-af87-40b4-9c5e-58abe1a28721@t1g2000pra.googlegroups.com> Message-ID: <16651e80808120804h53bb09b7sc5583ae6454db23b@mail.gmail.com> On Tue, Aug 12, 2008 at 10:49 AM, Alexandru Mosoi wrote: > I'm using python's interpreter's to run various commands (like a > normal shell). However if sources are modified changes are not > reflected so I have to restart interpreter. Is there any way to avoid > restarting this? > > example: > import blah reload(blah) Please see the documentation (http://docs.python.org/lib/built-in-funcs.html) for reload, though. There are lots of caveats to keep in mind. In particular, reload does not work if you import using the 'from ... import ...' construct, and it doesn't do anything magical about existing instances of classes that have now been redefined. Using reload() can be a useful tool when you are prototyping things and using them in the interactive interpreter, but probably should not be relied on in production code. -- Jerry From john.sasil at gmail.com Thu Aug 14 03:44:07 2008 From: john.sasil at gmail.com (john.sasil at gmail.com) Date: Thu, 14 Aug 2008 00:44:07 -0700 (PDT) Subject: i want to control python using keyboard Message-ID: <5bab4be9-4abc-4b42-84bc-e7e441b35120@v39g2000pro.googlegroups.com> hi i want to play alarm sound when i press a particular key in keyboard.so someone help me in doing it. Thanks and Regards Sasil.G From martin at see.sig.for.address.invalid Sun Aug 24 08:28:01 2008 From: martin at see.sig.for.address.invalid (Martin Gregorie) Date: Sun, 24 Aug 2008 12:28:01 +0000 (UTC) Subject: The Importance of Terminology's Quality References: <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> <48af8cc4$0$20919$607ed4bc@cv.net> <48b0b81f$0$7353$607ed4bc@cv.net> Message-ID: On Sat, 23 Aug 2008 21:22:05 -0400, John W Kennedy wrote: > Martin Gregorie wrote: >> On Sat, 23 Aug 2008 00:06:28 -0400, John W Kennedy wrote: >> >>> Martin Gregorie wrote: >>>> Not necessarily. An awful lot of CPU cycles were used before >>>> microcode was introduced. Mainframes and minis designed before about >>>> 1970 didn't use or need it >>> No, most S/360s used microcode. >> >> I never used an S/360. >> >> I thought microcode came into the IBM world with S/370 and Future >> Series (which later reappeared as the AS/400, which I did use). Didn't >> the S/370 load its microcode off an 8 inch floppy? > > Some did, but not all. The 370/145 was the first, and made a big splash > thereby. > ..snip... Thanks for that. As I said, during most of that era I was using ICL kit. Microcode was never mentioned in the 1900 contect. Hoiwever, they had a very rough approximation called extracodes. though they were closer to software traps than microcode: if hardware didn't implement an op code the OS intercepted it and ran equivalent code. This was used for i/o operations and for FP instructions on boxes that didn't have FP hardware. As a result all boxes executed the same instruction set. Some opcodes might be very slow on some hardware but it would execute. The 2900 series had huge amounts of microcode - it even defined both memory mapping and opcodes. You could run 1900 code (24 bit words, fixed length instructions, ISO character codes) simultaneously with 'native' code (8 bit bytes, v/l instructions, EBCDIC) with each program running under its usual OS (George 3 for 1900, VME/B for 1900). The only other systems I'm aware of that could do this were the big Burroughs boxes (6700 ?), which used a byte-based VM for COBOL and a word- based VM for FORTRAN and Algol 60) and IBM AS/400 (OS/400 could run S/34 code alongside S/38 and AS/400 code). AFAICT Intel virtualisation doesn't do this - all code running under VMware or any of the other VMs is still running in a standard Intel environment. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From smbaker at gmail.com Wed Aug 13 15:31:42 2008 From: smbaker at gmail.com (Scott) Date: Wed, 13 Aug 2008 12:31:42 -0700 (PDT) Subject: getting full exception information from an xmlrpc server Message-ID: <1091f512-7b47-4bec-93f5-32f4e6516505@o40g2000prn.googlegroups.com> I'm debugging an xmlrpc client/server application. Often when an exception occurs in the server, I receive only a very short error message on the client. For example: xmlrpclib.Fault: :"> Presumably this is because xmlrpclib on the server is catching the exception, and only sending the exception name to the client, not the server's stack trace. What I would like is the full stack trace of what went wrong on the server (i.e. the junk python usually dumps to the console when an exception occurs). I don't care which side I see the dump on (client or server), but I need to see the whole trace so I can figure out what the problem is. Is there an easy way to do this? Thanks, Scott From mathieu.prevot at ens.fr Thu Aug 21 05:17:58 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Thu, 21 Aug 2008 11:17:58 +0200 Subject: subprocess seems to "detach" / ignore wait() In-Reply-To: References: <3e473cc60808202241j2825bc3cl7f1050f1ec68563b@mail.gmail.com> <3e473cc60808202246r48e2b692q3e82efa1fbbd6c78@mail.gmail.com> Message-ID: <3e473cc60808210217i187ad991ye98d4540ca2f5398@mail.gmail.com> 2008/8/21 Gabriel Genellina : > En Thu, 21 Aug 2008 02:46:06 -0300, Mathieu Prevot escribi?: > >>> So what is the right thing to do so my script >>> returns 1 or 0 depending on its state and success ? > > I use something like this: > > def main(argv): > try: > try: > do_things() > return 0 > finally: > do_cleanup() > except: > log_exception() > return 1 > > if __name__=='__main__': > import sys > sys.exit(main(sys.argv)) > >> PS: BTW how can I detach my process ie have an equivalent to >> `myscript.py&` from the python script ? > > There are a few recipes in the Python CookBook at http://code.activestate.com/recipes/langs/python/ The return from main()... it was my thought too. Thank you Gabriel :) Mathieu From gminick at bzt.bzt Sun Aug 31 13:20:43 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Sun, 31 Aug 2008 17:20:43 +0000 (UTC) Subject: How can we get to the end of a quote inside a string References: Message-ID: On Sun, 31 Aug 2008 07:29:26 -0700 (PDT), rajmohan.h at gmail.com wrote: > Suppose I have a string which contains quotes inside quotes - > single and double quotes interchangeably - > s = "a1' b1 " c1' d1 ' c2" b2 'a2" >>> s = "a1' b1 " c1' d1 ' c2" b2 'a2" File "", line 1 s = "a1' b1 " c1' d1 ' c2" b2 'a2" ^ SyntaxError: invalid syntax >>> Writing a small parser for your needs shouldn't be that hard. To some extent you can use regular expressions: >>> re.findall(re.compile("\".*?\""), s) ['" c1\' d1 \' c2"'] >>> re.findall(re.compile("\'.*?\'"), s) ['\' b1 " c1\'', '\' c2" b2 \''] >>> but it won't work in all cases. You can read more here: http://www.gnosis.cx/TPiP/ -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From gandalf at shopzeus.com Fri Aug 8 05:25:14 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 08 Aug 2008 11:25:14 +0200 Subject: Fastest way to store ints and floats on disk In-Reply-To: References: <489B41CE.8080909@shopzeus.com> Message-ID: <489C10FA.3000005@shopzeus.com> > > Hmm... I wrote an browser based analysis tool and used the working > name pyvot... Is this for the public domain? > > I found Numeric to provide the best balance of memory footprint and > speed. I also segregated data prep into a separate process to avoid > excessive memory use at run time. Turns out python Do you mean numpy? (Numeric is not actively supported, numarray is deprecated.) > > For the site I'm at, I've got 10 years sales history recapped from > 4327846 detail records into 458197 item by customer by month records > and top shows a 240Mb memory footprint. I've got 21 cross indexed > selection fields, and can display up to six data types (qty, price, > sqft, cost, gp%, avg). At another site I've got approx 8.5M records > recapped into 1M records with 15 indexes and 5 years monthly history > living in a 540Mb memory footprint. > > It's reasonably quick: a query like 'select san mateo, foster city and > san carlos accounts, sort by customer and product category and display > this year's sales by month' selects 260 records and renders in the > browser in about 2 seconds. Or on the larger installation 'Show sales > for the past five years for product group 12 sorted by city within > route' selects 160 records and renders in about 3 seconds. Incredible. :-) > My objective was to keep the info in memory for fast response times. Permature optimalization is the root of all evil. (Who said that?) All right, first I'll try to keep it in memory and come back if that doesn't work out. > I played a lot of games getting this all to work well, including some > c extensions, but Numeric's take, sum, tostring and fromstring ended > up with 'pivotal' roles. :) Thank you, Laszlo From castironpi at gmail.com Wed Aug 6 00:55:10 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 5 Aug 2008 21:55:10 -0700 (PDT) Subject: string to type object (C) References: <4477a269-f189-4ae1-9c97-e78633bb3d27@2g2000hsn.googlegroups.com> Message-ID: <6a725a88-5407-455d-a9e3-d63aff64eddf@t54g2000hsg.googlegroups.com> On Aug 5, 7:59?pm, Miles wrote: > On Tue, Aug 5, 2008 at 2:30 AM, castironpi wrote: > > I'm looking for a one-to-one function from strings to the built-in > > data types in C. ?I will be keeping the string in a file. ?I need the > > PyTypeObject* back from it. ?If nothing else I'll just do a bunch of > > strcmp( "tuple" ) { return &PyTuple_Type; } commands, provided > > &PyTuple_Type; will be linking the right address. > > Something along the lines of this? > b = PyImport_Import("__builtin__"); > return PyObject_GetAttrString(b, typestring); > > -Miles Miles, That's what I was looking for. I wanted to avoid the heavy Import but I thought I remembered that imports are free after the first time. Import needed a PyString. PyObject* s= PyString_FromString( "__builtin__" ); PyObject* b= PyImport_Import(s); return PyObject_GetAttrString(b, "str"); I expect I need a Py_DECREF on s and b. Do you know if uncooperative (not necc'ly malicious) code could interfere: >>> __builtin__.int= None >>> __builtin__.int >>> __builtin__.int= type( 0 ) >>> __builtin__.int ? Or would PyImport_Import(s) create a namespace that had the int type in it from scratch? From jwkenne at attglobal.net Sat Aug 23 00:18:29 2008 From: jwkenne at attglobal.net (John W Kennedy) Date: Sat, 23 Aug 2008 00:18:29 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: <0-SdnROBHqDbVDHVnZ2dnUVZ_jWdnZ2d@speakeasy.net> References: <48a782e9$0$20913$607ed4bc@cv.net> <48a8df27$0$7362$607ed4bc@cv.net> <0-SdnROBHqDbVDHVnZ2dnUVZ_jWdnZ2d@speakeasy.net> Message-ID: <48af8f95$0$29518$607ed4bc@cv.net> Rob Warnock wrote: > What was the corresponding 1401 boot sequence? The 1401 had a boot-from-tape-1 button on the console, and a boot-from-card button on the card reader. You couldn't truly boot from a disk; you loaded a little starter deck of about 20 cards on the card reader. On the 1401, the typewriter was an optional luxury, mainly used in long batch jobs to do ad-hoc on-line queries. On the compatible 1460, the typewriter was somewhat more common, because the console the typewriter mounted on was a standard part of the system, so only the typewriter had to be added. -- John W. Kennedy "You can, if you wish, class all science-fiction together; but it is about as perceptive as classing the works of Ballantyne, Conrad and W. W. Jacobs together as the 'sea-story' and then criticizing _that_." -- C. S. Lewis. "An Experiment in Criticism" From james7047276 at googlemail.com Sun Aug 24 11:22:29 2008 From: james7047276 at googlemail.com (james7047276 at googlemail.com) Date: Sun, 24 Aug 2008 08:22:29 -0700 (PDT) Subject: aec kontaktanzeigen in Bad Hersfeld internet kontaktanzeigen erotik kontaktanzeigen net fremdgehen * kontaktanzeigen paar singletreff aachen kontaktanzeigen bielefeld fremd gehen single treff erotische kontaktanzeigen bielefeld Message-ID: <54ff2f88-d158-4d51-93f8-7e54603937b0@b1g2000hsg.googlegroups.com> aec kontaktanzeigen in Bad Hersfeld internet kontaktanzeigen erotik kontaktanzeigen net fremdgehen * kontaktanzeigen paar singletreff aachen kontaktanzeigen bielefeld fremd gehen single treff erotische kontaktanzeigen bielefeld + + EROTIK KONTAKTE - EROTISCHE KONTAKTANZEIGEN http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ + + + + + + + + + + + singletreff g?ttingen in Oschatz lustige sex kontaktanzeigen in G?nzburg kontaktanzeigen schwerin in Landsberg schwule kontaktanzeigen in Hildesheim fremdgehen macht in Prenzlau single erotische kontaktanzeigen in Bad erotik kontaktanzeigen thueringen in Aue kontaktanzeigen mainz in Ruppin private kontakt anzeigen in Eisleben kontaktanzeigen schwul in Koethen www single erotik kontaktanzeigen org in Wolfratshausen single kontaktanzeigen in Bergen sex kontaktanzeigen niedersachsen in Waldeck http://www.bebin.tv/forum/showthread.php?t=31454 - christliche kontaktanzeigen in F?rth http://www.bloglines.com/forums/read.php?21,71919 - sex kontaktanzeigen thueringen in Freiburg http://www.gamesforum.ca/showthread.php?t=317057 - sex kontaktanzeigen osteuropa in Kamenz http://www.bebin.tv/forum/showthread.php?t=31384 - kontaktanzeigen f?r schwule in Delitzsch http://www.meinews.net/jedes-t226215.html - kontaktanzeigen thueringen in Dieburg http://www.meinews.net/cialis-t244424.html - aec erotik kontaktanzeigen in Meiningen http://billige-autoreifen.mirror-server.net Billige Autoreifen - kontaktanzeigen niedersachsen in Sta?furt http://draconian.com/dragon-forum/showthread.php?t=17742 - single treff siegen in Boeblingen http://www.gamesforum.ca/showthread.php?t=319660 - erotik kontaktanzeigen cottbus in Gro?-Gerau http://www.meinews.net/cialis-t244251.html - erotik kontaktanzeigen fuer dicke in Waldeck http://www.gamesforum.ca/showthread.php?t=319638 - sex kontaktanzeigen aachen in Wesel http://www.bloglines.com/forums/read.php?10,71529 - FilipinoFriendFinder.com in Weilburg http://draconian.com/dragon-forum/showthread.php?t=20493 - kostenlose singletreff in Gie?en http://www.meinews.net/erotik-t245288.html - sex kontaktanzeigen heidelberg in Beeskow From castironpi at gmail.com Wed Aug 27 14:12:37 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 27 Aug 2008 11:12:37 -0700 (PDT) Subject: Python multimap References: Message-ID: <4d2f1ac5-c21c-42d9-977e-6493f0c23573@d77g2000hsb.googlegroups.com> On Aug 27, 12:52?pm, brad wrote: > Mike Kent wrote: > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> k = {} > >>>> k['1'] = [] > >>>> k['1'].append('Tom') > >>>> k['1'].append('Bob') > >>>> k['1'].append('Joe') > > >>>> k['1'] > > ['Tom', 'Bob', 'Joe'] > > There is only one '1' key in your example. I need multiple keys that are > all '1'. I thought Python would have something built-in to handle this > sort of thing. > > I need a true multimap: > > k['1'] = 'Tom' > k['1'] = 'Tommy' > > without Tommy overwriting Tom and without making K's value a list of > stuff to append to. That's still just a regular map. I don't understand what a multimap does that a map of lists doesn't do. From wuwei23 at gmail.com Sat Aug 9 12:10:27 2008 From: wuwei23 at gmail.com (alex23) Date: Sat, 9 Aug 2008 09:10:27 -0700 (PDT) Subject: internet searching program References: <304d52cb-a8a8-46d5-81be-4eb01c73d479@26g2000hsk.googlegroups.com> Message-ID: On Aug 9, 12:59 pm, KillSwitch wrote: > Is it possible to make a program to search a site on the internet, > then get certain information from the web pages that match and display > them? Like, you would put in keywords to be searched for on > youtube.com, then it would search youtube.com, get the names of the > videos, the links, and the embed information? Or something like that. You might find the mechanize module handy: http://wwwsearch.sourceforge.net/mechanize/ And possibly BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/ From ktenney at gmail.com Fri Aug 8 17:13:36 2008 From: ktenney at gmail.com (Kent Tenney) Date: Fri, 8 Aug 2008 21:13:36 +0000 (UTC) Subject: sending to an xterm References: <20080808205821.GJ23567@dragontoe.org> Message-ID: Derek Martin pizzashack.org> writes: > > On Fri, Aug 08, 2008 at 08:25:19PM +0000, Kent Tenney wrote: > > Howdy, > > > > I want to open an xterm, send it a command and have it execute it. > > You can't do that. xterm doesn't execute shell commands passed on > stdin... It can, however, execute one passed on the command line. > > Instead of just running xterm, you can run "xterm -e 'cmd foo bar'" > where cmd is the program to run and foo and bar are its arguments. > The problem is that as soon as the program exits, xterm will exit > also. > OK, I see that. (getting off topic) any chance of keeping the xterm open after running the command? Thanks, Kent From timothy.grant at gmail.com Mon Aug 4 18:45:57 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Mon, 4 Aug 2008 15:45:57 -0700 Subject: Why doesn't import work? In-Reply-To: <9ff8bc40-3cc7-4d01-a577-bce3f7b9b557@e39g2000hsf.googlegroups.com> References: <9ff8bc40-3cc7-4d01-a577-bce3f7b9b557@e39g2000hsf.googlegroups.com> Message-ID: On Mon, Aug 4, 2008 at 3:34 PM, ssecorp wrote: > I have in Lib/site-packages a module named pdfminer. when I do import > pdfminer it complains: > >>>> import pdfminer > > Traceback (most recent call last): > File "", line 1, in > import pdfminer > ImportError: No module named pdfminer > > > I created a file pdfminer.py and put it in site-packages and that > works. > > so I apparently can't import a directory pdfminer. In the directory > pdfminer there are 3 other directoriees and inside them python-files. > > how would I import them? > -- > http://mail.python.org/mailman/listinfo/python-list > set your PYTHONPATH environment to include the directory where your module is. -- Stand Fast, tjg. [Timothy Grant] From weiguo6 at gmail.com Thu Aug 7 19:39:09 2008 From: weiguo6 at gmail.com (Wei Guo) Date: Thu, 7 Aug 2008 16:39:09 -0700 Subject: A question about string and float number In-Reply-To: References: <489A8A01.1050908@linkline.com> Message-ID: Hi Grant, I am using the try/exception and just curious why function type doesn't work. Best regards, Wei On 8/7/08, Timothy Grant wrote: > > That's because s IS a string. It's not been converted to a float. > > In [1]: s = '3.1415' > In [2]: n = float(s) > In [3]: type(s) > Out[3]: > In [4]: type(n) > Out[4]: > > Why are you avoiding the very simple try:/except: solution to this problem? > > On Thu, Aug 7, 2008 at 1:28 PM, Wei Guo wrote: > > Hi I tried the first type method but it seens that it doesn't work. Could > > anyone help me about it? > > > >>>> s = '3.145' > >>>> type(s) == type(float()) > > False > >>>> type(s) > > > >>>> type(float()) > > > >>>> > > > > Best regards, > > > > Wei > > > > > > On 8/7/08, Wei Guo wrote: > >> > >> Hi Thanks for Tyler and Edwin's help. > >> > >> For my questions, I need to import some xml file and there are floating > >> number and strings in it. I need to process string and number > differently. > >> This is reason that I am asking question here. Is this background > >> information we need for this quesions. > >> > >> Btw, which way is better? type or with exception ValueError? > >> > >> Thanks, > >> > >> Wei > >> > >> > >> On 8/6/08, Tyler Breisacher wrote: > >>> > >>> It's generally a bad idea to use "except" without naming a specific > >>> exception. The exception you might expect in this case is ValueError. > Any > >>> other exception *should* be uncaught if it happens. By the way, this > method > >>> will return true for integers as well as floats. For example, > isFloat('3') > >>> will return 3.0. So make sure this is what you want, since it wasn't > 100% > >>> clear from the original message. > >>> > >>> > >>> Wei Guo wrote: > >>>> > >>>> #this is a better way of testing a string for float > >>>> def isFloat(s): > >>>> try: > >>>> s = float(s) > >>>> except: > >>>> return False > >>>> return True > >>> > >>> > >>> -- > >>> http://mail.python.org/mailman/listinfo/python-list > >> > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > Stand Fast, > tjg. [Timothy Grant] > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rpw3 at rpw3.org Thu Aug 21 10:11:48 2008 From: rpw3 at rpw3.org (Rob Warnock) Date: Thu, 21 Aug 2008 09:11:48 -0500 Subject: The Importance of Terminology's Quality References: <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: sln at netherlands.com> wrote: +--------------- | rpw3 at rpw3.org (Rob Warnock) wrote: | >In the LGP-30, they used hex addresses, sort of[1], but the opcodes | >(all 16 of them) had single-letter mnemonics chosen so that the | >low 4 bits of the character codes *were* the correct nibble for | >the opcode! ;-} ... | >[1] The LGP-30 character code was defined before the industry had | > yet standardized on a common "hex" character set, so instead of | > "0123456789abcdef" they used "0123456789fgjkqw". [The "fgjkqw" | > were some random characters on the Flexowriter keyboard whose low | > 4 bits just happened to be what we now call 0xa-0xf]. Even worse, | > the sector addresses of instructions were *not* right-justified | > in the machine word (off by one bit), plus because of the shift- | > register nature of the accumulator you lost the low bit of each | > machine word when you typed in instructions (or read them from | > tape), so the address values you used in coding went up by *4*! | > That is, machine locations were counted [*and* coded, in both | > absolute machine code & assembler] as "0", "4", "8", "j", "10", | > "14", "18", "1j" (pronounced "J-teen"!!), etc. | | Whats os interresting about all this hullabaloo is that nobody has | coded machine code here, and know's squat about it. +--------------- Think again! *BOTH* of the two examples I gave -- for the LGP-30 & the IBM 1410 -- *WERE* raw machine code, *NOT* assembler!!! Please read again what I wrote about the character codes for the instruction mnemonics *BEING* the machine instruction codes. For the IBM 1410, the bootstrap code that ones types in: v v L%B000012$N *IS* raw machine code, *NOT* assembler!! [See my previous post for the meaning of the fields of that instruction.] The IBM 1410 is a *character* machine, not a binary machine, so each memory location is a (6+1 bit) character. As a result, one can [and *must*, during bootup!] type absolute machine code directly into memory using the console typewriter [an only-slightly-modified IBM Selectric, as it happens]. The fact that -- for the sake of user convenience -- the hardware supports manual entry of machine code into memory by the operator in a form that closely *resembles* assembler (but *ISN'T*!) was a deliberate design feature. Similarly, the characters you type for the LGP-30's opcodes *ARE* the opcodes, at least by the time they get into the machine, since when typing in code (or reading it from paper tape) one sets the I/O system to "4-bit input mode", in which the upper bits of the characters are stripped off by the I/O hardware during input. Thus when you type a "Bring" (load) instruction such as this ["Bring" (load) location 0xd7c (track 0xd, sector 0x31)]: b0q7j you're typing *RAW* machine code, *NOT* assembler!! You see, the lower 4 bits of character "b" -- the "mnemonic" for "Bring" -- were binary 0001, the *same* as the lower 4 bits of the digit "1" (and two other characters as well). So when you typed a "b" in that position in "4-bit input mode" you were typing the same thing as the character "1" which was the same thing as *binary* 0001 which was the absolute machine opcode for the ""Bring" instruction!! "No assembler required" (pardon the pun). +--------------- | I'm not talking assembly language. +--------------- Neither was I. The fact that for the two machines I mentioned absolute machine code was somewhat readable to humans seems to have confused you, but that's the way some people liked to design their hardware back in those days -- with clever punning of character codes with absolute machine opcodes (for the convenience of the user). +--------------- | Don't you know that there are routines that program machine code? +--------------- What do you mean "routines"?!? For the above two machines, you can enter machine code with *no* programs ("routines?") running; that is, no boot ROM is required (or even available, as it happened). +--------------- | Yes, burned in, bitwise encodings that enable machine instructions? +--------------- The two machines mentioned above did not *HAVE* a "boot ROM"!! You had to *manually* type raw, absolute machine code into them by hand every time you wanted to boot them up [at least a little bit, just enough to load a larger bootstrap program]. +--------------- | Nothing below that. +--------------- You're assuming that all machines *have* some sort of "boot ROM". Before the microprocessor days, that was certainly not always the case. The "boot ROM", or other methods of booting a machine without manually entering at least a small amount of "shoelace" code [enough the *load* the real bootstrap], was a fairly late invention. -Rob p.s. Similarly, the DEC PDP-8 & PDP-11 were also originally booted by manually toggling the console switches in order to deposit a few instructions into memory, and then the starting address was toggled in and "Start" was pushed. It was only later that a boot ROM became available for the PDP-11 (as an expensive option!) -and only much later still for the PDP-8 series (e.g., the MI8E for the PDP-8/E). ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From paul at boddie.org.uk Thu Aug 21 08:44:58 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 21 Aug 2008 05:44:58 -0700 (PDT) Subject: Is my thinking Pythonic? References: <638bf217-3eaf-43af-8604-4145aa156afe@m73g2000hsh.googlegroups.com> Message-ID: <7d708fec-4b7d-4283-9406-8365d15af108@z66g2000hsc.googlegroups.com> On 21 Aug, 14:21, Hussein B wrote: > If you have a huge class, you can't figure the instance variables of > each object. > So, I created this constructor: > -- > def __init__(self): > ? self.speed = None > ? self.brand = None > -- > This way, I can figure the instance variables by just reading the > __init__ method. > What do you think of my approach? is it considered Pythonic? I don't like to use the term "Pythonic", but I think it's reasonable to initialise the attributes in this way. In effect, what you're doing is to ensure that the attributes have some well-defined state at each point in the lifetime of the instance, and I find myself doing this a lot. My __init__ methods typically consist of any calls to superclass __init__ methods followed by the explicit initialisation of any additional attributes defined for the instance in the class. Some people might advocate not bothering defining the attributes until they are actually set with some value, but then you have to deal with situations where the attributes are missing. Generally, handling missing attributes isn't worth the bother unless you have a large number of attributes which could only *potentially* be present: a situation which occurs when wrapping "foreign" libraries, for example, where properties or use of __getattr__ seem more essential than the luxury they might otherwise appear to be. Paul From larry.bates at websafe.com` Sat Aug 2 11:28:28 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 02 Aug 2008 10:28:28 -0500 Subject: Searching for some kind of data type In-Reply-To: <33d13c77-e710-4951-a559-7ea8b6e15287@26g2000hsk.googlegroups.com> References: <33d13c77-e710-4951-a559-7ea8b6e15287@26g2000hsk.googlegroups.com> Message-ID: Giampaolo Rodola' wrote: > Hi, > for an FTP server I wrote I'd need to group the FTP commands in one > table that defines the command itself, the syntax string, required > permission, whether it requires authorization, whether it takes > argument and whether there's a need to validate the path from the > argument. > The more obvious way I found to do that is something like this: > > class CommandProperty: > def __init__(self, perm, auth_needed, arg_needed, check_path, > syntax): > self.perm = perm > self.auth_needed = auth_needed > self.arg_needed = arg_needed > self.check_path = check_path > self.syntax = syntax > > ftp_cmds = { > "ABOR" : CommandProperty(perm=None, auth_needed=True, > arg_needed=False, check_path=False, syntax="ABOR (abort transfer)."), > "APPE" : CommandProperty(perm='a', auth_needed=True, > arg_needed=True, check_path=True, syntax="APPE file-name > (append data to an existent file)."), > "CDUP" : CommandProperty(perm='e', > auth_needed=True,arg_needed=False, check_path=False, syntax="CDUP (go > to parentdirectory)."), > ... > ... > ... > } > > ...but I find it somewhat redundant and... "ugly". > I was wondering if there was some kind of data type which could better > fit such purpose or if someone could suggest me some other approach to > do this same thing. Maybe using a dictionary is not the better choice > here. > > > Thanks in advance > > > --- Giampaolo > http://code.google.com/p/pyftpdlib/ Seems completely reasonable to me. You might just consider using keyword arguments in the __init__ method and eliminate the dictionary altogether. Not tested, but you will get the idea: class CommandProperty: def __init__(self, perm = perm, auth_needed = True, arg_needed = True, check_path = False, syntax = syntax): self.perm = perm self.auth_needed = auth_needed self.arg_needed = arg_needed self.check_path = check_path self.syntax = syntax ftpCommands = dict( ABOR = CommandProperty(perm = None, arg_needed = False, syntax="ABOR (abort transfer)."), APPE = CommandProperty(perm = 'a', check_path=True, syntax = "APPE file-name (append data to" \ "an existent file)."), CDUP = CommandProperty(perm= 'e', arg_needed = False, syntax="CDUP (go> to parentdirectory)."), ... ... ... ) IMHO this is a "little" easier to manage because you can take advantage of the default values for keyword arguments to eliminate some of the arguments. Hope this helps, Larry From hniksic at xemacs.org Tue Aug 19 09:41:37 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 19 Aug 2008 15:41:37 +0200 Subject: optparse escaping control characters References: <4001fcc2-e595-4bd6-9baf-c71db3761d36@m3g2000hsc.googlegroups.com> <877iad9nrm.fsf@mulj.homelinux.net> <6a650558-b9d4-4833-a909-147df44155f9@m45g2000hsb.googlegroups.com> Message-ID: <873al19l66.fsf@mulj.homelinux.net> Dan Halligan writes: > How would I pass a control character to python on the command line? It depends on which command line you are using. Most Unix-like shells will allow you to input a control character by preceding it with ^V. Since \t is the TAB character, you should be able to input it like this: $ python -c 'import sys; print sys.argv' '^V' ['-c', '\t'] # note single backslash From prologic at shortcircuit.net.au Thu Aug 28 21:57:02 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 29 Aug 2008 11:57:02 +1000 Subject: Fastest way to write huge files In-Reply-To: <538050a90808281735u51ce90d0o3db3945a6ed2b591@mail.gmail.com> References: <538050a90808281735u51ce90d0o3db3945a6ed2b591@mail.gmail.com> Message-ID: Hi, You could use generators connected via a pipe or tcp socket ... cheers James On Fri, Aug 29, 2008 at 10:35 AM, Mohamed Yousef wrote: > Hello , > > let's say , I'm moving large files through network between devices > what is the fastest way to do this ? > what i came up with :- > > 1) using regular file operations with an in memory limit of 4MB which > when filled written to disk and re-filled again > > 2) using memory mapped files in the following way , map first 20MB of > file and after finishing them flush and map next 20MB > ------ > which of them should be faster in writting to disk ? and less memory consuming > > or is there faster ways ? > > Thanks, > > Regards , > Mohamed Yousef > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From emanuele.nespolo at gmail.com Thu Aug 28 02:39:56 2008 From: emanuele.nespolo at gmail.com (nisp) Date: Wed, 27 Aug 2008 23:39:56 -0700 (PDT) Subject: unexpected from/import statement behaviour References: <42780654-8a54-470e-a494-ca53fd0504f5@p25g2000hsf.googlegroups.com> <7dbab131-7f7b-4266-b706-fff52670e9e1@l64g2000hse.googlegroups.com> Message-ID: <3196d355-9096-4ba1-9485-28ce03935e92@a1g2000hsb.googlegroups.com> On Aug 27, 3:35 pm, Peter Otten <__pete... at web.de> wrote: > nisp wrote: > > Thanks first of all ! I read the interesting Diez's link but something > > still remains to me unclear, on the other hand it's clear the my > > problem is concentrated there and on symbols. > > Read it again. If you have two modules > > module1.py > from sys import stderr > > module2.py > from module1 import stderr > > you get three names 'stderr' in three different namespaces, and each name > may bind a different object. > > > > > Here is what I'm trying to do > > > HelloWorld.py: this is a real simplification of my external module > > though still reflecting its structure (commented out is the version > > that, let's say, works) > > > from sys import stderr > > #import sys > > > class Cheers: > > def __init__(self): > > self.cheersMsg = 'Hello World !!' > > print "Cheers stderr %s" % stderr > > #print "Cheers stderr %s" % sys.stderr > > def _putCheers(self): > > print>>stderr, 'Here is my msg:', self.cheersMsg > > print>>stderr, 'This is a nice day today !!' > > #print>>sys.stderr, 'Here is my msg:', self.cheersMsg > > #print>>sys.stderr, 'This is a nice day today !!' > > def doSomeStuff(self): > > self._putCheers() > > > And below there is the module that uses the above one (mymodule.py): > > > #!/usr/bin/python > > > import sys > > This imports HelloWorld.stderr: > > > from HelloWorld import * > > You now have a global variable 'stderr' in module __main__, initialized to > the same value as HelloWorld.stderr. > > > class StderrCatcher: > > def __init__(self): > > self.data = '' > > def write(self,stuff): > > self.data = self.data + "\t" + stuff > > > def main(): > > > print "mymodule stderr: %s" % sys.stderr > > This rebinds sys.stderr and a local 'stderr' in main() > > > sys.stderr = stderr = StderrCatcher() > > but both HelloWorld.stderr and __main__.stderr are unaffected. What you need > is > import HelloWorld > sys.stderr = HelloWorld.stderr = StderrCatcher() > > > m = Cheers() > > m.doSomeStuff() > > print "stderr: \n%s" % sys.stderr.data > > > if __name__ == '__main__': > > main() > > > Below there is the output when it doesn't work: > > > mymodule stderr: ', mode 'w' at 0xb7d160b0> > > Cheers stderr ', mode 'w' at 0xb7d160b0> > > Here is my msg: Hello World !! > > This is a nice day today !! > > stderr: > > > And here when it works: > > > mymodule stderr: ', mode 'w' at 0xb7dc40b0> > > Cheers stderr <__main__.StderrCatcher instance at 0xb7d8bd4c> > > stderr: > > Here is my msg: Hello World !! > > This is a nice day today !! > > > Thanks again! > > > PS Sorry for having probably replied to somone of you directly :-( Hi Peter! Definitely you are right ! May be this time I understood completely the topic (or may be not ?... gosh !) ... I didn't considered well the "from HelloWolrd import *" in mymodule.py. Now my module is: import sys import HelloWorld class StderrCatcher: def __init__(self): self.data = '' def write(self,stuff): self.data = self.data + "\t" + stuff def main(): print "mymodule stderr: %s" % sys.stderr mystderr = sys.stderr = HelloWorld.stderr = StderrCatcher() m = HelloWorld.Cheers() m.doSomeStuff() print >>sys.stderr, "mymodule prints something" print "stderr: \n%s" % mystderr.data if __name__ == '__main__': main() and its output is: mymodule stderr: ', mode 'w' at 0xb7d2d0b0> Cheers stderr <__main__.StderrCatcher instance at 0xb7cf4e4c> stderr: Here is my msg: Hello World !! This is a nice day today !! mymodule prints something now it works perfectly ! Great ! Thanks to all of you ! Nisp From larry.bates at websafe.com` Mon Aug 4 16:56:15 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 04 Aug 2008 15:56:15 -0500 Subject: Trying to fix Invalid CSV File In-Reply-To: <42134ad4-ae35-4d25-94fc-2504d29003e6@r15g2000prh.googlegroups.com> References: <0427191c-d493-442d-ba26-94802bc6062b@v13g2000pro.googlegroups.com> <078f7aad-3bba-49b4-8978-18ac5bfaa6f7@r15g2000prd.googlegroups.com> <6bade254-5001-4ae2-a000-003b84437a76@w1g2000prk.googlegroups.com> <42134ad4-ae35-4d25-94fc-2504d29003e6@r15g2000prh.googlegroups.com> Message-ID: Ryan Rosario wrote: > On Aug 4, 8:30 am, Emile van Sebille wrote: >> John Machin wrote: >>> On Aug 4, 6:15 pm, Ryan Rosario wrote: >>>> On Aug 4, 1:01 am, John Machin wrote: >>>>> On Aug 4, 5:49 pm, Ryan Rosario wrote: >>>>>> Thanks Emile! Works almost perfectly, but is there some way I can >>>>>> adapt this to quote fields that contain a comma in them? >> >> >>> Emile's snippet is pushing it through the csv reading process, to >>> demonstrate that his series of replaces works (on your *sole* example, >>> at least). >> Exactly -- just print out the results of the passed argument: >> >> >>> >> rec.replace(',"',",'''").replace('",',"''',").replace('"','""').replace("'''",'"') >> >> '123,"Here is some, text ""and some quoted text"" where the quotes >> should have been doubled",321' >> >> Where it won't work is if any of the field embedded quotes are next to >> commas. >> >> I'd run it against the file. Presumably, you've got a consistent field >> count expectation per record. Any resulting record not matching is >> suspect and will identify records this approach won't address. >> >> There's probably better ways, but sometimes it's fun to create >> executable line noise. :) >> >> Emile > > Thanks for your responses. I think John may be right that I am reading > it a second time. I will take a look at the CSV reader documentation > and see if that helps. Then once I run it I can see if I need to worry > about the comma-next-to-quote issue. This is a perfect demonstration of why tab delimited files are so much better than comma and quote delimited. Virtually all software can handle table delimited as well as comma and quote delimited, but you would have none of these problems if you had used tab delimited. The chances of tabs being embedded in most data is virtually nil. -Larry From nagle at animats.com Sun Aug 17 13:15:47 2008 From: nagle at animats.com (John Nagle) Date: Sun, 17 Aug 2008 10:15:47 -0700 Subject: urllib getting SSL certificate info In-Reply-To: References: <200808160234.28304.ghirai@ghirai.com> Message-ID: <48a85819$0$17204$742ec2ed@news.sonic.net> Fredrik Lundh wrote: > Ghirai wrote: > >> Using urllib, is there any way i could access some info about the SSL >> certificate (when opening a https url)? >> >> I'm really interested in the fingerprint. >> >> I haven't been able to find anything so far. > > you can get some info via (undocumented?) attributes on the file handle: > > >>> import urllib > >>> f = urllib.urlopen("https://mail.google.com/") > >>> f.fp > > ['issuer', 'read', 'server', 'write'] > >>> f.fp._ssl.issuer() > '/C=ZA/O=Thawte Consulting (Pty) Ltd./CN=Thawte SGC CA' > >>> f.fp._ssl.server() > '/C=US/ST=California/L=Mountain View/O=Google Inc/CN=mail.google.com' > > If you really need details from the SSL cert, you usually have to use M2Crypto. The base SSL package doesn't actually do much with certificates. It doesn't validate the certificate chain. And those strings of attributes you can get are ambiguious; data fields may contain unescaped "/", which is the field separator. I went through this last year and had to use M2Crypto, which is something of a headache but more or less works. John Nagle From gordyt at gmail.com Tue Aug 26 18:12:53 2008 From: gordyt at gmail.com (gordyt) Date: Tue, 26 Aug 2008 15:12:53 -0700 (PDT) Subject: Python and database unittests References: Message-ID: <906bf68d-2727-429b-a4f5-99cdf4461d86@k13g2000hse.googlegroups.com> Daniel I don't know if it would work for your situation or not, but if you are using Python 2.5, you could use the now built-in sqlite3 module. If you didn't even want to create a temporary database file you could use the special memory-only syntax like this: >>> import sqlite3 >>> conn =sqlite3.connect(":memory:") >>> # use the connection >>> conn.close() --gordy From notvalid2 at sbcglobal.net Tue Aug 26 20:21:02 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Tue, 26 Aug 2008 17:21:02 -0700 Subject: Date Comparison and Manipulation Functions? In-Reply-To: References: Message-ID: zuul at ferg.org wrote: > check out Pyfdate: http://www.ferg.org/pyfdate > > from pyfdate import * > > t = Time().add(hours=14) > print "It is now", t.wdt > > datestring1 = "2005/10/05" #year,month,day > datestring2 = "2002/09/22" #year,month,day > datestring3 = "2007/11/11" #year,month,day > > year,month,day = numsplit(datestring1) # split into integers > t1 = Time(year,month,day) > for datestring in (datestring2,datestring1,datestring3): > year,month,day = numsplit(datestring) > t2 = Time(year,month,day) > > if t1 > t2: > print t1.isodate, "is later than ", t2.isodate > elif t1 == t2: > print t1.isodate, "is the same as ", t2.isodate > elif t1 < t2: > print t1.isodate, "is earlier than", t2.isodate > > print > > t1 = Time(2000,2,28) > print "The date after", t1.d, "is", t1.plus(day=1).d > t1 = Time(2001,2,28) > print "The date after", t1.d, "is", t1.plus(day=1).d > t1 = Time(2004,2,28) > print "The date after", t1.d, "is", t1.plus(day=1).d > > print > datestring1 = "2005/10/05 20:10:08" > datestring2 = "2005/10/05 20:10:06" > datestring3 = "2005/10/05 20:10:09" > > t1 = Time(*numsplit(datestring1)) > for datestring in (datestring2,datestring1,datestring3): > t2 = Time(*numsplit(datestring)) > > if t1 > t2: > print t1.d, t1.civiltime2, "is later than ", t2.d, t2.civiltime2 > elif t1 == t2: > print t1.d, t1.civiltime2, "is the same as ", t2.d, t2.civiltime2 > elif t1 < t2: > print t1.d, t1.civiltime2, "is earlier than", t2.d, t2.civiltime2 I'm using IDLE for Python 2.4, and put pfydate distribution in C:\Python24\Lib\site-packages\pfydate, as required by the page. How to install pyfdate. Save pyfdate.py into your PythonNN/Lib/site-packages directory. I copied it into C:\Python24\Lib\site-packages\pfydate Execution in IDLE produced: --------------------------------- Traceback (most recent call last): File "C:\Sandia_Meteors\Improved_Sentinel\Sentinel_Playground\date_example.py", line 1, in ? from pyfdate import * ImportError: No module named pyfdate --------------------------------- Looking in the Path Browser, I don't see pyfdate. I see PIL package and scipy package. Comments? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From deets at nospam.web.de Mon Aug 25 18:44:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Aug 2008 00:44:39 +0200 Subject: python - firefox dom/xpath question/issue In-Reply-To: References: Message-ID: <6hgqunFlobm0U2@mid.uni-berlin.de> bruce schrieb: > Hi. > > Got a test web page, that basically has two " the page via Firefox/Dom Inspector, I can create a test xpath query > "/html/body/form" which gets the target form for the test. > > The issue comes when I examine the page's source html. It looks like: > > > > > > > > . > . > . > > > > I've simplified things a bit... but basically, the 1st "html/body" is empty, > with the 2nd containing the data/nodes I need. If that's your document, it is invalid XML - XML only allows *one* root. Thus the parsers failure isn't too suprising. Try & wrap the whole document under an arbitrary root-tag, and included that as first part of the xpath. See if that helps. Diez From brtzsnr at gmail.com Wed Aug 13 17:29:07 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Wed, 13 Aug 2008 14:29:07 -0700 (PDT) Subject: callbacks in python References: <2b3a25c6-9985-4d05-8721-5a57a020e845@w7g2000hsa.googlegroups.com> Message-ID: <01a616b8-ae21-4dcc-a2cf-1a51af909634@m3g2000hsc.googlegroups.com> On Aug 14, 12:02?am, Fredrik Lundh wrote: > your use of the word "callback" is a bit unusual, and your example isn't > valid Python code, but it looks as if functools.partial might be what > you need: > > ? ? ?http://docs.python.org/lib/module-functools.html my current implementation is very similar to partial() :) (10x, i'll use partial from now on). however it seems that I don't understand very well positional and keyword arguments in python because I got the error described here: http://docs.python.org/ref/calls.html#calls (TypeError: f() got multiple values for keyword argument 'a') which confused me even more. so if you pass positional and keyword arguments to both partial() and function returned the order of passed arguments might be different than expected. i was looking for an implementation that somehow avoids this confusion. From rustompmody at gmail.com Sun Aug 17 12:19:21 2008 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 17 Aug 2008 21:49:21 +0530 Subject: python-mode errors Message-ID: When I start python mode I get the error: idle error: # -Wrong number of arguments : # 2" The Python mode version is 4.78 Is this a known problem? Thanks From michael at stroeder.com Thu Aug 14 14:20:22 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 14 Aug 2008 20:20:22 +0200 Subject: Fixed-length text file to database script In-Reply-To: References: Message-ID: <8k9en5-8i8.ln1@nb2.stroeder.com> Larry Bates wrote: > While you are correct, that is not what the OP asked. There is no > reference to processing data prior to insertion into MySQL database. > Also the OP said they had a 1 day deadline. Larry, having a bad day? I'm confident that the OP is able to sort out *himself* what he needs. Also the 1 day deadline would not be an obstacle. Would it for you? Ciao, Michael. From steven at REMOVE.THIS.cybersource.com.au Tue Aug 5 05:47:57 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 05 Aug 2008 09:47:57 GMT Subject: very large dictionary References: <5c5e6d6e-04ef-4340-963f-d3825875b32c@e39g2000hsf.googlegroups.com> <6fftjvFb7ktoU2@mid.uni-berlin.de> <60FCF960-D1CD-4885-9F46-B5D7B798A9FF@gmail.com> <20080803224254.GG11163@tuva.opensoft.se> <6b690d0c-d817-4582-9dd1-9309b2d5cda1@e39g2000hsf.googlegroups.com> <00a78388$0$20302$c3e8da3@news.astraweb.com> <7ef44808-5f88-4860-8f3b-dcad586f6f53@i76g2000hsf.googlegroups.com> Message-ID: On Tue, 05 Aug 2008 01:20:08 -0700, Simon Strobl wrote: >> > I thought it would be practical not to create the dictionary from a >> > text file each time I needed it. I.e. I thought loading the .pyc-file >> > should be faster. Yet, Python failed to create a .pyc-file >> >> Probably a good example of premature optimization. > > Well, as I was using Python, I did not expect to have to care about the > language's internal affairs that much. I thought I could simply do > always the same no matter how large my files get. In other words, I > thought Python was really scalable. Yeah, it really is a pain when abstractions leak. http://www.joelonsoftware.com/articles/LeakyAbstractions.html >> Out of curiosity, how >> long does it take to create it from a text file? > > I do not remember this exactly. But I think it was not much more than an > hour. Hmmm... longer than I expected. Perhaps not as premature as I thought. Have you tried the performance of the pickle and marshal modules? -- Steven From castironpi at gmail.com Thu Aug 14 23:44:32 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 14 Aug 2008 20:44:32 -0700 (PDT) Subject: negative numbers are not equal... References: <48A4932F.4010302@gmail.com> Message-ID: <2e66b313-d2b1-4ca1-804f-6af79b252739@j22g2000hsf.googlegroups.com> On Aug 14, 4:31?pm, Wojtek Walczak wrote: > On Thu, 14 Aug 2008 18:23:21 -0300, ariel ledesma wrote: > > i see now, so i guess that's also why id() returns the same address for > > them as well... > > It just have to work like this. > > a is b > > is actually equal to: > > id(a) == id(b) > > so there is no other way for id() in such case. > > Hope this helps. > > -- > Regards, > Wojtek Walczak,http://www.stud.umk.pl/~wojtekwa/ For a= 6 b= a the test a is b should clearly return true. Python distinguishes what mathematics does not, between identity and equality. Clearly 5+4 and 6+3 - evaluate- to the same, but math doesn't define whether they are the same, and in some sense the question isn't asked ordinarily, or isn't debated. I want to infer that math doesn't define the 'is' relation as Python knows it. I feel the documentation should state, 'the interpreter is free to return a -new- equivalent non-identical object in the case of immutables.' My tests: >>> a= -6 >>> a is -6 False >>> -6 is -6 True I don't know a convincing argument for the truth of Is( -6, -6 ). Perhaps you could make one, or one for the permissibility of Is( a, b ) & ~Equal( a, b )... identical non-equivalent. From ckumwaka at googlemail.com Wed Aug 13 01:59:11 2008 From: ckumwaka at googlemail.com (kumwaka) Date: Tue, 12 Aug 2008 22:59:11 -0700 (PDT) Subject: gasp Message-ID: <65dba773-6441-424e-a019-dc1e493dddb7@v57g2000hse.googlegroups.com> I am a beginner in Python. Please tell me how to go about in downloading and installing the module gasp.I am using Python 2.5.2. From lists at cheimes.de Thu Aug 14 13:42:45 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 14 Aug 2008 19:42:45 +0200 Subject: Getting stdout using ctypes. In-Reply-To: References: Message-ID: <48A46E95.6000206@cheimes.de> Grant Edwards wrote: > If he's running Unix, he needs to replace the stdout file > descriptor (fd 1), with something that's connected to the > "write" end of a pipe. Then he needs to read the other > ("read") end of the pipe in his application. > > You do that using the dup2() system call: It's dangerous to mix streams and descriptors. Traditionally freopen() is used to redirect a standard stream to a file: http://www.gnu.org/software/libc/manual/html_mono/libc.html#Standard-Streams ? Function: FILE * freopen (const char *filename, const char *opentype, FILE *stream) This function is like a combination of fclose and fopen. It first closes the stream referred to by stream, ignoring any errors that are detected in the process. (Because errors are ignored, you should not use freopen on an output stream if you have actually done any output using the stream.) Then the file named by filename is opened with mode opentype as for fopen, and associated with the same stream object stream. If the operation fails, a null pointer is returned; otherwise, freopen returns stream. freopen has traditionally been used to connect a standard stream such as stdin with a file of your own choice. This is useful in programs in which use of a standard stream for certain purposes is hard-coded. In the GNU C library, you can simply close the standard streams and open new ones with fopen. But other systems lack this ability, so using freopen is more portable. From bdesth.quelquechose at free.quelquepart.fr Thu Aug 21 16:22:58 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 21 Aug 2008 22:22:58 +0200 Subject: How to simulate packages? In-Reply-To: <7d1b00d3-8c7d-4bce-860a-2e740ca52cd8@b2g2000prf.googlegroups.com> References: <7d1b00d3-8c7d-4bce-860a-2e740ca52cd8@b2g2000prf.googlegroups.com> Message-ID: <48adced6$0$32729$426a74cc@news.free.fr> Daniel a ?crit : > Hello, > > I have a project that I've decided to split into packages in order to > organize my code better. So what I have looks something like this > > src > -module1 > -mod1_file.py > -module2 > -mod2_file.py > > Everytime I run mod2_file.py I need to import mod1_file.py. Right now > I'm using an ugly little thing to do my import (see below). Isn't > there some python mechanism to handle packages? cf Gabriel's answer wrt/ Python's packages. > import os, sys > # add packages to path then finish importing > for dir in ['module1','module2']: > # how about this ugly thing to find adjacent directories for > imports > sys.path.append('\\'.join(os.path.dirname(__file__).split('\\') > [:len(os.path.dirname(__file__).split('\\'))-1]) + "\\" + dir) > > Any and all suggestions appreciated. Thanks in advance. A suggestion: os.path is about os independance when it comes to filesystem. Please read the whole doc for this module, and learn how to avoid writing system dependant code. From davideyork at gmail.com Tue Aug 5 17:50:34 2008 From: davideyork at gmail.com (David York) Date: Tue, 5 Aug 2008 14:50:34 -0700 Subject: Finding IP address of localhost via socket API (or other API) Message-ID: <38c9cdb10808051450q3912f70evdae9fd61950e09d2@mail.gmail.com> Does anybody know how to find the real IP address (e.g.: address visible to internet) of a machine via Python? In other words I have a machine with an IP address something like 192.168.1.5, an address given to me by a router. The router's address (and thus my machine's address) to the outside world is something realistic, 123.156.123.156 or whatever. How do I get that number? I've tried socket.getaddrinfo('localhost', None) but all I get is 127.0.0.1 as expected. How do I find out my machine's IP address as visible to the outside world? Thanks a lot. David -------------- next part -------------- An HTML attachment was scrubbed... URL: From qxyuestc at yahoo.cn Sat Aug 30 05:46:52 2008 From: qxyuestc at yahoo.cn (qxyuestc at yahoo.cn) Date: Sat, 30 Aug 2008 02:46:52 -0700 (PDT) Subject: How to place menu on the bottom Message-ID: <89fab7ac-c34c-453b-9dc2-e58215e3a666@i20g2000prf.googlegroups.com> #!/usr/bin/env python import sys import os from tkinter import * def callback(self): #int this snippet, all menu entries use the same callback... print("callback") class DemoMenu(): def __init__(self): self.dataTemp = "" self.createWidgets() def createWidgets(self): # create application GUI self.rootWin = Tk() self.rootWin.minsize(width=800, height=600) self.rootWin.maxsize(width=800, height=600) self.rootWin.title = ("JoeQ Menu test...") self.mainFrame = Frame(self.rootWin) self.createMenu() def createMenu(self): # create menu menuFrame = Frame(self.rootWin) menuFrame.pack(side=BOTTOM, fill=X) menuBar = Menu(menuFrame, tearoff=1) filemenu = Menu(menuBar, tearoff=0) filemenu.add_command(label="Open...", command=callback) filemenu.add_separator() filemenu.add_command(label="Exit", command=callback) menuBar.add_cascade(label="File", menu=filemenu) self.rootWin.config(menu=menuBar) return menuBar def start(self): self.rootWin.mainloop() if __name__ == '__main__': demomenu = DemoMenu() demomenu.start() ###################################################### I want to place the menu on the bottom (menuFrame.pack(side=BOTTOM, fill=X)). But it does not work. Why? From zancudero at gmail.com Fri Aug 8 07:23:45 2008 From: zancudero at gmail.com (Alexei Zankevich) Date: Fri, 8 Aug 2008 14:23:45 +0300 Subject: regular expressions. In-Reply-To: References: <23cd7bec-264e-4a1d-a285-4683b48bf99d@a21g2000prf.googlegroups.com> Message-ID: <7df72c080808080423q18995752pb56abefd9cd8b968@mail.gmail.com> Use the print statement: import re vowel = r'[aeiou]' print re.findall(vowel, r"vowel") Alexey On Fri, Aug 8, 2008 at 2:17 PM, Atul. wrote: > > > Yes. You didn't paste the traceback into your message. > > > > >>> import re > > >>> vowel = r'[aeiou]' > > >>> re.findall(vowel, r"vowel") > > > > ['o', 'e'] > > > > It works as expected here. > > > > Peter > > When I key this input in IDLE it works but when I try to run the > module it wont work. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Wed Aug 13 17:02:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Aug 2008 23:02:35 +0200 Subject: callbacks in python In-Reply-To: <2b3a25c6-9985-4d05-8721-5a57a020e845@w7g2000hsa.googlegroups.com> References: <2b3a25c6-9985-4d05-8721-5a57a020e845@w7g2000hsa.googlegroups.com> Message-ID: Alexandru Mosoi wrote: > does anyone know a nice implementation of callbacks in python? i have > issues mixing named & unamed parameters. i want build a callback over > a function such that some parameters are passed when callback is > created and the rest are passed when the function is called. > > example: > callback = Callback(function, x=1, y) > callback(z, t=4, u) your use of the word "callback" is a bit unusual, and your example isn't valid Python code, but it looks as if functools.partial might be what you need: http://docs.python.org/lib/module-functools.html From davidreynon at gmail.com Thu Aug 14 11:55:04 2008 From: davidreynon at gmail.com (korean_dave) Date: Thu, 14 Aug 2008 08:55:04 -0700 (PDT) Subject: for y in range (0,iNumItems)--> not in order? References: <8514d915-95bf-4e57-a16a-68866e0ad789@l42g2000hsc.googlegroups.com> Message-ID: hahah true. Sorry folks. I am running a third party scripting machine that uses python. It's the third-party program that is at fault. More detail involved that you don't need to know, but it's not python's "fault". Sorry for the inconvenience. On Aug 14, 11:47?am, Fredrik Lundh wrote: > korean_dave wrote: > > Still the same output... > > > Here's the actual code... > > > ? ? for x in range(0,2): > > ? ? ? ? for y in range(0,27): > > ? ? ? ? ? ? for z in range(0,15): > > ? ? ? ? ? ? ? ? print(str(x) + " " + str(y) + " " + str(z)) > > umm. ?that's even less related to your original output than your earlier > code sample. > > $ python actual_code.py > 0 0 0 > 0 0 1 > 0 0 2 > 0 0 3 > 0 0 4 > ... > 1 26 10 > 1 26 11 > 1 26 12 > 1 26 13 > 1 26 14 > > please do a little more debugging on your own machine before claiming > that fundamental python features that's been around for ages suddenly > won't work. > > From akonsu at gmail.com Sat Aug 16 18:46:23 2008 From: akonsu at gmail.com (akonsu) Date: Sat, 16 Aug 2008 15:46:23 -0700 (PDT) Subject: how to add property "dynamically"? Message-ID: hello, i need to add properties to instances dynamically during run time. this is because their names are determined by the database contents. so far i found a way to add methods on demand: class A(object) : def __getattr__(self, name) : if name == 'test' : def f() : return 'test' setattr(self, name, f) return f else : raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name)) this seems to work and i can invoke method test() on an object. it would be nice to have it as property though. so i tried: class A(object) : def __getattr__(self, name) : if name == 'test' : def f() : return 'test' setattr(self, name, property(f)) return f else : raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name)) but this does not work, instance.test returns a callable but does not call it. i am not an expert in python, would someone please tell me what i am doing wrong? thanks konstantin From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 21 11:14:12 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 21 Aug 2008 17:14:12 +0200 Subject: getattr() on nested functions? In-Reply-To: References: <48abe483$0$31875$426a74cc@news.free.fr> <48AC322E.9000404@arimaz.com> <48ad5980$0$4634$426a74cc@news.free.fr> Message-ID: <48ad8631$0$3819$426a74cc@news.free.fr> Gabriel Rossetti a ?crit : > Bruno Desthuilliers wrote: >> Gabriel Rossetti a ?crit : >>> Terry Reedy wrote: >> (snip) >>>> Unlike the class approach, this requires recreating the constant >>>> functions and dict with each call to _test. Quick to write but a >>>> bit 'dirty', in my opinion. Another standard idiom is to set up the >>>> constants outside the function: >>>> >>>> def request(params): >>>> pass >>>> def submit(params, values): >>>> pass >>>> def update(params, values): >>>> pass >>>> def delete(params): >>>> pass >>>> dispatch = {'request':request, 'submit':submit, 'update':update, >>>> 'delete':delete} >>>> >>>> def _test(self, action, *args): >>>> return resultToXmo(dispatch[action](*args)) >>> >>> That's how I had done it originally (before the use of eval()), but >>> in this case also, since the functions are still nested, >> >> Uh ??? You probably want to re-read the above code snippet. >> > Uh...yes, I didn't see the external/parent function was no longer there. > I prefer to nest mine though because I have several parent functions for > different tasks, so each child/nested function has a diff. > implementation, I find that cleaner than having n*4+n top-level > functions (+ n dicts), e.g. I prefer this : > > def __task1(self, action, *args): > def request(params): > pass > def submit(params, values): > pass > def update(params, values): > pass > def delete(params): > pass > return resultToXml(locals()[action](*args)) > > def __task2(self, action, *args): > def request(params): > pass > def submit(params, values): > pass > def update(params, values): > pass > def delete(params): > pass > return resultToXml(locals()[action](*args)) > > > over this : > (snip) > > > I could use your callable approach, but like you said it may not be > worth the trouble. The "trouble" I was talking about was not with using callable objects, but with trying to hack func.func_code to extract nested functions (if ever possible). But anyway... The point of using callable objects is to avoid going thru the whole "setup" part again and again and again. Now if all your task functions only differ by the dispatch dict, there's at least another ways to avoid this runtime repetition - as well as coding repetition FWIW (warning : untested code): def _make_task(func): dispatch = func() def _task(action, *args): return resultToXml(dispatch[action](*args)) _task.__name__ = _task.func_name = func.__name__ return _task @_make_task def _task1(): def request(params): pass def submit(params, values): pass def update(params, values): pass def delete(params): pass return locals() HTH From deets at nospam.web.de Sat Aug 2 11:26:36 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 02 Aug 2008 17:26:36 +0200 Subject: applescript/python question In-Reply-To: References: Message-ID: <6fjclcFc0dh8U1@mid.uni-berlin.de> jyoung79 at kc.rr.com schrieb: > I can't seem to figure this out. I just installed Python 2.5.2 a few days ago on my OS X 10.4.11 > system. It runs fine and if I type "Python -V" in the Terminal it outputs "Python 2.5.2" which is > correct. However, if I try to run a 'do shell script' in AppleScript which I'm wanting to run a Python > program, it reverts to using Python 2.3. For example, if I run this code in AppleScript: > > -------------------- > set p to "#!/usr/bin/python > import sys > print sys.version[:3]" > set x to do shell script "Python -c \"" & p & "\"" > return x > -------------------- > > I get "2.3". Does anyone have any ideas why AppleScript is using the older version of Python? > Is there a way to fix this? I guess the shebang is simply ignored - the actual interpreter is fetched from the "Python -c"-line. It's a bit weird that there is Python with a capital P, but what happens if you change that to Python2.5 for example? Diez From boblatest at googlemail.com Wed Aug 27 07:15:48 2008 From: boblatest at googlemail.com (boblatest at googlemail.com) Date: Wed, 27 Aug 2008 04:15:48 -0700 (PDT) Subject: How can this script fail? References: <4129c566-de92-433e-bc3f-f1dcbc255c46@m3g2000hsc.googlegroups.com> Message-ID: <48b2013f-0103-4f00-8597-b1ccad2425cf@k13g2000hse.googlegroups.com> On Aug 27, 1:08?pm, "M.-A. Lemburg" wrote: > I don't think this is related to IDLE or your setup. The odbc > module is very old and unmaintained, so it's possible that Windows > doesn't find some system DLLs needed for it to work. Please note that 1) I can type "import odbc" directly into the IDLE shell without getting an error message, but only BEFORE I've run a script that tries to import odbc. 2) The same script runs fine under PyWin (which I don't like much as an environment). > If you're looking for a reliable Python ODBC interface, I'd suggest > you have a look at our mxODBC: Thanks, but I'm working on some kind of guerilla project of which my employer doesn't know, so they won't spend any money on a commercial product. robert From krishnan.sid at gmail.com Wed Aug 6 18:59:54 2008 From: krishnan.sid at gmail.com (Sid K) Date: Wed, 6 Aug 2008 15:59:54 -0700 (PDT) Subject: Adding Microsoft objects in Boa Constuctor Palette Message-ID: <26b16796-f717-40bb-b6e9-a918598b44e2@d77g2000hsb.googlegroups.com> This is what I wanted to do: Add Microsoft Active objects like Excel sheets and Word files to the Palette in Boa Constructor. There is a User tab in the GUI builder menu, but I'm not sure how to use/enable it. 1. Does anyone know how to do this? 2. Is anyone aware of any work that is currently going on to support adding Microsoft objects in Boa. 3. Does any other Python GUI creator/editor exist out there that can do this? 4. How would one add an excel sheet to a wx.Panel in general w/ or w/o Boa? Looking forward to replies... -SK From poojaangali at gmail.com Fri Aug 15 05:59:18 2008 From: poojaangali at gmail.com (pooja) Date: Fri, 15 Aug 2008 02:59:18 -0700 (PDT) Subject: EARN MONEY $1500-$5000 PER MONTH Message-ID: EARN MONEY $1500-$5000 PER MONTH SIMPLE ONLINE SURVEY CREATE UR ACCOUNT AND EARN IMMEDIATLY ************************************************************************* http://www.AWSurveys.com/HomeMain.cfm?RefID=kingraja666 ************************************************************************* From Edwin.Madari at VerizonWireless.com Mon Aug 11 08:23:05 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Mon, 11 Aug 2008 08:23:05 -0400 Subject: for x,y in word1, word2 ? In-Reply-To: Message-ID: <20080811122317.8A46A1E4005@bag.python.org> sounds like *soundex* is what you are looking for. google soundex regards Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of Marc 'BlackJack' Rintsch Sent: Monday, August 11, 2008 3:09 AM To: python-list at python.org Subject: Re: for x,y in word1, word2 ? On Sun, 10 Aug 2008 23:14:50 -0700, ssecorp wrote: > I know zip but lets say I have a word "painter" and I want to compare it > to a customer's spelling, he might have written "paintor" and I want to > check how many letters are the same. > > Now I know how I could do this, it is not hard. I am just wondering if > these is any specific simple syntax for it. No special syntax for that, but you can combine the `sum()` function, a generator expression and `zip()`: In [40]: sum(int(a == b) for a, b in zip('painter', 'paintor')) Out[40]: 6 Or this way if you think it's more clear: In [41]: sum(1 for a, b in zip('painter', 'paintor') if a == b) Out[41]: 6 Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From dudeja.rajat at gmail.com Fri Aug 29 05:37:33 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Fri, 29 Aug 2008 10:37:33 +0100 Subject: problem with execv command Message-ID: Hi, I'm facing problem with the execv command: my command is : os.execv(' C:\Program Files\Subversion\bin\svn ', ( 'list', ' \" http://subversion.stv.abc.com/svn/Eng \" ' ) ) The error I'm getting is : OSError: [Errno 22] Invalid argument I tried using a variable for http path but still I'm getting the same error Please help. -- Regards, Rajat From rafesacks at gmail.com Fri Aug 15 11:16:38 2008 From: rafesacks at gmail.com (Rafe) Date: Fri, 15 Aug 2008 08:16:38 -0700 (PDT) Subject: Parsing and Editing Source References: Message-ID: On Aug 15, 9:21 pm, "Paul Wilson" wrote: > Hi all, > > I'd like to be able to do the following to a python source file > programmatically: > * Read in a source file > * Add/Remove/Edit Classes, methods, functions > * Add/Remove/Edit Decorators > * List the Classes > * List the imported modules > * List the functions > * List methods of classes > > And then save out the result back to the original file (or elsewhere). > > I've begun by using the tokenize module to generate a token-tuple list > and am building datastructures around it that enable the above > methods. I'm find that I'm getting a little caught up in the details > and thought I'd step back and ask if there's a more elegant way to > approach this, or if anyone knows a library that could assist. > > So far, I've got code that generates a line number to token-tuple list > dictionary, and am working on a datastructure describing where the > classes begin and end, indexed by their name, such that they can be > later modified. > > Any thoughts? > Thanks, > Paul I can't help much...yet, but I am also heavily interested in this as I will be approaching a project which will require me to write code which writes code back to a file or new file after being manipulated. I had planned on using the inspect module's getsource(), getmodule() and getmembers() methods rather than doing any sort of file reading. Have you tried any of these yet? Have you found any insurmountable limitations? It looks like everything needed is there. Some quick thoughts regarding inspect.getmembers(module) results... * Module objects can be written based on their attribute name and __name__ values. If they are the same, then just write "import %s" % mod.__name__. If they are different, write "import %s as %s" % (name, mod.__name__) * Skipping built in stuff is easy and everything else is either an attribute name,value pair or an object of type 'function' or 'class'. Both of which work with inspect.getsource() I believe. * If the module used any from-import-* lines, it doesn't look like there is any difference between items defined in the module and those imported in to the modules name space. writing this back directly would 'flatten' this call to individual module imports and local module attributes. Maybe reading the file just to test for this would be the answer. You could then import the module and subtract items which haven't changed. This is easy for attributes but harder for functions and classes...right? Beyond this initial bit of code, I'm hoping to be able to write new code where I only want the new object to have attributes which were changed. So if I have an instance of a Person object who's name has been changed from it's default, I only want a new class which inherits the Person class and has an attribute 'name' with the new value. Basically using python as a text-based storage format instead of something like XML. Thoughts on this would be great for me if it doesn't hijack the thread ;) I know there a quite a few who have done this already. Cheers, - Rafe From http Fri Aug 29 21:43:29 2008 From: http (Paul Rubin) Date: 29 Aug 2008 18:43:29 -0700 Subject: posix semaphore support? References: Message-ID: <7x3aknjn0e.fsf@ruckus.brouhaha.com> Neal Becker writes: > Does that provide semaphores between unrelated processes? The threading module is just for threads of a single process. There's an shm module that implements semaphores: http://nikitathespider.com/python/shm/ From harrrrpo at gmail.com Sat Aug 23 18:29:09 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Sun, 24 Aug 2008 01:29:09 +0300 Subject: Imports awareness in Imported modules problem Message-ID: <538050a90808231529s61855330r1ec68048847ef241@mail.gmail.com> Hello , The problem I'm asking about is how can imported modules be aware of other imported modules so they don't have to re-import them (avoiding importing problems and Consicing code and imports ) Take Example :- in A.py :- import B print dir() # no problems we can see B which contain re module and C module B.C.W() # our problem here we get an empty list in B.py :- import re import C in C.py :- def W(): print dir()# when called from A we get [] though other imports has been made to re and others my goal is basically making W() aware of the re module when called from A ---- why am i doing this in the first place I'm in the process of a medium project where imports of modules start to make a jungle and i wanted all needed imports to be in a single file (namely __init__.py) and then all imports are made once and other modules feel it another reason to do this that my project is offering 2 interfaces (Console and GUI through Qt) and i needed a general state class ( whether i'm in Console or GUI mode) to be available for all , for determining state and some public functions ,and just injecting Imports everywhere seems a bad technique in many ways (debugging , modifying ...etc ) in PHP "Require" would do the trick neatly ... so is there is something I'm missing here or the whole technique is bad in which case what do you suggest Thanks, Regards, Mohamed Yousef From tkpmep at gmail.com Sat Aug 2 22:41:03 2008 From: tkpmep at gmail.com (Thomas Philips) Date: Sat, 2 Aug 2008 19:41:03 -0700 (PDT) Subject: Teething troubles with Python on a Mac Message-ID: <6651edd6-d47f-4e10-bf0b-0875190b9bc2@a1g2000hsb.googlegroups.com> I've got a new iMac, have installed Python 2.5.2 on it, and am now trying to run my existing Python programs on it (these are typically number crunching programs that I run from IDLE). Some things work, while others don't, and as this is my first time grappling with Unix and MacOS X, I appreciate some guidance on how to get up and running. Here are details of my setup interspersed with my woes and my questions. Your assistance is greatly appreciated. Item 1. I downloaded and installed 2.5.2 from python.org. Runs fine, it installed a MacPython directory under applications, which has a few icons, including IDLE. However, I have absolutely NO idea where all the Python files are kept. Question 1: How can I locate the Python installation? There a few files under Applications > MacPython 2.5, but this is clearly not the entire installation. Question 2: In Finder, If I click on Search For > Past week, I can see a sequence of folders under the horizontal scroll bar at the bottom of the window, allowing me to determine that some files that were placed under Applications > MacPython 2.5> Extra> Demo. But I do not seem to be able to see the sequence of folders under the horizontal scroll bar in any finder window. What do I need to do to make the folder sequence visible in all Finder Windows? Item 2. I downloaded and installed the SciPy superpack from Macinscience,org. Scipy seems to import correctly into the Python 2.5.1 that comes with the Mac, but i cannot import it into MacPython 2.5.2. Question 3. What do I have to do in order to make SciPy work with both Python 2.5.1 (that comes with the Mac) and 2.5.2 (that I installed myself)? Item 3. I accidentally clicked on something (not sure what) and suddenly found the path to the numpy folder was Macintosh HD > Developer > SDKs > MacOSX10.5.sdk>System> Library>Frameworks>Python.framework>Versions>2.5>extras>lib>Python>numpy. This is insane!!! Where would the superpack have installed SciPy, and how can I find it? Question 4. How do I get MacPython 2.5.2 to see SciPy, NumPy etc. Question 5. How can I find the current value of the PYTHONPATH environment variable, and how can I edit it and add a directory in which I keep my Python programs. Question 6. Apparently there's a Property List Editor that must be used to create a file called ~ /.MacOSX/environment.plist. I can't find a directory called ~/.MacOSX. Is this a hidden directory? Item 4. I opened a terminal window, and typed ipython. Here's what I got: Welcome to IPython. I will try to create a personal configuration directory where you can customize many aspects of IPython's functionality in: /Users/tom/.ipython WARNING: Installation error. IPython's directory was not found. Check the following: The ipython/IPython directory should be in a directory belonging to your PYTHONPATH environment variable (that is, it should be in a directory belonging to sys.path). You can copy it explicitly there or just link to it. IPython will create a minimal default configuration for you. Ipython actually runs once I hit enter, but I do not seem to be able to import and run my programs. Question 7. What is this cryptic message all about? I'm completely confused. I never thought I'd say this, but it actually seemed a lot easier to get Python and any associated programs up and running on Windows! I suspect that a large fraction of my troubles are due to the fact that I am brand new to the Mac and to Unix, but I bought the Mac in part because I thought that using it was effortless. Thank you in advance for your help. Sincerely Thomas Philips From JohnBMudd at gmail.com Mon Aug 25 14:50:07 2008 From: JohnBMudd at gmail.com (JohnMudd) Date: Mon, 25 Aug 2008 11:50:07 -0700 (PDT) Subject: os.popen() interferes with os.fork()? Message-ID: On Linux I get a "close failed: [Errno 10] No child processes" msg for each fork. But only if I have a pipe open. I don't understand the connection between the popen and the forks. Am I doing something wrong? #! /usr/bin/env python import os import sys import time p = os.popen('top -b -d1') n = 3 t1 = time.time() for i in range(n): pid = os.fork() if pid == 0: sys.exit(0) delay = time.time() - t1 print 'rate: %.1f fork/sec' % (n/delay) From kay.schluehr at gmx.net Wed Aug 13 02:31:38 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 12 Aug 2008 23:31:38 -0700 (PDT) Subject: Python as a Testing Language - TTCN-3 Comparison References: <001701c8fc84$451cd820$0b02a8c0@afelty> Message-ID: <032c4153-c979-4788-8b6b-bc46a5550fe5@c58g2000hsc.googlegroups.com> Bernard Stepien wrote: > 1. TTCN-3 is an international standard that comes among other > things with very precise semantics, thus everyone in the world using it > will talk exactly the same language. This also reduces considerably the > amount of documentation you need for the next of kin after the developer > that has developed a test suites or tool moves on. That's what industry standards are for. If you choose Python you want to get work done fast and in a somewhat playful way and that's *not* the goal of development departments of big corps. Departments want to receive money for maintaining projects ad infinitum. Providing tools that make one-third of the staff obsolete might be welcomed by higher management and controllers but definitely not by lower management and engineers i.e. by your boss and your coworkers. Development process and tool standards like TTCN-3 are sent from heaven for department leaders because they can pretend to manage test development like a factory with replaceable test workers. This indeed increases efficiency on average, lowers dependencies on creativity of individual coders and makes their job a bit safer. I've actually nothing to criticize about them because their behavior is entirely rational and if I was in their position I'd fill the role with a bit of cynicism and responsibility for the working class who want to have a well paid job no matter what they do. Python is almost always never a good choice because for this because it is too easy for a coder to gain power over his own work [1]. Known exceptions: Python is good for small companies who can be aggressive and have not much to lose but also for small development departments in big corps with not much workforce. If there is pressure for innovation Python is o.k. as well. But then no one gives a shit on TTCN-3 and could care less about being compliant with it. Python has something in common with TTCN-3 according to your description: it is a language every programmer can learn and understand within a short period of time. But unlike TTCN-3 it is even useful. [1] Since we talk about testing in the Telco industry. I've done this a lot in the past and have written test frameworks in Python myself. They are very specific but there is one thing I'd like to advertise, namely the use of the right fundamental data structure for representing, parsing, and altering binary data for the tester: http://www.fiber-space.de/EasyExtend/doc/p4d/bytelets.html Here is some more context: http://pypi.python.org/pypi/P4D From __peter__ at web.de Fri Aug 22 11:55:13 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 22 Aug 2008 17:55:13 +0200 Subject: Should Python raise a warning for mutable default arguments? References: <00becb2d$0$20312$c3e8da3@news.astraweb.com> Message-ID: bearophileHUGS at lycos.com wrote: > DrScheme is an implementation of Scheme that is very newbie-friendly. > It has several limited sub-languages, etc. > > So maybe a command line option can be added to Python3 ( - > newbie ? :-) ) that just switches on similar warnings, to help newbies > (in schools, where there's a teacher that encourages to always use > that command line option) avoid some of the most common traps. Or maybe bundle pychecker with idle? $ cat tmp.py def test(x, a=[]): a.append(x) return a for i in range(5): print test(i) $ pychecker tmp.py Processing tmp... [0] [0, 1] [0, 1, 2] [0, 1, 2, 3] [0, 1, 2, 3, 4] Warnings... tmp.py:2: Modifying parameter (a) with a default value may have unexpected consequences Though it might be interesting to ask a newbie what he expects when warned of "unexpected consequences" ;) Peter From tjreedy at udel.edu Fri Aug 22 03:36:35 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 22 Aug 2008 03:36:35 -0400 Subject: Sorted Returns List and Reversed Returns Iterator In-Reply-To: References: <7f5690e0-0dcc-4d82-a177-6fdbcfa3f8e7@l33g2000pri.googlegroups.com> <48c54158-494f-4e0d-bcbd-b7dc05a90001@v39g2000pro.googlegroups.com> <490d4841-5595-4132-b01c-15f1d77a4414@a8g2000prf.googlegroups.com> <691c3dc2-44ae-43c6-ad4f-3f5e136f5ed1@a1g2000hsb.googlegroups.com> Message-ID: Peter Otten wrote: > ++imanshu wrote: >> I agree. Iterator is more flexible. I disagree. Neither is more flexible. You can iter the list returned by sorted and list the iter returned by reversed. Both do the minimum work necessary. See below. > Together and both might have returned the same types. True, but only by doing potentially unnecessary work and requiring the caller to do potentially unnecessary work that might even prevent the program from working. This is less flexible. Suppose sorted now returns alist with 50 million items. Suppose it instead returned iter(alist) but the caller wants to randomly index the items. Since the caller could not access the existing 50 million item list, the caller would have to make another 50 million item copy. This is non-trivial and might not even work do to memory limitations. > It's easy to generate a reversed sequence on the fly but impractical for a > sorted one. Python is taking the pragmatic approach here. To expand on this: sorting and reversing are algorithmically different operations. Sorting requires that one have all items in hand in a mutable sequence (list) for arbitrary re-ordering. Sorted works on any iterable and starts by making a new list. There is no point to not returning that list after it is sorted. It would be more work and less useful to do more. sorted(iterable, key=None, reverse=False): newlist = list(iterable) newlist.sort(key, reverse) return newlist Iterating over a concrete sequence in reverse order, on the other hand, is trivial. It would be more work and less useful to do more. def _reversed(seq): # 'hidden' generator function n = len(seq) while n: n -= 1 yield seq[n] def reversed(seq): if hasattr(seq, '__reversed__'): return seq.__reversed__() # I presume this is tried first else: return _reversed(seq) # generic fall-back Terry Jan Reedy From rhamph at gmail.com Mon Aug 4 17:04:52 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 4 Aug 2008 14:04:52 -0700 (PDT) Subject: Using two pythons in an application References: Message-ID: <3ca4d946-e2b0-4c2b-ac71-f760f9caaeb5@a21g2000prf.googlegroups.com> On Aug 3, 5:43?pm, Allen wrote: > Larry Bates wrote: > > Allen wrote: > >> I'm in the process of developing an application that will use Python > >> for a scripting support. ?In light of the upcoming changes to Python, > >> I was wondering if it is possible to link to and use two different > >> versions of ?Python so that in the future, scripts could be migrated > >> to the new version, and older scripts would still work as well. ?If so > >> are there any code examples of this. > > >> Brian Vanderburg II > > > Unlike languages you pay for, Python has on real motivation to > > "obsolete" old versions of Python (e.g. to force you to pay of an > > upgrade). ?You can still get version 1.5.2 of Python and it is MANY > > years old and most could consider quite obsolete. ?I just would not > > worry about it and stick with 2.5/2.6 for development and begin looking > > at Python 3.0 so I can learn what's new and exciting. > > > -Larry > > I agree. ?I had wanted for scripts of the program to be able to use the > new string format method that is only in py3k, but I'm currently looking > into other template solutions. That should work in 2.6 (sans bugs). To answer your original question, no, you can't load more than one version of python within a single process. The best you can do is running in a child process. From wuwei23 at gmail.com Tue Aug 12 09:49:04 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 12 Aug 2008 06:49:04 -0700 (PDT) Subject: Suggestion for converting PDF files to HTML/txt files References: Message-ID: <36e5683f-c46a-4bed-bd4c-269ba9e6ca86@q5g2000prf.googlegroups.com> On Aug 12, 11:13?pm, brad wrote: > Very neat program. Would be cool if it could easily integrate into other > py apps instead of being a standalone CLI tool. Perhaps, but I think you could get a long way using os.system(). From kyosohma at gmail.com Wed Aug 6 15:56:53 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 6 Aug 2008 12:56:53 -0700 (PDT) Subject: Run program from within Python References: <47eee9f1-c85d-4816-a204-8a11f178267d@d1g2000hsg.googlegroups.com> Message-ID: On Aug 6, 2:42?pm, frankrentef wrote: > Greetings all... > > Newbie to Python... need help with opening a file from within > Python... see the following code. > > import popen2 > stdout, stdin = popen2.popen2('c:\test\OpenProgram.exe 1 1') > keygen = stdout.read() > print "The keygen value is: %s" % keygen > > from the command line if I execute "OpenProgram.exe 1 1" a number is > returned. ?("1 1" are required to return the value needed.) Ultimately > I want to take that number and apply it to another script, but the > program is not running. > > Suggestions? > > NEWBIE to Python.. If you're using Python 2.4+, popen2 is deprecated. I recommend reading up on the subprocess module instead. Here's a couple links: http://blog.doughellmann.com/2007/07/pymotw-subprocess.html http://docs.python.org/lib/module-subprocess.html The first one also explains how to communicate with a process you opened. Mike From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 26 04:56:03 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 26 Aug 2008 10:56:03 +0200 Subject: What is class method? In-Reply-To: <31c553dc-b1f3-4a8c-b70e-024c751fd352@p10g2000prf.googlegroups.com> References: <31c553dc-b1f3-4a8c-b70e-024c751fd352@p10g2000prf.googlegroups.com> Message-ID: <48b3c4f3$0$30971$426a74cc@news.free.fr> MeTheGameMakingGuy a ?crit : > On Aug 24, 6:32 pm, Hussein B wrote: >> Hi, >> I'm familiar with static method concept, but what is the class method? >> how it does differ from static method? when to use it? >> -- >> class M: >> def method(cls, x): >> pass >> >> method = classmethod(method) >> -- >> Thank you for your time. > > Firstly, don't use method = classmethod(method). Decorators are far > better. The following code has the same effect: > > class M: > @classmethod > def method(cls, x): > pass > > Far more readable, right? Yes, but will only work with Python >= 2.4. There are cases where you want to keep compatibility with Python 2.3... > Class methods are useful if you've got lots of inheritance happening. > The first argument passed in is the class calling the method. Handy > for a mix-in: it can add methods affecting the actual class it's mixed > into, rather than messing with the mix-in itself. I'm not sure I get your point here. As far as I'm concerned, classmethods are useful anywhere you need to work on the class object itself. From Matt.Fielding at rockstarnewengland.com Tue Aug 12 11:49:49 2008 From: Matt.Fielding at rockstarnewengland.com (Matt Fielding (R* New England)) Date: Tue, 12 Aug 2008 11:49:49 -0400 Subject: Unable to lookup keys in dictionary In-Reply-To: Message-ID: I actually figured out the solution to my problem, of all times, right after I finished sending this mail. It seems P4Python returns a command as a dictionary, also inside of an array. The solution is in the following code: from P4 import P4, P4Exception p4 = P4() p4.port = "rsgnwep4s1:1666" p4.user = "mfielding" try: p4.connect() info = p4.run("info") info = info[0] print info s = info['serverVersion'] print s p4.disconnect() except P4Exception: for e in p4.errors: print e Matt Fielding IT Technician Rockstar New England ________________________________ From: python-list-bounces+matt.fielding=rockstarnewengland.com at python.org [mailto:python-list-bounces+matt.fielding=rockstarnewengland.com at python. org] On Behalf Of Matt Fielding (R* New England) Sent: Tuesday, August 12, 2008 11:27 AM To: python-list at python.org Subject: Unable to lookup keys in dictionary I am trying to run p4python API on top of python 2.5.2 and am extracting a dictionary from perforce. The following code returns the output that follows it: from P4 import P4, P4Exception p4 = P4() p4.port = "erased" #deleted p4.user = "erased" #deleted try: p4.connect() info = p4.run("info") print info p4.disconnect() except P4Exception: for e in p4.errors: print e Output: [{'userName': 'mfielding', 'clientRoot': 'c:\\perforce', 'monitor': 'enabled', 'serverRoot': 'H:\\p4root\\', 'serverVersion': 'P4D/NTX64/2007.3/143793 (2008/01/ 21)', 'serverDate': '2008/08/12 11:18:56 -0400 Eastern Daylight Time', 'clientAd dress': '10.24.20.97:1918', 'serverLicense': 'Mad Doc Software, Inc. 140 users ( support expired 2008/05/31) ', 'serverAddress': 'rsgnwep4s1.rockstar.t2.corp:166 6', 'clientHost': 'nwew-mfielding', 'security': 'enabled', 'password': 'enabled' , 'clientName': 'mfielding'}] I did this to test that I was receiving a dictionary back from the server, which I clearly am. I then followed by adding the following lines to the code: print info s = info[serverVersion] print s p4.disconnect() I would expect this to print out P4D/NTX64/2007.3/143793 (2008/01/23), but instead it spits out the following error: Traceback (most recent call last): File "test.py", line 10, in s = info[serverVersion] NameError: name 'serverVersion' is not defined Changing "s = info[serverVersion]" to "s = info['serverVersion']" only gives me another error, which is: Traceback (most recent call last): File "test.py", line 10, in s = info['serverVersion'] TypeError: list indices must be integers If anyone has any idea what is going on here, I would appreciate the help. I've spent a few hours over the past two days trying to figure this little quirk out, but to no avail. Matt Fielding IT Technician Rockstar New England -------------- next part -------------- An HTML attachment was scrubbed... URL: From arunasunil at gmail.com Wed Aug 13 21:24:01 2008 From: arunasunil at gmail.com (arunasunil at gmail.com) Date: Wed, 13 Aug 2008 18:24:01 -0700 (PDT) Subject: Python packages on the Mac References: <0a7f3c13-d901-4c6b-8d31-554daf0aa4a7@p10g2000prf.googlegroups.com> <65cd8d6d-c8b3-4460-a7f9-900cdf14a215@a70g2000hsh.googlegroups.com> Message-ID: On Aug 5, 5:33?am, Jeff wrote: > On Aug 4, 11:20?pm, arunasu... at gmail.com wrote: > > > Hi, > > > I would like to copy the contents of the PythonFramework.pkg folder > > and run python without having to run the installer on the Mac. On > > windows it's simple to copy the contents of the python folder and the > > python dll's. How can this be done on the Mac? > > > Thanks > > Sunil > > Are you trying to make a script for easy distribution without having > to first install Python? ?Look here:http://undefined.org/python/py2app.html This is cool. Will this work with Python 2.5.2? Sunil From sibteym at infotechsw.com Wed Aug 27 03:30:36 2008 From: sibteym at infotechsw.com (Sibtey Mehdi) Date: Wed, 27 Aug 2008 13:00:36 +0530 Subject: Memory Error Message-ID: <044701c90816$cc73be90$5fc513ac@pwit.com> I am using the cPickle module to serialization and de-serialization of heavy python object (80 MB). When I try to save the object it gives the memory Error. Any one can help me out of this problem. I am pickling the object as: def savePklFile(pickleFile, data): pickledFile = open(pickleFile, 'wb') cPickle.dump(data, pickledFile, -1) pickledFile.close() my system has 2 GB of RAM. Thanks, Sibtey -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sat Aug 9 17:49:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 09 Aug 2008 17:49:09 -0400 Subject: Ascii to binary conversion In-Reply-To: References: Message-ID: azrael wrote: > Any idea how to easily write a function that recieves a character or > string and returns a binary number like: > ascii("1") is converted to bin("00110001") Other alternatives in 2.6 (I believe) and 3.0: >>> 0b00111010101 469 >>> b='111010101' >>> eval('0b'+b) 469 >>> '{0:b}'.format(469) '111010101' From ken at seehart.com Mon Aug 25 19:37:29 2008 From: ken at seehart.com (Ken Seehart) Date: Mon, 25 Aug 2008 16:37:29 -0700 Subject: SocketServer and long-polling connections Message-ID: <48B34239.1040408@seehart.com> I apologize if this message is a repeat. It looks like didn't get received. I'm using SocketServer to implement a local server that serves comet long-polling connections. How do I increase the maximum number of open connections? Currently it is limited to about 8 I think. More than that and it seems to block on opening more connections until one of the other connections releases. Is it possible that the limit may actually be imposed by the client in some bizarre way? In this case all of the clients are local, and are multiple instances of the same mozilla activex DLL. - Ken From vel.accel at gmail.com Thu Aug 28 01:30:31 2008 From: vel.accel at gmail.com (dieter) Date: Wed, 27 Aug 2008 22:30:31 -0700 (PDT) Subject: Process "Killed" Message-ID: <48a554c6-eeb3-4605-bdf2-a4b7de17bca3@b1g2000hsg.googlegroups.com> Hi, Overview ======= I'm doing some simple file manipulation work and the process gets "Killed" everytime I run it. No traceback, no segfault... just the word "Killed" in the bash shell and the process ends. The first few batch runs would only succeed with one or two files being processed (out of 60) before the process was "Killed". Now it makes no successful progress at all. Just a little processing then "Killed". Question ======= Any Ideas? Is there a buffer limitation? Do you think it could be the filesystem? Any suggestions appreciated.... Thanks. The code I'm running: ================== from glob import glob def manipFiles(): filePathList = glob('/data/ascii/*.dat') for filePath in filePathList: f = open(filePath, 'r') lines = f.readlines()[2:] f.close() f = open(filePath, 'w') f.writelines(lines) f.close() print file Sample lines in File: ================ # time, ap, bp, as, bs, price, vol, size, seq, isUpLast, isUpVol, isCancel 1062993789 0 0 0 0 1022.75 1 1 0 1 0 0 1073883668 1120 1119.75 28 33 0 0 0 0 0 0 0 Other Info ======== - The file sizes range from 76 Kb to 146 Mb - I'm running on a Gentoo Linux OS - The filesystem is partitioned and using: XFS for the data repository, Reiser3 for all else. From fredrik at pythonware.com Tue Aug 19 07:20:00 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Aug 2008 13:20:00 +0200 Subject: WindowsXP/ CTypes - How to convert ctypes array to a string? In-Reply-To: References: Message-ID: dudeja.rajat at gmail.com wrote: > I've used CTYPES module to access a function from a dll. This function > provides me the version of the dll. This information is accessible to > me as an array of 4 long inetegers. information as : > 2, 1, 5, 0 > > I want to display these elements concatenated as "v2.1.5.0". This > string ( I'm thinking of writing the above 4 array elements to a > string) is to be displayed as label in a GUI ( the GUI used is Tk) > > Please suggest how can I write these elements to a string to get me > the desired results as "v2.1.5.0". And, is writing to a string is > right way? any special reason why you're not reading replies to your previous post? here's what I wrote last time. expecting that Python/ctypes should be able to figure out that you want an array of 4 integers printed as a dot-separated string is a bit optimistic, perhaps. but nothing that a little explicit string formatting cannot fix: >>> from ctypes import * >>> versionArr = c_long * 4 >>> version = versionArr(1, 2, 3, 4) >>> "%d.%d.%d.%d" % tuple(version) '1.2.3.4' inserting a "v" in the format string gives you the required result: >>> "v%d.%d.%d.%d" % tuple(version) 'v1.2.3.4' From ptmcg at austin.rr.com Sun Aug 3 04:39:22 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 3 Aug 2008 01:39:22 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> <7360bd9a-4ff6-4e75-821c-eabc88ee6258@u6g2000prc.googlegroups.com> Message-ID: <94fcd03e-739a-4db9-b386-65545aa45359@34g2000hsh.googlegroups.com> On Jul 31, 6:15?pm, Paul McGuire wrote: > On Jul 28, 12:15?pm, Kay Schluehr wrote: > > > > > > > On 28 Jul., 06:42, "Russ P." wrote: > > > > On Jul 27, 8:58 pm, castironpi wrote: > > > > > On Jul 27, 2:39 pm, Bruno Desthuilliers > > > > > wrote: > > > > > Derek Martin a ?crit : > > > > > > It's bad programming, but the world is full of bad programmers, and we > > > > > > don't always have the choice not to use their code. ?Isn't one of > > > > > > Python's goals to minimize opportunities for bad programming? > > > > > > Nope. That's Java's goal. Python's goals are to maximize opportunities > > > > > for good programming, which is quite different. > > > > Oh, gosh, that is so clever. What a bunch of crap. > > > > > +1 QOTW > > > > Do you realize what an insult that is to everyone else who has posted > > > here in the past week? > > > Nothing glues a community together so well as a common enemy. Or even > > better: two enemies i.e. Perl and Java in Pythons case. On the other > > hand, some enemies have to be ignored or declared to be not an enemy > > ( Ruby ), although oneself is clearly an enemy for them. The same > > antisymmetry holds for Python and Java. Java is an enemy for Python > > but Python is not worth for Java to be an enemy as long as it can be > > ignored. C++ and Java are enemies for each other. Same holds for Java > > and C#.- Hide quoted text - > > > - Show quoted text - > > Help... being... sucked into... black hole... inside a... Klein... > bottle...- Hide quoted text - > > - Show quoted text - ... which is inside... the black hole... From Edwin.Madari at VerizonWireless.com Mon Aug 18 15:28:22 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Mon, 18 Aug 2008 15:28:22 -0400 Subject: Newbie problem inserting into MySQL In-Reply-To: <4A358F5ED2A5364A86711EDFEB9494BD294C5AAA@NYOBGCEXMB21.uswin.ad.vzwcorp.com> Message-ID: <20080818192833.ECCA91E4006@bag.python.org> > -----Original Message----- > From: Madari, Edwin > Sent: Monday, August 18, 2008 3:03 PM > To: 'len'; python-list at python.org > Subject: Re: Newbie problem inserting into MySQL > > > -----Original Message----- > > From: > python-list-bounces+edwin.madari=verizonwireless.com at python.org > > [mailto:python-list-bounces+edwin.madari=verizonwireless.com at p > > ython.org] > > On Behalf Of len > > Sent: Monday, August 18, 2008 11:55 AM > > To: python-list at python.org > > Subject: Newbie problem inserting into MySQL > > > > > > Hi All > > > > I have started a little pet project to learn python and MySQL. The > > project involves figuring out all the combinations for a 5 number > > lottery and storing the data in a MySQL file. > > > > The file looks like this; > > +----------+---------------------+------+-----+--------- > > +----------------+ > > | Field | Type | Null | Key | Default | > > Extra | > > +----------+---------------------+------+-----+--------- > > +----------------+ > > | lottryid | int(11) | NO | PRI | NULL | > > auto_increment | > > | lottryno | char(10) | YES | | NULL > > | | > > | no1 | tinyint(3) unsigned | NO | | NULL > > | | > > | no2 | tinyint(3) unsigned | NO | | NULL > > | | > > | no3 | tinyint(3) unsigned | NO | | NULL > > | | > > | no4 | tinyint(3) unsigned | NO | | NULL > > | | > > | no5 | tinyint(3) unsigned | NO | | NULL > > | | > > | nosum | tinyint(3) unsigned | NO | | NULL > > | | > > | nohits | int(10) unsigned | YES | | NULL > > | | > > +----------+---------------------+------+-----+--------- > > +----------------+ > > > > The code looks as follows; > > #!/usr/lib/env python > > > > import MySQLdb > > import datetime > > > > db = MySQLdb.Connection(host="localhost", user="lenyel", > > passwd="lsumnler", \ > > db="lottery") > > > > cursor = db.cursor() > > > > cursor.execute('delete from littlelottery') > > > > listofrec = [] > > > > tupcnt = 0 > > print "first tuple created" > > for a in xrange(1,36): > > for b in xrange(2,37): > > for c in xrange(3,38): > > for d in xrange(4,39): > > for e in xrange(5,40): > > tupcnt += 1 > > thekey = ('%02i%02i%02i%02i%02i' % (a,b,c,d,e)) > > mysum = a + b + c + d + e > > rectuple = tupcnt, thekey, a, b, c, d, > e, mysum, 0 > > listofrec.append(rectuple) > > if tupcnt % 10000 == 0: > > print "beginnign of mysql write" > > print datetime.datetime.now().time() > > cursor.executemany('''insert into > > littlelottery > > values (?,?,?,?,?,?,?,?,?)''', listofrec) > > db.close() > > print "end of mysql write" > > print datetime.datetime.now().time() > > os._exit() > > > > print "insert into mysql completed" > > > > i get the following error on insert; > > raise errorclass, errorvalue > > TypeError: not all arguments converted during string formatting > > Script terminated. > > > > Do I have to covert all of the fields in the tuple records to string > > or what? > > > > Len Sumnler > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > statement prepared first and executed many times with > exectemany - db API http://www.python.org/dev/peps/pep-0249/ > inline statemets can be exeucuted only. > > hope that helps > Edwin another thing - cumulative inserts will result, since listofrec is not emptied after each sql execution. regards Edwin The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From haraldarminmassa at gmail.com Fri Aug 29 08:51:32 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Fri, 29 Aug 2008 05:51:32 -0700 (PDT) Subject: translating "create Semaphore" to Linux References: Message-ID: <34ca0e34-69d1-466c-83ff-b2d99f54ae39@z66g2000hsc.googlegroups.com> Tim, > ... why use a Semaphore rather than a Mutex? as much as I understood the documentation at MSDN http://msdn.microsoft.com/en-us/library/ms686927(VS.85).aspx http://msdn.microsoft.com/en-us/library/ms686946(VS.85).aspx a mutex seems to be nothing else than a special case of a semaphore? That is, a semaphore can be created to allow MAX_SEM_COUNT concurrent runners, and MUTEX defaults to one and only one ... The other api-spells are identical, like wait_for_xxxx...; so propably I stumbled on the working Semaphore Code before, or in some ancient win32 wrapper createMutex was not documented or something in that aspect:) > Or why notsimply use the bound socket as its own mutex? I know > Windows won't allow you to rebind the same socket to the > same addr/port in two different processes (unless perhaps > you play some trickery with the socket options). My experience was that this is correct for certain values of "allow" and "trickery". Sometimes the binding seems to get allowed but does not work. Main reason is that the socket-bind happens somewhere in medusa or ; so to use it as a semaphore I would have to dig there. I am not totally sure what trickery on socket is played down there; and I prefer to stay as far away as possible from that area. Harald From bj_666 at gmx.net Mon Aug 11 03:08:34 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Aug 2008 07:08:34 GMT Subject: for x,y in word1, word2 ? References: <55d5ea68-f613-4754-8510-cc3934e36421@b1g2000hsg.googlegroups.com> Message-ID: <6ga6riFet68vU1@mid.uni-berlin.de> On Sun, 10 Aug 2008 23:14:50 -0700, ssecorp wrote: > I know zip but lets say I have a word "painter" and I want to compare it > to a customer's spelling, he might have written "paintor" and I want to > check how many letters are the same. > > Now I know how I could do this, it is not hard. I am just wondering if > these is any specific simple syntax for it. No special syntax for that, but you can combine the `sum()` function, a generator expression and `zip()`: In [40]: sum(int(a == b) for a, b in zip('painter', 'paintor')) Out[40]: 6 Or this way if you think it's more clear: In [41]: sum(1 for a, b in zip('painter', 'paintor') if a == b) Out[41]: 6 Ciao, Marc 'BlackJack' Rintsch From Afro.Systems at gmail.com Tue Aug 12 10:21:15 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Tue, 12 Aug 2008 07:21:15 -0700 (PDT) Subject: trying to use SOCK_RAW yields error " References: <3b701b38-9dd3-48f6-bdb0-c04fc9085008@x41g2000hsb.googlegroups.com> Message-ID: > When using SOCK_RAW, the family should be AF_PACKET, > not AF_INET. Note that you need root privileges to do so. I changed as instructed: server = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.getprotobyname('ip')) now I am getting: Traceback (most recent call last): File "tcpsrv.py", line 15, in server.bind((host,port)) File "", line 1, in bind socket.error: (19, 'No such device') From Edwin.Madari at VerizonWireless.com Thu Aug 14 11:39:31 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Thu, 14 Aug 2008 11:39:31 -0400 Subject: a question about mysqldb In-Reply-To: Message-ID: <20080814154550.190A21E401D@bag.python.org> replace the name of table before calling *.execute. s.dbptr.execute(str % (e[0])) good luck. Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of Evan Sent: Thursday, August 14, 2008 11:27 AM To: python-list at python.org Subject: a question about mysqldb a simple problem but I do not know why...:(, could anyone help me? MySQLdb nominally uses just the %s placeholder style, in my script, i got error if you want to use placeholder(%s) for table name: +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ >>> str="select tID,tNote from %s where tID=1" <-------- check here >>> >>> e=["tmp"] >>> s.dbptr.execute(str,e) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line 166, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''tmp') where tID=1' at line 1") >>> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ But sql worked but the I got no query result: ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ >>> str="select tID,tNote from tmp where %s = %s" <----------check here >>> e=["tID",int(1)] >>> s.dbptr.execute(str,e) 0L <------------------ check here >>> >>> s.dbptr.fetchall() () >>> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ And then, it worked if I do: ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ >>> str="select tID,tNote from %s where %s = %s" % ("tmp","tID",1) >>> >>> str 'select tID,tNote from tmp where tID = 1' >>> s.dbptr.execute(str) 1L >>> >>> s.dbptr.fetchall() ({'tID': 1L, 'tNote': 'kao'},) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ mysql> desc tmp -> ; +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+----------------+ | tID | int(11) | NO | PRI | NULL | auto_increment | | tDate | date | YES | | NULL | | | tSID | int(11) | NO | | NULL | | | tCom | varchar(15) | YES | | NULL | | | tNote | text | YES | | NULL | | +-------+-------------+------+-----+---------+----------------+ 5 rows in set (0.00 sec) +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ mysql> mysql> Thanks, -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From poojaangali at gmail.com Fri Aug 15 06:00:13 2008 From: poojaangali at gmail.com (pooja) Date: Fri, 15 Aug 2008 03:00:13 -0700 (PDT) Subject: EARN MONEY $1500-$5000 PER MONTH Message-ID: <82300e5a-70ad-43d9-b464-2fe5a7c038e6@i20g2000prf.googlegroups.com> EARN MONEY $1500-$5000 PER MONTH SIMPLE ONLINE SURVEY CREATE UR ACCOUNT AND EARN IMMEDIATLY ************************************************************************* http://www.AWSurveys.com/HomeMain.cfm?RefID=kingraja666 ************************************************************************* From george.sakkis at gmail.com Wed Aug 27 17:09:58 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 27 Aug 2008 14:09:58 -0700 (PDT) Subject: Identifying the start of good data in a list References: <94524253-b946-4ffa-ae2e-ae6a555d4e7c@a1g2000hsb.googlegroups.com> Message-ID: <9bf75f04-a4bb-42ec-a80c-66ae4d458fd5@e53g2000hsa.googlegroups.com> On Aug 27, 3:00 pm, Gerard flanagan wrote: > tkp... at hotmail.com wrote: > > I have a list that starts with zeros, has sporadic data, and then has > > good data. I define the point at which the data turns good to be the > > first index with a non-zero entry that is followed by at least 4 > > consecutive non-zero data items (i.e. a week's worth of non-zero > > data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, > > 9], I would define the point at which data turns good to be 4 (1 > > followed by 2, 3, 4, 5). > > > I have a simple algorithm to identify this changepoint, but it looks > > crude: is there a cleaner, more elegant way to do this? > > > flag = True > > i=-1 > > j=0 > > while flag and i < len(retHist)-1: > > i += 1 > > if retHist[i] == 0: > > j = 0 > > else: > > j += 1 > > if j == 5: > > flag = False > > > del retHist[:i-4] > > > Thanks in advance for your help > > > Thomas Philips > > data = [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > def itergood(indata): > indata = iter(indata) > buf = [] > while len(buf) < 4: > buf.append(indata.next()) > if buf[-1] == 0: > buf[:] = [] > for x in buf: > yield x > for x in indata: > yield x > > for d in itergood(data): > print d This seems the most efficient so far for arbitrary iterables. With a few micro-optimizations it becomes: from itertools import chain def itergood(indata, good_ones=4): indata = iter(indata); get_next = indata.next buf = []; append = buf.append while len(buf) < good_ones: next = get_next() if next: append(next) else: del buf[:] return chain(buf, indata) $ python -m timeit -s "x = 1000*[0, 0, 0, 1, 2, 3] + [1,2,3,4]; from itergood import itergood" "list(itergood(x))" 100 loops, best of 3: 3.09 msec per loop And with Psyco enabled: $ python -m timeit -s "x = 1000*[0, 0, 0, 1, 2, 3] + [1,2,3,4]; from itergood import itergood" "list(itergood(x))" 1000 loops, best of 3: 466 usec per loop George From digitig at gmail.com Fri Aug 1 08:53:32 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 1 Aug 2008 13:53:32 +0100 Subject: Python Written in C? In-Reply-To: <8d3752f20807202258w2a4167e4hd40b56b12c0c74fc@mail.gmail.com> References: <8d3752f20807202258w2a4167e4hd40b56b12c0c74fc@mail.gmail.com> Message-ID: 2008/7/21 Krishnakant Mane : > First off all c# is absolute rubbish waist of time. What a pity others are joining in this pointless language flame-war. Look, I recently had to write a script for manipulating some data; I struggled to organise it in Python and in C++, but when I tried C# everything fell naturally into place and I had it done in next to no time. Other times it has been Python or C++ that has been the most natural way to express what I'm trying to do. Just because /you/ don't like C# doesn't mean it's rubbish or a waste of time; personally I loathe Perl, but I respect the fact that a lot of programmers can get good results very quickly in it. I reckon that the programmer who only knows one language is like a carpenter trying to make a cabinet with just a chisel. Ok for making the joints (although a hammer would have been handy to hit it with), not /really/ as good as a plane for getting large areas smooth, and the blade keeps jumping out when you try to use it as a screwdriver... The one-language programmer isn't really in a position to choose the right tool for the job, because they only have one tool. Anybody who says that a language in real use is a waste of time is denying the reality of those who find it an effective tool. Similarly, anybody who says that a language -- any language -- is right for all jobs plainly doesn't understand that language design involves a lot of compromises, and that the compromises that are appropriate choices for one task are inappropriate for another. Python is a great tool. So is C#. You /can/ do the same job with either, but the smart move is to choose the one that is best adapted to the task in hand. -- Tim Rowe From cousinstanley at gmail.com Fri Aug 29 09:47:30 2008 From: cousinstanley at gmail.com (Cousin Stanley) Date: Fri, 29 Aug 2008 15:47:30 +0200 (CEST) Subject: iterating over two arrays in parallel? References: Message-ID: > I want to interate over two arrays in parallel, > something like this: > > a=[1,2,3] > b=[4,5,6] > > for i,j in a,b: > print i,j > > where i,j would be 1,4, 2,5, 3,6 etc. > > Is this possible? > > Many TIA! > Mark >>> >>> list_1 = range( 1 , 4 ) >>> list_2 = range( 4 , 7 ) >>> >>> list12 = zip( list_1 , list_2 ) >>> >>> for this in list12 : ... print ' ' , this ... (1, 4) (2, 5) (3, 6) >>> >>> for i , j in list12 : ... print ' ' , i , j ... 1 4 2 5 3 6 -- Stanley C. Kitching Human Being Phoenix, Arizona From anartz at anartz.cjb.net Mon Aug 11 09:15:45 2008 From: anartz at anartz.cjb.net (anartz at anartz.cjb.net) Date: Mon, 11 Aug 2008 07:15:45 -0600 Subject: =?UTF-8?B?ZHluYW1pY2FsbHkgY3JlYXRpbmcgaHRtbCBjb2RlIHdpdGggcHl0aG9uLi4u?= Message-ID: <200808111315.m7BDFjqs045647@cjb.net> Hi, how can I combine some dynamically generated html code (using python) with the output of a urllib.openurl() call? I have tried to use the StringIO() class with .write functions, but it did not work. Below is the code that does not work. [CODE] f=StringIO.StringIO() f.write('data analysis') f.write(urllib.urlopen("http://localhost/path2Libs/myLibs.py", urllib.urlencode(TheData))) f.write("") print "Content-type: text/html\n" print f.read() f.close() [/CODE] What is wrong with this approach/code? Is there an easier way of doing it? Thanks. From martin at marcher.name Tue Aug 26 03:43:40 2008 From: martin at marcher.name (Martin Marcher) Date: Tue, 26 Aug 2008 09:43:40 +0200 Subject: Are dictionaries the same as hashtables? In-Reply-To: References: Message-ID: <20080826074338.GB10162@marcher.name> On 2008-08-26 00:32:20, cnb wrote: > Are dictionaries the same as hashtables? Yes, but there is nothing in there that does sane collision handling like making a list instead of simply overwriting. PS: your sig was *a bit* longer than you question. please don't do that... -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 844 bytes Desc: Digital signature URL: From deets at nospam.web.de Sat Aug 2 13:05:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 02 Aug 2008 19:05:53 +0200 Subject: Continually check object status In-Reply-To: <48dca0ce-3389-4f0d-a137-a1aaa9dcef67@25g2000hsx.googlegroups.com> References: <48dca0ce-3389-4f0d-a137-a1aaa9dcef67@25g2000hsx.googlegroups.com> Message-ID: <6fjifiFb0jraU1@mid.uni-berlin.de> futileissue at gmail.com schrieb: > Beginner, so please bare with me. I'm not sure what to call what it > is I'm looking for. > > If I have an object class, let's call it "Creature": > > class Creature: > def __init__(self, status): > self.status = "happy" > > def change_status(self, new_status): > self.status = new_status > > def print_status(self): > print self.status > > I would like to be able to print out the Creature's status every 20 > seconds. Let's say I use a script like this: > > import time > while True: > time.sleep(20) > Creature.print_status() > > But, while cycling through printing the status, I would like to be > able to update Creature.status to something new. > > I might be approaching this from the wrong direction entirely. Thanks > for your input. The "simple", yet possibly dangerous answer is: you need multi-threading. Multi-threading is a technique that allows several (quasi)-parallel paths of execution whilst sharing memory and objects inside that memory. The module in python to achieve this is called "threading". However, concurrent programming is a very advanced topic, ridded with pitfalls for even experienced developers. There are other ways to solve the problem, commonly known as event-loops and timers. These are usually part of frameworks for e.g GUI-creation an such, but you can also roll your own if you like. So, the better answer might be a question: what do you ultimately want to achieve? Given the name of your class, Creature, I assume you are writing on some game or such. Depending on how you plan to do that, you might have a framwork providing you with the needed tools/library calls or whatever. Diez From fredrik at pythonware.com Sat Aug 30 01:57:07 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 30 Aug 2008 07:57:07 +0200 Subject: Which is faster? In-Reply-To: References: Message-ID: cnb wrote: > For a big nbr of it might matter? > Is av_grade O(n*2) and the first O(n) when it comes to adding or is > "sum x for x in y" just traversing the list ones, accumulating the > values, it doesnt first build the list and then travese it for sum? sum() doesn't build a list, but even if it would do that, it'd still be O(n) -- looping over an array twice doesn't change the time complexity. to find out which one's actually faster, benchmark them. From aaa at bbb.it Mon Aug 4 05:59:13 2008 From: aaa at bbb.it (Fred Mangusta) Date: Mon, 04 Aug 2008 10:59:13 +0100 Subject: Nlp, Python and period Message-ID: Hi, are you aware of any nlp packages or algorithms in Python to spot whether a '.' represents an end of sentence or rather something else (eg Mr., foo at home.co.uk, etc)? Thanks F. From stephane at is-webdesign.com Mon Aug 25 08:56:04 2008 From: stephane at is-webdesign.com (=?iso-8859-1?q?KLEIN_St=E9phane?=) Date: Mon, 25 Aug 2008 12:56:04 +0000 (UTC) Subject: I can't fetch dom node in svg file with getElementById method (module minidom and libxml2dom) References: Message-ID: Le Mon, 25 Aug 2008 04:30:00 -0700, Paul Boddie a ?crit?: >> Well, my final purpose isn't to fetch root dom node but to fetch many >> other sub node. > > You could always try using an XPath expression: > > node = (dom2.xpath("//*[@id='svg2383']") or [None])[0] > > Similar things could be done in PyXML and other libraries, I'm sure, but > minidom lacks XPath support, if I remember correctly. Thanks ! It work. Regards, Stephane From deets at nospam.web.de Thu Aug 21 06:09:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 21 Aug 2008 12:09:52 +0200 Subject: evaluating code lines above breakpoints ? References: Message-ID: <6h4t94Fj84dgU1@mid.uni-berlin.de> Stef Mientki wrote: > hello, > > I'm trying to create a high level debugger, based on rpd2. > > So when the debugger enters a breakpoint, > I want to display the values of all variables in the, let's say, > 5 lines above the breakpoint (if possible). > Any hints on how I get a list of all vars in those lines ? > My rough idea is to scan the lines, skip keywords, test type of each > term ( by eval), if the term is var eval the value of it. > Are there better ways ? I don't know about better ways, but I for *sure* know that this is a really bad idea. Simply because a debugger that executes arbitrary evals can cause side-effects that make it useless. Why do you want this anyway? Why don't you simply show all the variables in the local frame? I'd say thats enough. > Another idea, when hoovering over a variable during a breakpoint, a > hint appears with the type and value of that var. The simple thing to do is to extract tokens, and then if these as names are matched in the local frames, you can display the content. Things get more difficult in cases like foo[index] as this can cause a side-effect to occur. I wouldn't automatically evaluate the expression, for reasons given above. Diez From timothy.grant at gmail.com Thu Aug 7 12:40:10 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Thu, 7 Aug 2008 09:40:10 -0700 Subject: Access individual fields in csv using python In-Reply-To: References: Message-ID: On Thu, Aug 7, 2008 at 9:23 AM, Krishna wrote: > How do I access individual fields in csv using python? Please let me > know ASAP as its real urgent for me. > > Thanks for your help > > Krishna > -- > http://mail.python.org/mailman/listinfo/python-list > I'd likely use the csv module. http://docs.python.org/lib/module-csv.html -- Stand Fast, tjg. [Timothy Grant] From circularfunc at yahoo.se Tue Aug 26 03:52:44 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 26 Aug 2008 00:52:44 -0700 (PDT) Subject: Are dictionaries the same as hashtables? References: Message-ID: <0dbb5dfe-8ec4-4a57-ac3f-08c021a39337@k30g2000hse.googlegroups.com> On Aug 26, 9:43?am, Martin Marcher wrote: > On 2008-08-26 00:32:20, cnb wrote: > > > Are dictionaries the same as hashtables? > > Yes, but there is nothing in there that does sane collision handling > like making a list instead of simply overwriting. > > PS: your sig was *a bit* longer than you question. please don't do > that... > > ?signature.asc > < 1KViewDownload my what? From gneuner2 at comcast.net Fri Aug 22 11:11:09 2008 From: gneuner2 at comcast.net (George Neuner) Date: Fri, 22 Aug 2008 11:11:09 -0400 Subject: The Importance of Terminology's Quality References: <48a8df27$0$7362$607ed4bc@cv.net> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: On Thu, 21 Aug 2008 02:30:27 GMT, sln at netherlands.com wrote: >On Wed, 20 Aug 2008 21:18:22 -0500, rpw3 at rpw3.org (Rob Warnock) wrote: > >>Martin Gregorie wrote: >>+--------------- >>| I was fascinated, though by the designs of early assemblers: I first >>| learnt Elliott assembler, which required the op codes to be typed on >>| octal but used symbolic labels and variable names. Meanwhile a colleague >>| had started on a KDF6 which was the opposite - op codes were mnemonics >>| but all addresses were absolute and entered in octal. I always wondered >>| about the rationale of the KDF6 assembler writers in tackling only the >>| easy part of the job. >>+--------------- >> >>In the LGP-30, they used hex addresses, sort of[1], but the opcodes >>(all 16 of them) had single-letter mnemonics chosen so that the >>low 4 bits of the character codes *were* the correct nibble for >>the opcode! ;-} >> >>[Or you could type in the actual hex digits, since the low 4 bits >>of *their* character codes were also their corresponding binary >>nibble values... "but that would have been wrong".] >> >> >>-Rob >> >>[1] The LGP-30 character code was defined before the industry had >> yet standardized on a common "hex" character set, so instead of >> "0123456789abcdef" they used "0123456789fgjkqw". [The "fgjkqw" >> were some random characters on the Flexowriter keyboard whose low >> 4 bits just happened to be what we now call 0xa-0xf]. Even worse, >> the sector addresses of instructions were *not* right-justified >> in the machine word (off by one bit), plus because of the shift- >> register nature of the accumulator you lost the low bit of each >> machine word when you typed in instructions (or read them from >> tape), so the address values you used in coding went up by *4*! >> That is, machine locations were counted [*and* coded, in both >> absolute machine code & assembler] as "0", "4", "8", "j", "10", >> "14", "18", "1j" (pronounced "J-teen"!!), etc. >> >>----- >>Rob Warnock >>627 26th Avenue >>San Mateo, CA 94403 (650)572-2607 > > >Whats os interresting about all this hullabaloo is that nobody has >coded machine code here, and know's squat about it. A friend of mine had an early 8080 micros that was programmed through the front panel using knife switches ... toggle in the binary address, latch it, toggle in the binary data, latch it, repeat ad nauseam. It had no storage device initially ... to use it you had to input your program by hand every time you turned it on. I did a little bit of programming on it, but I tired of it quickly. As did my friend - once he got the tape storage working (a new prom) and got hold of a shareware assembler, we hardly ever touched the switch panel again. Then came CP/M and all the initial pain was forgotten (replaced by CP/M pain 8-). >I'm not talking assembly language. Don't you know that there are routines >that program machine code? Yes, burned in, bitwise encodings that enable >machine instructions? Nothing below that. > >There is nobody here, who ever visited/replied with any thought relavence that can >be brought foward to any degree, meaning anything, nobody.... What are you looking for? An emulator you can play with? Machine coding is not relevant anymore - it's completely infeasible to input all but the smallest program. My friend had a BASIC interpreter for his 8080 - about 2KB which took hours to input by hand and heaven help you if you screwed up or the computer crashed. >sln George From mal at egenix.com Fri Aug 1 15:04:28 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 01 Aug 2008 21:04:28 +0200 Subject: DB-API corner case (psycopg2) In-Reply-To: <6fh3gfFbi581U1@mid.individual.net> References: <6fgi95Fbeot8U1@mid.individual.net> <6fh3gfFbi581U1@mid.individual.net> Message-ID: <48935E3C.3040304@egenix.com> On 2008-08-01 20:38, Thomas Guettler wrote: > I forgot to mention where I stumbled about this. > > Django has a wrapper: > http://code.djangoproject.com/browser/django/trunk/django/db/backends/util.py > > def execute(self, sql, params=()): > start = time() > try: > return self.cursor.execute(sql, params) > finally: > > Most people don't have a percent sign in the variable sql. > > I guess > cursor.execute(sql, None) > is not portable for all database backends. > > I guess this should be the best solution: > if params: > return self.cursor.execute(sql, params) > else: > return self.cursor.execute(sql) > > What do you think? Not good enough... you should use this: def execute(self, sql, params=None): start = time() try: if params is None: return self.cursor.execute(sql) else: return self.cursor.execute(sql, params) finally: ... > Thomas > > Thomas Guettler schrieb: >> Hi, >> >> I discovered this: >> >> import psycopg2 >> connection=psycopg2.connect("dbname='...' user='...'") >> cursor=connection.cursor() >> cursor.execute('''SELECT '%' ''') # Does not fail >> cursor.execute('''SELECT '%' ''', ()) # Does fail >> >> Traceback (most recent call last): >> File "/localhome/modw/tmp/t.py", line 5, in >> cursor.execute('''SELECT '%' ''', ()) # Does fail >> IndexError: tuple index out of range >> >> Is this a bug in psycopg2? >> >> How do other PEP 249 implementation behave? >> >> Regards, >> Thomas >> > -- > http://mail.python.org/mailman/listinfo/python-list -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Aug 01 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 26 06:29:41 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 26 Aug 2008 12:29:41 +0200 Subject: Is my thinking Pythonic? In-Reply-To: References: <638bf217-3eaf-43af-8604-4145aa156afe@m73g2000hsh.googlegroups.com> <39fcb558-2869-438b-9309-e55ccfed7ec6@i24g2000prf.googlegroups.com> <48add182$0$12232$426a74cc@news.free.fr> <48ae84de$0$13858$426a34cc@news.free.fr> Message-ID: <48b3dae6$0$17486$426a74cc@news.free.fr> Fredrik Lundh a ?crit : > Bruno Desthuilliers wrote: > >> Given the lack of proper support for the descriptor protocol in >> old-style classes and a couple other diverging behaviors, I wouldn't >> say that advising newcomers to use new-style classes is so pointless. > > Yeah, but if you don't need descriptors, new-style classes don't buy you > anything Except being python-3000 ready wrt/ diverging behavious - like overriding __magic__ methods on a per-instance basis. Ok, this is certainly not a very common case, but still we've seen questions about this on this ng... > (except a slight slowdown in certain situations). > Dogmatic "dogmatic" ??? > use > of new-style classes (or any other "new" feature) isn't "pythonic". You're right to quote the word "new" here - how many years since Python grew a new object model explicitely intended to replace the original one ? From brendandetracey at yahoo.com Mon Aug 25 08:42:08 2008 From: brendandetracey at yahoo.com (Brendan) Date: Mon, 25 Aug 2008 05:42:08 -0700 (PDT) Subject: urllib2 HTTPBasicAuthHandler and resumingbroken downloads References: <63d6d10e-c023-4ec6-9f11-0687d7ae8254@k37g2000hsf.googlegroups.com> Message-ID: <68ce446c-f7c0-45fb-a723-69db37dc9dea@d45g2000hsc.googlegroups.com> On Aug 22, 1:59?pm, "Gabriel Genellina" wrote: > En Fri, 22 Aug 2008 08:55:57 -0300, Brendan ? > escribi : > > > > > > > On Aug 21, 3:57?pm, "Gabriel Genellina" > > wrote: > >> En Thu, 21 Aug 2008 15:37:41 -0300, Brendan ? > >> ? > >> escribi : > > >> > Is there any way to resume an https file download using urllib2 and an > >> > HTTPBasicAuthHandler? > > >> You should provide the Range header (and probably If-Range too) in the ? > >> request.http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 > > > Ug. Why does everything in Python boil down to reading rfcs? It really > > slows us non computer science types down. I'll probably spend a day on > > this instead of an hour. I did search the web but had no luck finding > > an example, so I posted here as a last resort. > > The easy way is to use wget... > If you want a Python example, go to the Python cookbook:http://code.activestate.com/recipes/langs/python/ > enter "resume download" in the search box, and the very first recipe shows ? > how to use the Range header. > > -- > Gabriel Genellina- Hide quoted text - > > - Show quoted text - Thanks for the link. Much appreciated. From tino at wildenhain.de Sat Aug 30 15:57:12 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sat, 30 Aug 2008 21:57:12 +0200 Subject: Writing to ms excel In-Reply-To: References: Message-ID: <48B9A618.8090106@wildenhain.de> Marin Brkic wrote: > Hello all, > > please, let me apologize in advance. English is not my first language > (not even my second one), so excuse any errors with which I'm about to > embarass myself in front of the general public. Second, I'm relatively > new to python, so sorry if this seems like a stupid question. > > I'm trying to find a way to write data to excel cells (or to be more > specific to an .xls file), let's say for the sake of argument, data > readen from a file (although it will be calculated in the process). > I've been searching, but couldn't find any examples which allows that. > > Do anyone knows of any ? All help is appreciated on this matter. > Tutorials? Anything ... Its quite easy, a little googling brings: http://sourceforge.net/projects/pyexcelerator which comes with examples and all. Works on any platform (python only code). I'm using it to generate excel reports for all the damnd ms office adicts in the company... Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From deets at nospam.web.de Thu Aug 21 13:32:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 21 Aug 2008 19:32:58 +0200 Subject: Is my thinking Pythonic? References: <638bf217-3eaf-43af-8604-4145aa156afe@m73g2000hsh.googlegroups.com> <39fcb558-2869-438b-9309-e55ccfed7ec6@i24g2000prf.googlegroups.com> Message-ID: <6h5n7tFj6mk1U1@mid.uni-berlin.de> Craig Allen wrote: > generally, I name the members in the Class definition and set them to > None there... > > class Car: > speed = None > brand = None > > def __init__(): > self.speed = defaultspeed #alternately, and more commonly, get > this speed as a initializer argument > self.brand = defaultbrand > > > That solves the issue of being able to "see" all the members of an > object by reading code... however, this all goes out the window when > composing an instance dynamically (i.e. metaclass type stuff). While I use this idiom myself, one must be cautious not to create unwanted side-effects if anything mutable comes into play: class Foo: bar = [] def baz(self): self.bar.append(2) will *not* make bar instance-variable, but keep it as class-variable. From news1234 at free.fr Mon Aug 18 17:54:21 2008 From: news1234 at free.fr (nntpman68) Date: Mon, 18 Aug 2008 23:54:21 +0200 Subject: searching through a string and pulling characters In-Reply-To: References: Message-ID: <48a9ef8d$0$11574$426a34cc@news.free.fr> Hi, Is it thousands of lines or millions of lines? If it's just a few thousands and you're not working on an embedded device with little memory you could use the brute force approach Just read the whole file in one string vaiable split everything into an array separated by '()' Now you can directly access each element by number (or by number + 1 if you want, that the first index is 0 Example: ( assuming your text file is bla.txt ) import os import sys in_file = open('bla.txt') whole_text = in_file.read() sections = whole_text.split('()') # now print all entries n=0 for section in sections: print '%3d' % n,'---------------' print section n += 1 #or directly selecting one entry n=3 print "=" * 60 print 'Entry %d\n' % n,sections[3] print "=" * 60 bye N Alexnb wrote: > This is similar to my last post, but a little different. Here is what I would > like to do. > > Lets say I have a text file. The contents look like this, only there is A > LOT of the same thing. > > () A registry mark given by underwriters (as at Lloyd's) to ships in > first-class condition. Inferior grades are indicated by A 2 and A 3. > () The first three letters of the alphabet, used for the whole alphabet. > () In church or chapel style; -- said of compositions sung in the old church > style, without instrumental accompaniment; as, a mass a capella, i. e., a > mass purely vocal. > () Astride; with a part on each side; -- used specif. in designating the > position of an army with the wings separated by some line of demarcation, as > a river or road. > > Now, I am talking 1000's of these. I need to do something like this. I will > have a number, and what I want to do is go through this text file, just like > the example. The trick is this, those "()'s" are what I need to match, so if > the number is 245 I need to find the 245th () and then get the all the text > from after it until the next (). If you have an idea about the best way to > do this I would love your help. If you made it all the way through thanks! > ;) From deets at nospam.web.de Tue Aug 19 12:07:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 19 Aug 2008 18:07:00 +0200 Subject: who to call a list of method inside the class itself References: Message-ID: <6h09euFi1j20U1@mid.uni-berlin.de> Edwin.Madari at VerizonWireless.com wrote: > fredrik at pythonware.com wrote: >> >> Edwin.Madari at VerizonWireless.com wrote: >> >> > 1. return string names of required methods in getAllMethod >> > return ['method1', 'method2', 'method3'] >> > 2. use gettattr on self and then exetute methods in applyAll >> > def applyAll(self): >> > for method_name in self.getAllMethod(): >> > method = gettattr(self,method_name) >> > method() #execute method now >> >> why? > > ensure instance's method invocation with all state information to that > point, rather than relying on implemenation. Erm, that makes no sense. The OP's code was perfectly fine - for some reason he seemed to think it wasn't. Your additional indirection doesn't add anything beyond clutter, as name = "foo" getattr(instance, name) == instance.foo holds. Diez From darcy at druid.net Sat Aug 2 09:27:12 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 2 Aug 2008 09:27:12 -0400 Subject: Strong/weak typing In-Reply-To: References: <6727fa22-aee9-4a9b-b9c0-08534aab6b34@m45g2000hsb.googlegroups.com> Message-ID: <20080802092712.d252256e.darcy@druid.net> On Fri, 01 Aug 2008 22:47:04 -0400 Mel wrote: > middle_name = raw_input ('Name?') > middle_name = middle_name.split() > middle_name = middle_name[1] > > It works, but I don't like it enough to actually use it. Especially since this works better anyway: middle_name = raw_input ('Name?').split()[1] -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From wuwei23 at gmail.com Thu Aug 7 03:44:14 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 7 Aug 2008 00:44:14 -0700 (PDT) Subject: benchmark References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> <489a8cf8$0$11738$9b4e6d93@newsspool1.arcor-online.net> <00aa8eeb$0$20317$c3e8da3@news.astraweb.com> Message-ID: <7d6b3d0d-deb7-4f4b-99a8-1a5b52c1cf1f@h17g2000prg.googlegroups.com> Steven D'Aprano wrote: > In other words, about 20% of the time he measures is the time taken to > print junk to the screen. Which makes his claim that "all the console outputs have been removed so that the benchmarking activity is not interfered with by the IO overheads" somewhat confusing...he didn't notice the output? Wrote it off as a weird Python side-effect? I find his reluctance to entertain more idiomatic implementations particularly telling. It's seems he's less interested in actual performance comparisons and more into showing that writing static lang style code in dynamic langs is bad, which isn't really anything new to anyone anywhere, I would've thought. All up, this reminds me of last years benchmarking fiasco that demonstrated Storm's ORM handling being -incredibly-faster than SQLAlchemy's SQL expression handling, something that just didn't seem to be born out by user experience. Eventually, Mike Beyer reverse engineered the benchmarks to discover that, surprise surprise, the tests -weren't equal-; in one test SQLA was issuing a commit per insert, while Storm was performing -no commits whatsoever-. Benchmarks, IMO, are like statistics. You can tweak them to prove pretty much any position you already take. From cokofreedom at gmail.com Fri Aug 22 05:24:20 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Fri, 22 Aug 2008 02:24:20 -0700 (PDT) Subject: def X(l=[]): weirdness. Python bug ? References: <8824d$48ae83b2$18847a51$1995@news.chello.nl> Message-ID: On Aug 22, 11:13?am, Bart van Deenen wrote: > Hi all. > > I've stumbled onto a python behavior that I don't understand at all. > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > > # function > def X(l=[]): > ? ?l.append(1) > ? ?print l > > # first call of X > X() > [1] > > #second call of X > X() > [1, 1] > > Where does the list parameter 'l' live between the two successive calls of X(). > Why is it not recreated with an empty list? > Is this correct behavior or is it a Python bug? > Does anyone have any pointers to the language documentation where this behavior is described? > > Thanks all > > Bart van Deenen http://docs.python.org/ref/function.html "Default parameter values are evaluated when the function definition is executed." Depending on your use the common way to handle this is to do def x(lst = None): if lst is None: pass # lst has not been set to anything else: pass # lst has been set to something From lists at svrinformatica.it Thu Aug 14 03:50:28 2008 From: lists at svrinformatica.it (Mailing List SVR) Date: Thu, 14 Aug 2008 09:50:28 +0200 Subject: Distinguish file and folder on ftp site Message-ID: <1218700228.7851.1.camel@localhost.localdomain> Hi, is there a simple way to do this? ftplib seems unable to distinguish between files and dir, a mimetype check would be good, regards Nicola From half.italian at gmail.com Mon Aug 11 19:03:20 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Mon, 11 Aug 2008 16:03:20 -0700 (PDT) Subject: SSH utility References: Message-ID: On Aug 11, 5:17?am, Edwin.Mad... at VerizonWireless.com wrote: > for similar tasks, I use pexpecthttp://pypi.python.org/pypi/pexpect. > > spawning bash process and simulate an interactive session. Here sending ls command, retrieving results and exiting. In the spawned process ssh or any other command, is just another command. > > ------------actual session-------------------------- > $ python > Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) > [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin > Type "help", "copyright", "credits" or "license" for more information.>>> import pexpect > >>> c = pexpect.spawn('/bin/bash') > >>> c.expect([pexpect.TIMEOUT, pexpect.EOF, '\$ ']) > 2 > >>> c.before, c.after > > ('\x1b[?1034hmadared at NJWARHQD0IT696A:~\r\n', '$ ')>>> c.sendline('ls') > 3 > >>> c.expect([pexpect.TIMEOUT, pexpect.EOF, '\$ ']) > 2 > >>> c.before, c.after > > ('ls\r\x.txt ?xx.txt ?xy.txt ?y.txt\r\nmadared at NJWARHQD0IT696A:~\r\n', '$ ')>>> c.sendline('exit') > 5 > >>> c.expect([pexpect.TIMEOUT, pexpect.EOF, '\$ ']) > 1 > >>> c.before, c.after > > ('exit\r\nexit\r\n', )>>> exit() > > madared at NJWARHQD0IT696A:~ > $ > --------------------------------------------------------------- > > hope that helps. > > regards. > Edwin > > -----Original Message----- > From: python-list-bounces+edwin.madari=verizonwireless.... at python.org > > [mailto:python-list-bounces+edwin.madari=verizonwireless.... at python.org] > On Behalf Of James Brady > Sent: Monday, August 11, 2008 12:26 AM > To: python-l... at python.org > Subject: SSH utility > > Hi all, > I'm looking for a python library that lets me execute shell commands > on remote machines. > > I've tried a few SSH utilities so far: paramiko, PySSH and pssh; > unfortunately all been unreliable, and repeated questions on their > respective mailing lists haven't been answered... > > It seems like the sort of commodity task that there should be a pretty > robust library for. Are there any suggestions for alternative > libraries or approaches? > > Thanks! > James > --http://mail.python.org/mailman/listinfo/python-list > > The information contained in this message and any attachment may be > proprietary, confidential, and privileged or subject to the work > product doctrine and thus protected from disclosure. ?If the reader > of this message is not the intended recipient, or an employee or > agent responsible for delivering this message to the intended > recipient, you are hereby notified that any dissemination, > distribution or copying of this communication is strictly prohibited. > If you have received this communication in error, please notify me > immediately by replying to this message and deleting it and all > copies and backups thereof. ?Thank you. I second pexpect and the nice little module that comes with it ssh_session.py. Been using it for ages now! ~Sean From raashid_hbk at yahoo.com Wed Aug 20 13:39:45 2008 From: raashid_hbk at yahoo.com (raashid bhatt) Date: Wed, 20 Aug 2008 10:39:45 -0700 (PDT) Subject: urllib fails to connect References: Message-ID: <5e7ed5d0-e2d3-4364-8567-456e3988d226@z11g2000prl.googlegroups.com> On Aug 20, 10:06?am, "jlist" wrote: > I'm running ActiveState Python 2.5 on Windows XP. It used > to work fine. Today however I get (10061, 'Connection refused') > for any site I try with urllib.urlopen(). May be the host is Listening on the port you are connecting to or the host isnt availible if u on a LAN try to ping the host first and Disable the Firewall on Hosts Computer From kay.schluehr at gmx.net Sat Aug 9 04:38:04 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 9 Aug 2008 01:38:04 -0700 (PDT) Subject: ANN: P4D 1.2 Message-ID: P4D = E4X style embedded DSL for Python but without E and X. The main feature of P4D 1.2 are *Bytelets*. While the primary purpose of P4D 1.1 was the support textual data which can be considered as isomorphic to XML the new release is focussed on binary data. Bytelets are P4D objects that are assembled from hexcode which is reified as a Hex object. Bytelets can also be serialized as Hex objects which makes them apt for low level communication. Bytelets can be used to parse hexcode into other Bytelets of the same structure and Bytelets can be cloned like object prototypes which makes it easy to produce sequences of variations of one Bytelet ( usually you do not derive from a Bytelet but modify a prototype ). For more information see: http://pypi.python.org/pypi/P4D http://www.fiber-space.de http://www.fiber-space.de/EasyExtend/doc/p4d/bytelets.html From fabiofz at gmail.com Fri Aug 22 22:52:03 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Fri, 22 Aug 2008 23:52:03 -0300 Subject: Pydev 1.3.20 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.20 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Code Analysis: Show error if using token not defined in __all__ in wild import. * Search: Working with eclipse 3.4. Release Highlights in Pydev: ---------------------------------------------- * Pydev Package Explorer: Editor-link does not remove focus from current editor if it's already a match (bug when compare editor was opened) * Pydev debugger: Showing set and frozenset contents * Pydev debugger: Watch working in eclipse 3.4 * Pydev debugger: Breakpoint properties accept new lines and tabs * Pydev debugger: Workaround for python bug when filenames don't have absolute paths correctly generated * Pydev code-completion: Wild import will only show tokens defined in __all__ (if it's available) * Interactive console: Fixed problem when more attempts to connect were needed * Interactive console: Fixed console integration problem with other plugins because of interfaces not properly implemented * Incremental find: Backspace works correctly * Launch icons: Transparent background (thanks to Radim Kubacki) * Code Formatter: Exponentials handled correctly * Launching: Unit-test and code-coverage may launch multiple folders/files at once * Code coverage: Number format exception no longer given when trying to show lines not executed in the editor and all lines are executed * Auto-indent: Fixed issue when using tabs which could result in spaces being added What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From notvalid2 at sbcglobal.net Sat Aug 23 13:53:24 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Sat, 23 Aug 2008 10:53:24 -0700 Subject: Total No. of "Records" in a File? In-Reply-To: References: <1JXrk.20070$89.12375@nlpi069.nbdc.sbc.com> Message-ID: Nick Dumas wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Err...you want to know what is in a file before you open it? This could > be done if you keep some external database documenting changes made to > the file. But unless I misunderstand what you're saying, then it's not > possible to know the contents of a file without opening and reading that > file. > > W. eWatson wrote: >> I have an ordinary text file with a CR at the end of a line, and two >> numbers in each line. Is there some way to determine the number of lines >> (records) in the file before I begin reading it? >> > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (MingW32) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iEYEARECAAYFAkiwSZ4ACgkQLMI5fndAv9hXugCeJs5XBkLLne6ljqQggB/MoAVs > SNIAoJxsU04cwcZMrH9QjElAbMD34RdK > =RlmP > -----END PGP SIGNATURE----- Maybe. I could see it if the file were truly in a record format. The # of records might be kept by the OS. It's conceivable that Python or the OS might see a file with a CR as "recordized". All unlikely though. Just checkin'. How about in a slightly different case. Suppose I want to know the number of files in a folder? The OS and maybe some Python method might know that. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From Edwin.Madari at VerizonWireless.com Thu Aug 7 11:53:53 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Thu, 7 Aug 2008 11:53:53 -0400 Subject: Testing for the first few letters of a string In-Reply-To: Message-ID: <20080807155404.C68641E400D@bag.python.org> use re module import re template = '^My name is alex' astring = 'My name is alex, and I like pie' if re.match(template, astring): print 'Found it' else: print '%s does not begin with %s' % (astring, template) good luck. Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of Alexnb Sent: Thursday, August 07, 2008 11:40 AM To: python-list at python.org Subject: Testing for the first few letters of a string Okay, I have a fix for this problem, but it is messy and I think there might be a better way. Heres an example: Lets say I have a string: "My name is alex" and I have another string "My name is alex, and I like pie". I want to test to see if just the "My name is alex" part is there. I don't care about the pie part. My first instinct was to just create a for loop and test for the string like this: n = 0 for x in string1: if string1[n] == string2[n] n = n +0 else: break and then later testing to see what n was = to and figuring out if it got through the whole loop. I feel like there should be an easier way to do this, and probably is. So Does anyone have a suggestion? -- View this message in context: http://www.nabble.com/Testing-for-the-first-few-letters-of-a-string-tp18873375p18873375.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From notvalid2 at sbcglobal.net Sat Aug 23 19:28:42 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Sat, 23 Aug 2008 16:28:42 -0700 Subject: Turning py into an Executable Program for Win? Message-ID: How do I get my py code into some executable form so that Win users who don't have python can execute it? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From fiacre.patrick at gmail.com Thu Aug 28 12:01:30 2008 From: fiacre.patrick at gmail.com (Andrew Lee) Date: Thu, 28 Aug 2008 12:01:30 -0400 Subject: def X(l=[]): weirdness. Python bug ? In-Reply-To: <8824d$48ae83b2$18847a51$1995@news.chello.nl> References: <8824d$48ae83b2$18847a51$1995@news.chello.nl> Message-ID: <48b6cb62$0$20917$607ed4bc@cv.net> Bart van Deenen wrote: > Hi all. > > I've stumbled onto a python behavior that I don't understand at all. > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > > # function > def X(l=[]): > l.append(1) > print l > > # first call of X > X() > [1] > > #second call of X > X() > [1, 1] > > Where does the list parameter 'l' live between the two successive calls of X(). > Why is it not recreated with an empty list? > Is this correct behavior or is it a Python bug? > Does anyone have any pointers to the language documentation where this behavior is described? > > Thanks all > > Bart van Deenen > I happen to be reading about decorators at the moment: from copy import deepcopy def nodefault(myfunc): myfunc_defaults = myfunc.func_defaults def fresh(*args, **kwargs): myfunc.func_defaults = deepcopy(myfunc_defaults) return myfunc(*args, **kwargs) return fresh @nodefault def X(l=[]): l.append(1) print l >>> for i in range(1,6): ... X() ... [1] [1] [1] [1] [1] Which is just a very fancy way of doing: def X(l=[]): if l is None: l = [] l.append(1) print l * sound of two pennies * From Sebastian.Pawlus at gmail.com Tue Aug 26 06:40:28 2008 From: Sebastian.Pawlus at gmail.com (x_O) Date: Tue, 26 Aug 2008 03:40:28 -0700 (PDT) Subject: RPCXML hide implementation. Message-ID: <1309dc37-6589-428c-a7fa-3e9e3251b872@2g2000hsn.googlegroups.com> Hi I'm working recently with XMLRPC for python and It never was so easy. But I've meet a obstacle. Because python is not giving us any reasonable encapsulation mechanism, I have problems with hiding some part of the implementation. When class has 2 methods and I want to make rpc private only ONE of them. I can always use __name. But what in case when I really need to use those two methods inside other class as a public, but not by RPC Simple code: class RpcClass: def one(self): #visible by RPC, available as public for other class return "one" def two(self): #INVISIBLE by RPC, available as public for other class return "two" Server.register_instance(RpcClass()) Thanks From steve at REMOVE-THIS-cybersource.com.au Thu Aug 21 06:22:46 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Aug 2008 10:22:46 GMT Subject: exception handling in complex Python programs References: Message-ID: <00bd3cc9$0$20315$c3e8da3@news.astraweb.com> On Thu, 21 Aug 2008 00:34:21 -0700, eliben wrote: > On Aug 19, 7:19?pm, eliben wrote: >> Python provides a quite good and feature-complete exception handling > > > Thanks for the interesting discussion. Armed by the new information and > few online sources, I blogged a summary for myself on the topic of > robust exception handling in Python: > > http://eli.thegreenplace.net/2008/08/21/robust-exception-handling/ Just a few random points. You say: "Exceptions are better than returning error status codes. Some languages (like Python) leave you with no choice as the whole language core and standard libraries throw exceptions." Of course you have a choice. Your function can return anything you want: def mysqrt(x): try: return math.sqrt(x) except ValueError: return "Code 37" I've written functions that return an object on success and None if the function failed. In the context of what I was doing, that made more sense than raising an exception. Furthermore, the str.find() method returns -1 for not found instead of raising an exception. There are probably other examples as well. You also wrote: "Exceptions exist for exceptional situations: unanticipated events that are not a part of normal execution." Exceptions can and often are anticipated. E.g. if you write code that opens a URL, you better anticipate that the server might reject your connection. You better expect to be asked for a cookie, or authentication. If you check for robots.txt, you better expect that it might not exist. That's all normal execution. "When a programmer calls str.find('substring') he doesn?t expect an exception to be thrown if the substring isn?t found." But if he called str.index() then he does expect an exception to be thrown, just like for list.index() and dict[key] can raise exceptions. They are neither bugs nor unexpected. "This is what he called find for. A better approach is to return a special value like None or -1." Sometimes, maybe. But usually not, because that just complicates the calling code. You end up writing code that repeatedly checks that the result isn't a special value before doing anything. Often a better tactic is to write your code assuming that the result is the unexceptional case, and then wrap it in a try...except block to catch the exceptional cases. "When used for flow-control, exceptions are like goto. There might be a few esoteric cases in which they?re appropriate, but 99.99% of the time they are not." I strongly disagree. try...except is like break or continue. Yes, it breaks the linear flow of control, but not in a wild, dangerous way like goto. It is possible to write bad code with exceptions, but you can write bad code with anything. -- Steven From gminick at bzt.bzt Fri Aug 15 11:17:50 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Fri, 15 Aug 2008 15:17:50 +0000 (UTC) Subject: How do I control output buffering on Win32? References: <1I-dndTLBfGbCjjVnZ2dnUVZ_hCdnZ2d@posted.visi> Message-ID: On Fri, 15 Aug 2008 09:47:34 -0500, Grant Edwards wrote: > When I ssh in to my Windows XP box and run Python apps, output > from "print" and and "sys.stdout.write()" is being buffered so > that none of the output shows up until the program exits. > > From within my program how do I set output buffering to either > line-buffered or un-buffered? [I'm looking for the equivalent > of the C stdio "setbuf" call.] That's not exactly what you want, but what about creating your own printing function and flushing at its end? import sys def printf(mystr): print mystr sys.stdout.flush() -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From timothy.grant at gmail.com Mon Aug 4 20:28:52 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Mon, 4 Aug 2008 17:28:52 -0700 Subject: Module re, extract on string match In-Reply-To: References: Message-ID: On Mon, Aug 4, 2008 at 4:54 PM, Sriram Rajan wrote: > I am wondering if I can use re.search to extract from a particular > location in a string. > Example: > string1='/Users/sriram/folder1/folder2/folder3/folder4/folder5/file' > re.search ('folder3,string1) > > > > Thanks, > > Sriram Something like below? Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> s = '/Users/sriram/folder1/folder2/folder3/folder4/folder5/file' >>> y = re.search('folder3.*', s) >>> y.group() 'folder3/folder4/folder5/file' >>> -- Stand Fast, tjg. [Timothy Grant] From timr at probo.com Mon Aug 18 01:17:52 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 18 Aug 2008 05:17:52 GMT Subject: export sites/pages to PDF References: Message-ID: jvdb wrote: > >My employer is asking for a solution that outputs the content of urls >to pdf. It must be the content as seen within the browser. >Can someone help me on this? It must be able to export several kind of >pages with all kind of content (javascript, etc.) There are a number of obstacles to this. Printer pages are a different size from screen windows, so the browser does the layout differently. Further, many style sheets have rules that are "screen only" or "print only". If you really want an image of exactly what's on the screen, then I don't think you have any option other than a screen capture utility, like "xwd". -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tjreedy at udel.edu Fri Aug 1 16:45:10 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 01 Aug 2008 16:45:10 -0400 Subject: Difference between type and class In-Reply-To: References: <87myjy2vc6.fsf@nokile.rath.org> <00a23ad3$0$20313$c3e8da3@news.astraweb.com> Message-ID: Thomas Troeger wrote: > Steven D'Aprano wrote: >>> class A: >>> def bar(self): >>> print "A" >> >> >> Alas, you've chosen the worst-possible example to "clarify" matters, >> because old-style classic classes are *not* unified with types, and >> will disappear in the future: > > Of course I wanted to write `class A(object)', but I keep forgetting > this one because I'm still used to the old ways... > > Will this disappear in Python 3.0., i.e. can you again simply write > class A: > and inherit from object automagically? Yes. IDLE 3.0b2 >>> class a: pass >>> a >>> a.__bases__ (,) 3.0 is really a nicer version. Once the final release is out, the main reason to stick with 2.x for new code will be if it depends on third-party code (including your own ;-) that has not been upgraded. From brahmaforces at gmail.com Tue Aug 19 02:32:05 2008 From: brahmaforces at gmail.com (brahmaforces) Date: Mon, 18 Aug 2008 23:32:05 -0700 (PDT) Subject: Python Substitute for PHP GD, Resizing an image on the client side Message-ID: <02f733bb-e734-46a9-b42f-5b664cdddd3f@v26g2000prm.googlegroups.com> Hi Folks, I am using cherrypy and python. I am trying to get a user profile image to resize on the client side before uploading to the server. PHP has a gd library that does it it seems. Has anyone done this in a python environment without uploading to the server? From prologic at shortcircuit.net.au Thu Aug 28 00:48:58 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 28 Aug 2008 14:48:58 +1000 Subject: List of modules available for import inside Python? In-Reply-To: References: Message-ID: On Thu, Aug 28, 2008 at 2:21 PM, ssecorp wrote: > Also, is there anything like Cpan for Python? Try the Python Cheese Shop / PyPi http://pypi.python.org/pypi cheers James -- -- -- "Problems are solved by method" From george.sakkis at gmail.com Fri Aug 22 23:13:49 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 22 Aug 2008 20:13:49 -0700 (PDT) Subject: Should Python raise a warning for mutable default arguments? References: <00becb2d$0$20312$c3e8da3@news.astraweb.com> <6h8hhhFk2gamU1@mid.uni-berlin.de> <00bf687f$0$20312$c3e8da3@news.astraweb.com> Message-ID: <3c3ec9a8-5d1e-4aeb-afce-267d99520a67@x41g2000hsb.googlegroups.com> On Aug 22, 9:54?pm, Steven D'Aprano wrote: > On Fri, 22 Aug 2008 14:39:11 -0700, Emile van Sebille wrote: > > Dan wrote: > >> I'd suggest that at the > >> end of the tutorial, when people have a better general idea of how > >> Python works, there would be a Python Gotchas section. > > > Hmmm, OK -- mutable defaults, integer division, name mangling... > > > I'd think decimal precision is more a general problem than a python > > problem, but still one that throws newbies... > > > Any other ideas for gotcha's (as opposed to faqs)? > > Augmented assignment: x ?= y is not always the same as x = x ? y. > > Repeated string addition can be very slow. For that matter, so can list > addition. > > Inserting at the beginning of lists is slow. > > Everything about unicode is a Gotcha! *wink* > > Raw strings are not designed for Windows paths, they're designed for > regexes. Consequently, you can't write the following: > > r'C:\dir\' > > list.sort() and list.reverse() return None. > > sorted() returns a list, but reversed() returns an iterator. > > urllib2.urlopen() will automatically detect the proxy in your environment > and use that. That's usually a feature, but sometimes it can be a gotcha. > > urllib2 doesn't work well with some HTTPS proxies. This is, I believe, a > known bug, but until it is fixed, it can be a gotcha. My "favorite": comparisons between disparate types are allowed by default. Thankfully fixed in 3.0. George From steve at REMOVE-THIS-cybersource.com.au Mon Aug 25 19:48:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Aug 2008 23:48:00 GMT Subject: Replace reduce with listcomprehension? References: <3a99c7ea-4cc9-4b9f-b6f8-60856cbd8837@c58g2000hsc.googlegroups.com> <836b78ed-605b-4b23-933e-116953103a0f@d77g2000hsb.googlegroups.com> <297c7ac3-f63a-4ffe-8597-ef975b8bf5b8@y21g2000hsf.googlegroups.com> <6hgrffFlsv2pU1@mid.uni-berlin.de> Message-ID: <00c33f63$0$15868$c3e8da3@news.astraweb.com> On Tue, 26 Aug 2008 00:53:35 +0200, Diez B. Roggisch wrote: >> So it seems only reduce will be eliminated. > > Nope. From the link you provided yourself: > > """ > Only reduce will be removed from the 3.0 standard library. You can > import it from functools. > """ functools isn't in the standard library??? *wink* Seriously, I think Guido meant "built-ins". Since I don't agree with him that reduce() is hard to read, I disagree that accumulators are easier to use. But since reduce is only an import away, I'm satisfied. -- Steven From bj_666 at gmx.net Wed Aug 27 11:39:30 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Aug 2008 15:39:30 GMT Subject: Getting references to obect instances into a list References: <59619323-8ff1-4697-bfbe-b19aa478e8b8@m44g2000hsc.googlegroups.com> Message-ID: <6hlapiFmn37uU1@mid.uni-berlin.de> On Wed, 27 Aug 2008 08:32:52 -0700, parent.eric.3 at gmail.com wrote: > Thanks for your reply Simon. > > I will read the article you told me to but first, please, have a look at > this snippet: Please read the article! >>>> m = [2,3,4] >>>> p = ['a','b','c'] >>>> q = [m,p] >>>> q > [[2, 3, 4, 'a', 'b', 'c'], ['a', 'b', 'c']] >>>> del p >>>> q > [[2, 3, 4, 'a', 'b', 'c'], ['a', 'b', 'c']] >>>> >>>> > > How come q is not updated after I deleted p? Because neither the name `q` nor the list object bound to it has anything to do with the name `p`. ``del`` does not delete objects but *names*. Objects exist as long as there is a reference to them. You deleted the name `p` and thus one reference to the list with the three characters but there's still the reference from the list bound to `q` to that three character list. What did you expect for an "updated q" anyway? Ciao, Marc 'BlackJack' Rintsch From Slaunger at gmail.com Thu Aug 7 02:16:52 2008 From: Slaunger at gmail.com (Slaunger) Date: Wed, 6 Aug 2008 23:16:52 -0700 (PDT) Subject: Best practise implementation for equal by value objects References: <135eb396-6daa-4ff4-a722-253ba149889c@27g2000hsf.googlegroups.com> Message-ID: <573362d6-5356-4029-8ee4-f43248263976@p25g2000hsf.googlegroups.com> On 6 Aug., 21:36, Terry Reedy wrote: > Slaunger wrote: > > Hi, > > > I am new here and relatively new to Python, so be gentle: > > > Is there a recommended generic implementation of __repr__ for objects > > equal by value to assure that eval(repr(x)) == x independet of which > > module the call is made from? > > The CPython implementation gives up on that goal and simply prints > for at least two reasons ;-). > > 1. In general, it require fairly sophisticated analysis of __init__ to > decide what representation of what attributes to include and decide if > the goal is even possible. ?If an attribute is an instance of a user > class, then *its* __init__ needs to be analyzed. ?If an attribute is a > module, class, or function, there is no generic evaluable representation. OK, the situation is more complicated than that then. In the case here though, the attributes would always be sinmple bulit-in types, where eval(repr(x))==x or, where the attribute is a user-defined equal-by-value class, that I have control over. The classes I am making as struct type classes with some added functionlity for human readable string representation, packing into a stream or unpacking from a stream using a "private" class Struct. I come from a Java and JUnit world, where, if I am used to always overriding the default reference based implementations of the equals(), toString(), and hashCode() methods for "equals-by-value" objects such that they work well and efficient in, e.g., hash maps. With my swich-over to Python, I looked for equivalent features and stumbled over the eval(repr(x))==x recommendation. It is not that I actually (yet) need the repr implementations, but mostly because I find the condition very useful in PyUnit to check in a test that I have remembered to initialize all instance fields in __init__ and that I have remembered to include all relevant attributes in the __eq__ implementation. Whereas this worked fine in a unit test module dedicated to only test the specific module, the test failed when called from other test package modules, wrapping the unit tests from several unit test modules. > > 2. Whether eval(repr(x)) even works (returns an answer) depends on > whether the name bindings in the globals and locals passed to eval > (which by default are the globals and locals of the context of the eval > call) match the names used in the repr. ?You discovered that to a first > approximation, this depends on whether the call to repr comes from > within or without the module containing the class definition. ?But the > situation is far worse. ?Consider 'import somemod as m'. ?Even if you > were able to introspect the call and determine that it did not come from > somemod**, prepending 'somemod.' to the repr *still* would not work. > Or, the call to repr could come from one context, the result saved and > passed to another context with different name bindings, and the eval > call made there. ?So an repr that can be eval'ed in any context is hopeless. > Ok, nasty stuff > If this is a practical rather than theoretical question, then use your > first repr version that uses the classes definition name and only eval > the result in a context that has that name bound to the class object. > > from mymod import Age > #or > import mymod > Age = mymod.Age > > #in either case > eval(repr(Age(10))) == Age(10) > > > class Age: > > > ? ? def __init__(self, an_age): > > ? ? ? ? self.age = an_age > > > ? ? def __eq__(self, obj): > > ? ? ? ? self.age == obj.age > > > ? ? def __repr__(self): > > ? ? ? ? return self.__class__.__name__ + \ > > ? ? ? ? ? ? ? ?"(%r)" % self.age > Yes, it is most from a practicl point of view, altough I was surprised that I could not find more material on it in the Python documentation or mailing groups, and I moight just do what you suggest in the unit test modules to at least make it robust in that context. Hmm... a bit of a dissapointment for me that this cannot be done cleaner > ** > While such introspection is not part of the language, I believe one > could do it in CPython, but I forgot the details. ?There have been > threads like 'How do I determine the caller function' with answers to > that question, and I presume the module of the caller is available also. OK, I think CPython, for the moment, is too much new stuff to dig into right now. Just grasping some of all the possibilities in the API, and how to do things the right way is giving me enough challenges for now... > > Terry Jan Reedy Again, thank you for your thorough answer, Slaunger From hubaghdadi at gmail.com Wed Aug 27 06:09:58 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Wed, 27 Aug 2008 03:09:58 -0700 (PDT) Subject: Understanding this generator function Message-ID: Hey, This is an example of a generator function: ===== def counter(start_at=0): count = start_at while True: val = (yield count) if val is not None: count = val else: count += 1 ====== >>> count = counter(5) >>> count.next() 5 >>> count.send(9) 9 ====== I'm not able to understand how this generator function is working, would you please me (what happens when calling next/send)? Thanks. From davidreynon at gmail.com Tue Aug 19 11:42:55 2008 From: davidreynon at gmail.com (korean_dave) Date: Tue, 19 Aug 2008 08:42:55 -0700 (PDT) Subject: datetime.datetime.now() in military time Message-ID: <4401a30e-0445-40d3-b23a-bec538ff148c@a70g2000hsh.googlegroups.com> import datetime def main(): timenow = datetime.datetime.now() print(str(timenow.hour)) if __name__ == "__main__": main() If the time was, say, 2pm, how can I make output of timenow.hour "14" instead of "2"? Thanks. -Dave From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 26 04:52:30 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 26 Aug 2008 10:52:30 +0200 Subject: A variables variables In-Reply-To: <5455bc1a-a4fe-42b2-ab86-9becf30b8f6e@x35g2000hsb.googlegroups.com> References: <625fce19-df89-4a6c-890a-22008a4fe92f@c58g2000hsc.googlegroups.com> <5455bc1a-a4fe-42b2-ab86-9becf30b8f6e@x35g2000hsb.googlegroups.com> Message-ID: <48b3c41f$0$30971$426a74cc@news.free.fr> castironpi a ?crit : > On Aug 23, 7:25 pm, Gandalf wrote: >> how can I declare a variable with another variable name? >> >> for example I will use PHP: >> >> $a= "hello"; >> >> $a_hello="baybay"; >> >> print ${'a_'.$a) //output: baybay >> >> how can i do it with no Arrays using python >> >> thanks! > > Here's one idea. > >>>> a= 'hello' >>>> a_hello= 'bayb' >>>> print eval( 'a_'+ a ) > bayb Please avoid this kind of yucky ugly hacks. From ivan at datasyncorp.com Mon Aug 4 11:40:37 2008 From: ivan at datasyncorp.com (Ivan Ven Osdel) Date: Mon, 4 Aug 2008 10:40:37 -0500 (CDT) Subject: Agnostic fetching In-Reply-To: <6fjetjFbovjiU1@mid.uni-berlin.de> Message-ID: <909379793.819371217864437840.JavaMail.root@saturn.datasyncintra.net> >----- Original Message ----- >From: "Diez B. Roggisch" >To: python-list at python.org >Sent: Saturday, August 2, 2008 11:05:07 AM GMT -06:00 US/Canada Central >Subject: Re: Agnostic fetching >Bruce Frederiksen schrieb: > On Fri, 01 Aug 2008 17:05:00 -0700, jorpheus wrote: > >> OK, that sounds stupid. Anyway, I've been learning Python for some >> time now, and am currently having fun with the urllib and urllib2 >> modules, but have run into a problem(?) - is there any way to fetch >> (urllib.retrieve) files from a server without knowing the filenames? >> For instance, there is smth like folder/spam.egg, folder/ >> unpredictable.egg and so on. If not, perhaps some kind of glob to >> create a list of existing files? I'd really appreciate some help, >> since I'm really out of my (newb) depth here. > > You might try the os.path module and/or the glob module in the standard > python library. >Not on remote locations. The only work on your local filesystem. >Diez Here's a function I wrote for checking remote or local file existence. It works for me but admittedly I haven't tested many cases with it. Also its currently specific to an http URI scheme. def fileExists(self, fileUrlPath): fileExists = False if "http:" in fileUrlPath.lower(): #We don't want to open the file so ask the header if the #file exists urlParts = urlparse(fileUrlPath) host = urlParts[1] http = httplib.HTTP(host) http.putrequest("HEAD", fileUrlPath) http.putheader("Host", host) http.endheaders() errorcode, errormessage, headers = http.getreply() if errorcode == 200: fileExists = True else: fileExists = path.exists(fileUrlPath) return fileExists -- Ivan Ven Osdel http://datasyncsuite.com From __peter__ at web.de Mon Aug 11 05:38:57 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 11 Aug 2008 11:38:57 +0200 Subject: benchmark References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> Message-ID: M8R-n7vorv at mailinator.com wrote: > On Aug 10, 10:10?pm, Kris Kennaway wrote: >> jlist wrote: >> > I think what makes more sense is to compare the code one most >> > typically writes. In my case, I always use range() and never use psyco. >> > But I guess for most of my work with Python performance hasn't been >> > a issue. I haven't got to write any large systems with Python yet, >> > where performance starts to matter. >> >> Hopefully when you do you will improve your programming practices to not >> make poor choices - there are few excuses for not using xrange ;) >> >> Kris > > And can you shed some light on how that relates with one of the zens > of python ? > > There should be one-- and preferably only one --obvious way to do it. For the record, the impact of range() versus xrange() is negligable -- on my machine the xrange() variant even runs a tad slower. So it's not clear whether Kris actually knows what he's doing. For the cases where xrange() is an improvement over range() "Practicality beats purity" applies. But you should really care more about the spirit than the letter of the "zen". Peter From weiguo6 at gmail.com Thu Aug 7 16:28:46 2008 From: weiguo6 at gmail.com (Wei Guo) Date: Thu, 7 Aug 2008 13:28:46 -0700 Subject: A question about string and float number In-Reply-To: References: <489A8A01.1050908@linkline.com> Message-ID: Hi I tried the first type method but it seens that it doesn't work. Could anyone help me about it? >>> s = '3.145' >>> type(s) == type(float()) False >>> type(s) >>> type(float()) >>> Best regards, Wei On 8/7/08, Wei Guo wrote: > > Hi Thanks for Tyler and Edwin's help. > > For my questions, I need to import some xml file and there are floating > number and strings in it. I need to process string and number differently. > This is reason that I am asking question here. Is this background > information we need for this quesions. > > Btw, which way is better? type or with exception ValueError? > > Thanks, > > Wei > > > On 8/6/08, Tyler Breisacher wrote: >> >> It's generally a bad idea to use "except" without naming a specific >> exception. The exception you might expect in this case is ValueError. Any >> other exception *should* be uncaught if it happens. By the way, this method >> will return true for integers as well as floats. For example, isFloat('3') >> will return 3.0. So make sure this is what you want, since it wasn't 100% >> clear from the original message. >> >> >> Wei Guo wrote: >> >>> #this is a better way of testing a string for float >>> def isFloat(s): >>> try: >>> s = float(s) >>> except: >>> return False >>> return True >>> >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From marco.bizzarri at gmail.com Sat Aug 30 13:48:10 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 30 Aug 2008 19:48:10 +0200 Subject: Counting Elements in an xml file In-Reply-To: <7dd68868-5490-464d-9cc1-ddf6a2c50dbe@l42g2000hsc.googlegroups.com> References: <7dd68868-5490-464d-9cc1-ddf6a2c50dbe@l42g2000hsc.googlegroups.com> Message-ID: <3f0d61c40808301048ra3a08f6l283790381686080b@mail.gmail.com> On Sat, Aug 30, 2008 at 7:37 PM, Ouray Viney wrote: > Hi All: > > I am looking at writing a python script that will let me parse a > TestSuite xml file that contains n number of TestCases. > > My goal is to be able to count the elements base on a key > value pair in the xml node. > > Example > > > > I would like to be able to count the number of TestCases that contain > the "execute=true" but not the ones that contain "execute=false". > > I have review the python docs and various python ebooks. > > Does anyone have any experience with this sort of thing? If so, could > you suggest a good library and possibly some samples? Isn't the SAX part of this howto http://pyxml.sourceforge.net/topics/howto/xml-howto.html enough for you to create your parser? Regards Marco -- Marco Bizzarri http://iliveinpisa.blogspot.com/ http://notenotturne.blogspot.com/ From hishaam.ab at gmail.com Wed Aug 13 08:04:34 2008 From: hishaam.ab at gmail.com (Hishaam) Date: Wed, 13 Aug 2008 05:04:34 -0700 (PDT) Subject: Regarding Telnet library in python Message-ID: <7412fd2f-b6b0-4b91-b05e-53b434d6fd2e@w24g2000prd.googlegroups.com> Hi, In python documentation, i found a telnet example as follows: ------------------------------------------------------------------------- import getpass import sys import telnetlib HOST = "localhost" user = raw_input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until("login: ") tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") tn.write("ls\n") tn.write("exit\n") print tn.read_all() ------------------------------------------------------------------------- The ouput of it as follows: ------------------------------------------------------------------------- Enter your remote account: root Last login: Mon Aug 13 11:54:32 from pcp246879pcs.ca Sun Microsystems Inc. SunOS 5.10 Generic January 2005 # Desktop boot hishaam net system work Documents cdrom home opt tfile2 zonemgr File.txt dev kernel platform tmp QA_tmp devices lib proc usr acunix etc lost+found sbin var bin export mnt sfile vol # ------------------------------------------------------------------------- The difficulty i find in this is th code line "print tn.read_all()" is used for reading all of the output of the code at once. Is there a possibility to read the stdout of each command by command like - # ls [capture in a variable] # cd /root [capture in a variable] Like the above would be useful if there are a large number of commands to be executed in the telnet session. Can anyone help on this? Regards, Hishaam From harrrrpo at gmail.com Sun Aug 24 06:11:03 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Sun, 24 Aug 2008 13:11:03 +0300 Subject: Imports visibility in imported modules problem In-Reply-To: <1bb81100-c8bb-48e6-b9f9-ce199d8198f1@m45g2000hsb.googlegroups.com> References: <1bb81100-c8bb-48e6-b9f9-ce199d8198f1@m45g2000hsb.googlegroups.com> Message-ID: <538050a90808240311k6c619b82g820ef75875262927@mail.gmail.com> On Sun, Aug 24, 2008 at 5:54 AM, Patrick Maupin wrote: > On Aug 23, 7:27 pm, "Mohamed Yousef" wrote: > >> The problem I'm asking about is how can imported modules be aware of >> other imported modules so they don't have to re-import them (avoiding >> importing problems and Consicing code and imports ) > > You could import sys and look at sys.modules no even if you imported sys or used dir you will see no re in W() from A . and you can even try to use re and will see >> why am i doing this in the first place I'm in the process of a medium >> project where imports of modules start to make a jungle and i wanted >> all needed imports to be in a single file (namely __init__.py) and >> then all imports are made once and other modules feel it > > This doesn't sound like a good idea. If A imports a module which is > automatically imported into B's namespace, that sounds like a > maintenance nightmare. why ? this saves time and consices whole package imports in one file and maintaining it is easier (eg. you will never have circuular imports) >> >> another reason to do this that my project is offering 2 interfaces >> (Console and GUI through Qt) and i needed a general state class ( >> whether i'm in Console or GUI mode) to be available for all , for >> determining state and some public functions ,and just injecting >> Imports everywhere seems a bad technique in many ways (debugging , >> modifying ...etc ) > > I still don't understand. put it another way a general variable in all modules and some functions visible in all modules >> in PHP "Require" would do the trick neatly ... so is there is >> something I'm missing here or the whole technique is bad in which case >> what do you suggest ? > > I don't know what to suggest, in that you haven't yet stated anything > that appears to be a problem with how Python works. If two different > modules import the same third module, there is no big performance > penalty. The initialization code for the third module is only > executed on the first import, and the cost of having the import > statement find the already imported module is trivial. it's not performance it's the jungle resulting many imports in every file and suppose i changed the module used in all modules name guess what , it will have to be renamed in every import to it in all modules From henhiskan at gmail.com Thu Aug 28 13:18:48 2008 From: henhiskan at gmail.com (Richard Rossel) Date: Thu, 28 Aug 2008 10:18:48 -0700 (PDT) Subject: epoch seconds from a datetime Message-ID: <40ab500b-f33f-4d6a-9c7c-fecee0119ba0@s50g2000hsb.googlegroups.com> Hi friends, I need a little help here, I 'm stuck with epoch calculation issue. I have this datetime: date_new = datetime(*time.strptime('20080101T000000','%Y%m%dT%H%M%S') [0:6]) This date_new is in UTC Now I need to know the seconds since epoch of this new date, so I run this: seconds = int(time.mktime(date_new.timetuple())) but the seconds returned belongs to : Tue, 01 Jan 2008 03:00:00 GMT because the localtime is in timezone 'America/Santiago': -3 I fix this trying to alter the TZ with time.tzset(): os.environ['TZ'] = 'UTC' time.tzset() .... and now I can gets the right epoch, but I can't restore the previous TimeZone, I try with: os.environ['TZ'] = '', but the time.tzset() doesn't back to the original ( America/Santiago) A solution should be set the os.environ['TZ'] to 'America/Santiago' but I can't make a TZ hardcode because the software should works on different timezones. So the question, how can restore the system into original timezone, or how to know the seconds since epoch from UTC datetime without change the local system TIMEZONE. please help From williamhpurcell at gmail.com Thu Aug 21 16:45:16 2008 From: williamhpurcell at gmail.com (William Purcell) Date: Thu, 21 Aug 2008 15:45:16 -0500 Subject: programming toolbox Message-ID: Hi all, I started programming with python about a year ago. I am now somewhat experienced with python but have virtually no experience with any other language. I use python to write little command line tools, GUI's to do anything from my time sheet at work to balancing my checkbook, and for school to do plotting and data manipulation. I was wondering what more experienced programmers think about what languages are necessary to be able to handle most programming problems. Another way to word the question is... Should I spend the time to learn C/C++ (or any other for that matter) or will Python handle most programming problems? Especially for applications that other people want to use and I need stability and speed. Just Curious, Bill P.S. If you do think it's worth learning C/C++...what type problems are fit for C/C++ and which should I keep with Python for? What are a couple languages that really complement python? -------------- next part -------------- An HTML attachment was scrubbed... URL: From adityashukla1983 at gmail.com Wed Aug 27 00:15:58 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Tue, 26 Aug 2008 23:15:58 -0500 Subject: Extracting path of a program from a list. Message-ID: <73045cca0808262115w71afa3adjc3565e204fd1d90f@mail.gmail.com> Hello folks, I wanna know how can i extract path of a program whose path i have added to the PATH variable. This is what i have done import os x=os.getenv("PATH") print x >>%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;c:\Program Files\Microsoft SQL Server\90\Tools\binn\;C:\Program Files\QuickTime\QTSystem\;C:\folder1\folder2\prog Now i have to extract the path of my program ie (C:\folder1\folder2\prog) .I mean i can split the string using y=x.split(';') a=y[-1] but i dont wanna do this way ,i wanna search for my program from this list and then return its path Please help me on this. Thanks in advance. Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Aug 14 11:47:23 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 17:47:23 +0200 Subject: for y in range (0,iNumItems)--> not in order? In-Reply-To: References: <8514d915-95bf-4e57-a16a-68866e0ad789@l42g2000hsc.googlegroups.com> Message-ID: korean_dave wrote: > Still the same output... > > Here's the actual code... > > for x in range(0,2): > for y in range(0,27): > for z in range(0,15): > print(str(x) + " " + str(y) + " " + str(z)) umm. that's even less related to your original output than your earlier code sample. $ python actual_code.py 0 0 0 0 0 1 0 0 2 0 0 3 0 0 4 ... 1 26 10 1 26 11 1 26 12 1 26 13 1 26 14 please do a little more debugging on your own machine before claiming that fundamental python features that's been around for ages suddenly won't work. From mail at timgolden.me.uk Sat Aug 9 18:34:51 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 09 Aug 2008 23:34:51 +0100 Subject: Win32 trouble with threading, signals, and sleep() In-Reply-To: <839ec5810808081817l4c47df87m2ed18edb54190dd4@mail.gmail.com> References: <839ec5810808081817l4c47df87m2ed18edb54190dd4@mail.gmail.com> Message-ID: <489E1B8B.9090603@timgolden.me.uk> Lowell Alleman wrote: > I'm running into this issue on Windows with the follow exception at > the time when the signal handler is called: > > Traceback (most recent call last): > ... > self.done.wait(30) > File "D:\Python24\lib\threading.py", line 348, in wait > self.__cond.wait(timeout) > File "D:\Python24\lib\threading.py", line 222, in wait > _sleep(delay) > IOError: [Errno 4] Interrupted function call Well you've certainly picked a ticklish area to run into problems with ;). First, forget about the threading aspects for the moment. AFAICT the smallest program which reproduces your problem is: import signal import time def handler (*args): pass signal.signal(signal.SIGBREAK, handler) time.sleep (10) Now run that and do a ctrl-break somewhere in that time.sleep. Sure enough... Traceback (most recent call last): File "C:\data\temp\sig3.py", line 8, in time.sleep (10) IOError: [Errno 4] Interrupted function call Under the covers, the sleep function is implemented as a WaitForSingleObject call with a timeout. The object being waited on is an anonymous event which is set from a console ctrl handler when one of those interrupts happens (ctrl-c / ctrl-break / shutdown). This makes sure that the (otherwise blocking) sleep can be interrupted. Something like this: import win32api import win32event hEvent = win32event.CreateEvent (None, 1, 0, None) def handler (*args): win32event.PulseEvent (hEvent) return True win32api.SetConsoleCtrlHandler (handler, 1) # # This line is basically the sleep happening # win32event.WaitForSingleObject (hEvent, 10000) For reasons which I'm not aware of, the code recognises that the interrupt has fired and sets the WSAEINTR error code, which is the IOError 4 which you're seeing, and then exits. EINTR is usually issued when a blocking call is cancelled explicitly, so presumably this is considered a simulation of that. Not sure. What happens now is that control passes back out to the routine which called the sleep. But... an exception condition has been set inside the sleep call and is now raised, appearing to come from within the routine which called sleep. Clear? You could obviously continue to catch the exception. Alternatively, I think your best bet, as long as you can make it work with the threads, is to install your own console ctrl handler. Note that the docs for this specify that: "When the signal is received, the system creates a new thread in the process to execute the function." So you'll need to be quite careful to make your code thread-safe. But it should work. I adapted your example slightly to replace all of the lines setting the signal handlers to one statement: win32api.SetConsoleCtrlHandler (handler, 1) and the handler function itself takes only one arg, the signal no, and returns False to indicate that control should pass to the next handler, which will probably be the default Python handler: def handler(arg): print "Signal handler", arg global workers for w in workers: w.stop() return False Hope that all helps. TJG From ronald.johnson at gmail.com Tue Aug 5 12:30:31 2008 From: ronald.johnson at gmail.com (ronald.johnson at gmail.com) Date: Tue, 5 Aug 2008 09:30:31 -0700 (PDT) Subject: Is there a faster way to do this? Message-ID: <8dbfab27-770e-44a5-b4db-12f67d21ab3f@t54g2000hsg.googlegroups.com> I have a csv file containing product information that is 700+ MB in size. I'm trying to go through and pull out unique product ID's only as there are a lot of multiples. My problem is that I am appending the ProductID to an array and then searching through that array each time to see if I've seen the product ID before. So each search takes longer and longer. I let the script run for 2 hours before killing it and had only run through less than 1/10 if the file. Heres the code: import string def checkForProduct(product_id, product_list): for product in product_list: if product == product_id: return 1 return 0 input_file="c:\\input.txt" output_file="c:\\output.txt" product_info = [] input_count = 0 input = open(input_file,"r") output = open(output_file, "w") for line in input: break_down = line.split(",") product_number = break_down[2] input_count+=1 if input_count == 1: product_info.append(product_number) output.write(line) output_count = 1 if not checkForProduct(product_number,product_info): product_info.append(product_number) output.write(line) output_count+=1 output.close() input.close() print input_count print output_count From fredrik at pythonware.com Tue Aug 19 11:04:18 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Aug 2008 17:04:18 +0200 Subject: who to call a list of method inside the class itself In-Reply-To: References: <95910272-2045-4170-ab6e-549489b12108@d77g2000hsb.googlegroups.com> Message-ID: maduma at pt.lu wrote: >>> def getAllMethod(self): >>> return [self.method1, self.method2, self.method3] >>> def applyAll(self): >>> for m in self.getAllMethod(): >>> # how to call all methods ? >>> # is it correct >>> m() >> what happens when you run the code? > The code it is running fine but i just wondering if it's the syntax is > correct (avoid any side effect) It's the same thing as explicitly calling the three methods from inside the applyAll method. You'll still get side effects if the methods have side effects, of course. self.method1 and friends are "bound methods", that is, callable objects that are bound to both the object instance (self) and the actual method. They're no different from the temporary bound methods that are used to carry out an ordinary method call ("self.method1()" is evaluated as "tmp = self.method1; tmp()" on the inside, where tmp is an internal variable) From dullrich at sprynet.com Tue Aug 5 11:47:07 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 05 Aug 2008 10:47:07 -0500 Subject: PIL (etc etc etc) on OS X References: <489379A7.5060009@codebykevin.com> <48948BBA.9050706@codebykevin.com> <489797fc$0$49816$e4fe514c@news.xs4all.nl> Message-ID: In article <489797fc$0$49816$e4fe514c at news.xs4all.nl>, Irmen de Jong wrote: > David C. Ullrich wrote: > > Just as well that the message sent earlier today > > seems to have been lost... > > > > Ok. Read your instructions on libjpeg. Read some > > of the install.doc. ./configure, fine. make, fine. > > "make test", fine. So I said "sudo make install" > > and this happened: > > > > 0-1d-4f-fc-28-d:jpeg-6b dullric$ sudo make install > > Password: > [...] > > I had to do the following to build and install it in a way such that PIL > would recognise > it. But it does now, without changing anything in PIL's setup files. > > $ cd jpeg-6b/ > $ ln -s `which glibtool` libtool > $ export MACOSX_DEPLOYMENT_TARGET=10.4 > $ ./configure --enable-shared --enable-static --host=powerpc > $ make > $ sudo make install Thanks - that gets me closer: I'd already found out about the --enable-* switches, but when I tried them it complained it couldn't find ./libtool. I _guessed_ host should be intel I changed the 10.4 to 10.5 and did this: $ ln -s `which glibtool` libtool $ export MACOSX_DEPLOYMENT_TARGET=10.4 $ ./configure --enable-shared --enable-static --host=intel $ make $ sudo make install That fixed the complaints about no ./libtool, great. Then I went back to PIL. The setup.py reported that everything was great, including JPEG. And then selftest.py said it couldn't find a jpeg decoder... 0-1d-4f-fc-28-d:Imaging-1.1.6 dullric$ python selftest.py ***************************************************************** Failure in example: _info(Image.open("Images/lena.jpg")) from line #24 of selftest.testimage Exception raised: Traceback (most recent call last): File "./doctest.py", line 499, in _run_examples_inner exec compile(source, "", "single") in globs File "", line 1, in File "./selftest.py", line 22, in _info im.load() File "PIL/ImageFile.py", line 180, in load d = Image._getdecoder(self.mode, d, a, self.decoderconfig) File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available 1 items had failures: 1 of 57 in selftest.testimage ***Test Failed*** 1 failures. *** 1 tests of 57 failed. > > (note that I have a PPC mac so the host parameter may not be correct for your > system) > --irmen -- David C. Ullrich From cito at online.de Fri Aug 15 14:53:57 2008 From: cito at online.de (Christoph Zwerschke) Date: Fri, 15 Aug 2008 20:53:57 +0200 Subject: Missing exceptions in PEP 3107 In-Reply-To: <1d08d8f1-abb7-4bf3-83a8-2a109dc62ce6@a3g2000prm.googlegroups.com> References: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> <1d08d8f1-abb7-4bf3-83a8-2a109dc62ce6@a3g2000prm.googlegroups.com> Message-ID: Matimus wrote: > Christoph wrote: >> Maybe the following syntax would be even more intuitive: >> >> def foo(a: "a info", b: "b info") return "ret info" raise "exc info": >> return "hello world" > > That seems much more intuitive and extensible. The "->" syntax has > always bothered me. The main issue I see with it though is that it > might be confusing. Consider: > > def foo(a, b) return 0: > > return a + b > > A person reading the code might be tempted to read the annotation and > think that it is the body. Maybe not a huge problem, but definitely > something that will come up occasionally. Yes, that's a drawback; and the same problem for a "raise" clause. >> Well, yes, but wasn't the whole point of PEP 3107 to get rid of such >> decorators and provide a single standard way of specifying this kind of >> info instead? > > Maybe, but I think it also does two more things: 1. creates a standard > location for storing annotations, and 2. Keeps you from violating DRY > (http://en.wikipedia.org/wiki/DRY). > Using a single decorator for exception info (or even return info) does > not violate either of the two stated benefits. The exception > information would go into the standard annotations dictionary. The > raises decorator does not violate DRY any more or less than it would > if added to the language syntax. That's a valid point, but as you already mentioned, the same applies to the return value. In my opinion it is desirable that either both return value and exceptions get a special syntax, or both must be described using decorators. -- Christoph From grommasher at gmail.com Wed Aug 6 23:15:11 2008 From: grommasher at gmail.com (Grom) Date: Wed, 6 Aug 2008 20:15:11 -0700 (PDT) Subject: Function from C/PHP to Python Message-ID: <814caf84-ec0e-4d15-810a-76a77e399e76@d45g2000hsc.googlegroups.com> Hello everyone :) I have one problem with that function in C int calc_passcode(const char* pass, char* code) { int magic1 = 0x50305735; int magic2 = 0x12345671; int sum = 7; char z; while ((z = *pass++) != 0) { if (z == ' ') continue; if (z == '\t') continue; magic1 ^= (((magic1 & 0x3f) + sum) * z) + (magic1 << 8); magic2 += (magic2 << 8) ^ magic1; sum += z; } magic1 &= 0x7fffffff; magic2 &= 0x7fffffff; return sprintf(code, "%08x%08x", magic1, magic2); } // end _calc_passcode(); Can someone help me to rewrite it to python? There is the same function, in PHP: function _calc_passcode($pass) { $magic1 = 0x50305735; $magic2 = 0x12345671; $sum = 7; for ($i = 0; $i < strlen($pass); $i++) { $z = ord($pass[$i]); if ($z == 32) continue; if ($z == 9) continue; $magic1 = $magic1 ^ (((($magic1 & 0x3f) + $sum) * $z) + ($magic1 << 8)); $magic2 = $magic2 + (($magic2 << 8) ^ $magic1); $sum += $z; $magic1 = $magic1 & 0x7fffffff; $magic2 = $magic2 & 0x7fffffff; } return sprintf('%08x%08x', $magic1, $magic2); } // end _calc_passcode(); Please... its very important to me From kiruta at gmail.com Sun Aug 24 16:24:09 2008 From: kiruta at gmail.com (akva) Date: Sun, 24 Aug 2008 13:24:09 -0700 (PDT) Subject: semantics of the |= operator References: <16f69c9c-386f-41a3-852a-cd482327fc2d@c58g2000hsc.googlegroups.com> <905d2c92-86fe-484c-820e-bf5b853be28f@m3g2000hsc.googlegroups.com> <6h8c0gFk3g8hU1@mid.individual.net> Message-ID: <38202519-3a0e-4978-a6e6-1fdf3153849f@v57g2000hse.googlegroups.com> thanks everybody. From half.italian at gmail.com Wed Aug 20 02:24:20 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Tue, 19 Aug 2008 23:24:20 -0700 (PDT) Subject: searching through a string and pulling characters References: <19039594.post@talk.nabble.com> Message-ID: On Aug 19, 6:11?am, Wojtek Walczak wrote: > On Mon, 18 Aug 2008 15:34:12 -0700 (PDT), Alexnb wrote: > > Also, on a side-note, does anyone know a very simple dictionary site, that > > isn't dictionary.com or yourdictionary.com. > > This one is my favourite:http://www.lingro.com/ > > -- > Regards, > Wojtek Walczak,http://tosh.pl/gminick/ Thats hot! From tedpottel at gmail.com Wed Aug 20 08:42:34 2008 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: Wed, 20 Aug 2008 05:42:34 -0700 (PDT) Subject: TRying to read sercah results from googles web page Message-ID: Hi, I am trying to write a BOT to read the search results from Google. When I read from the www.google.com, the code works fine, loads in the web page. When I try to load in a url with the search results, http://www.google.com/search?hl=en&q=ted', I get a web page that says I do not have permissions. Is theree a way around this, or is Google just to smart???? the program looks like this import urllib print "-------- Google Web Page --------" print urllib.urlopen('http://www.google.com//').read() print "-------- Google Search Web Page --------" print urllib.urlopen('http://www.google.com/search? hl=en&q=ted').read() From dudeja.rajat at gmail.com Sat Aug 30 09:23:52 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 30 Aug 2008 14:23:52 +0100 Subject: How to delete elements from Tix Combo Box? Message-ID: HI, I'm using a Tix combo box (I call it combo2), the contents of which are loaded depeding on the selection in another Tix combo box(I call it combo1) I have used the commands: self.cbAnalysisLibVersion.insert(END, results) to insert elements to the combo box. I'm looking for some similar option to delete elements from the combo box. I mean, as soon as I change selection in combo1 the previous elements in the combo2 should get cleared up( or deleted) and | shall be able to the above insert command to add new elements to the combo2 ( depending upon selection in combo1) Please suggest how can I clear up the ( delete the entries) in combo2. Thanks and regards, Rajat From mail at timgolden.me.uk Thu Aug 28 04:26:23 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 28 Aug 2008 09:26:23 +0100 Subject: calling NetShareEnum win32api with ctypes In-Reply-To: References: Message-ID: <48B6612F.5050905@timgolden.me.uk> taghi wrote: > I wrote this code in python 2.5: > > from ctypes import * ... snip ... > netapi32=cdll.LoadLibrary('netapi32.dll') This is your problem: netapi32 is a windows DLL and needs to be attached as such: netapi32 = windll.LoadLibrary ("netapi32.dll") or, more simply: netapi32 = windll.net32api But see my other post re this function in pywin32 TJG From bart at at.vandeenensupport.punt.com.invalid Fri Aug 22 05:41:18 2008 From: bart at at.vandeenensupport.punt.com.invalid (Bart van Deenen) Date: Fri, 22 Aug 2008 11:41:18 +0200 Subject: def X(l=[]): weirdness. Python bug ? References: <8824d$48ae83b2$18847a51$1995@news.chello.nl> Message-ID: <677cb$48ae8a20$18847a51$6106@news.chello.nl> Hi Thanks all for your answers. I figured your solution already, but now I understand where the behavior is from. One question remains: can I find my parameter 'l' somewhere? I looked in a lot of objects, but couldn't find it. Thanks Bart. cokofreedom at gmail.com wrote: > On Aug 22, 11:13 am, Bart van Deenen > wrote: >> >> # function >> def X(l=[]): >> l.append(1) >> print l >> >> # first call of X >> X() >> [1] >> >> #second call of X >> X() >> [1, 1] >> >> Where does the list parameter 'l' live between the two successive calls >> of X(). Why is it not recreated with an empty list? >> Is this correct behavior or is it a Python bug? >> Does anyone have any pointers to the language documentation where this >> behavior is described? >> > "Default parameter values are evaluated when the function definition > is executed." > > Depending on your use the common way to handle this is to do > > def x(lst = None): > if lst is None: > pass # lst has not been set to anything > else: > pass # lst has been set to something From jkrukoff at ltgc.com Wed Aug 6 15:46:27 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Wed, 06 Aug 2008 13:46:27 -0600 Subject: Best practise implementation for equal by value objects In-Reply-To: <135eb396-6daa-4ff4-a722-253ba149889c@27g2000hsf.googlegroups.com> References: <135eb396-6daa-4ff4-a722-253ba149889c@27g2000hsf.googlegroups.com> Message-ID: <1218051988.25651.19.camel@jmk> On Wed, 2008-08-06 at 05:50 -0700, Slaunger wrote: > Hi, > > I am new here and relatively new to Python, so be gentle: > > Is there a recommended generic implementation of __repr__ for objects > equal by value to assure that eval(repr(x)) == x independet of which > module the call is made from? > > Example: > > class Age: > > def __init__(self, an_age): > self.age = an_age > > def __eq__(self, obj): > self.age == obj.age > > def __repr__(self): > return self.__class__.__name__ + \ > "(%r)" % self.age > > age_ten = Age(10) > print repr(age_ten) > print eval(repr(age_ten)) > print eval(repr(age_ten)).age > > Running this gives > > Age(10) > Age(10) > 10 > > Exactly as I want to. > > The problem arises when the Age class is iomported into another module > in another package as then there is a package prefix and the above > implementation of __repr__ does not work. > > I have then experimented with doing somthing like > > def __repr__(self): > return self.__module__ + '.' + self.__class__.__name__ + > "(%r)" % self.age > > This seems to work when called from the outside, but not from the > inside of the module. That is, if I rerun the script above the the > module name prefixed to the representation I get the following error > > Traceback (most recent call last): > File "valuetest.py", line 15, in > print eval(repr(age_ten)) > __main__.Age(10) > File "", line 1, in > NameError: name '__main__' is not defined > > This is pretty annoying. > > My question is: Is there a robust generic type of implementation of > __repr__ which I can use instead? > > This is something I plan to reuse for many different Value classes, so > I would like to get it robust. > > Thanks, > Slaunger > -- > http://mail.python.org/mailman/listinfo/python-list Are you really sure this is what you want to do, and that a less tricky serialization format such as that provided by the pickle module wouldn't work for you? -- John Krukoff Land Title Guarantee Company From rafesacks at gmail.com Tue Aug 19 13:31:06 2008 From: rafesacks at gmail.com (Rafe) Date: Tue, 19 Aug 2008 10:31:06 -0700 (PDT) Subject: exception handling in complex Python programs References: Message-ID: On Aug 20, 12:19 am, eliben wrote: > Python provides a quite good and feature-complete exception handling > mechanism for its programmers. This is good. But exceptions, like any > complex construct, are difficult to use correctly, especially as > programs get large. > > Most of the issues of exceptions are not specific to Python, but I > sometimes feel that Python makes them more acute because of the free-n- > easy manner in which it employs exceptions for its own uses and allows > users to do the same. > > Now, what do I mean more specifically... When a program starts growing > large, I find myself a bit scared of all the exceptions that might be > thrown: Python's exceptions as a result of runtime-detection of errors > (Python's dynamic typing also comes into play here), exceptions from > libraries used by the code, and exceptions from my lower-level > classes. > Python doesn't allow to specify which exceptions are thrown (C++'s > feature adding 'throw' after a function/method declaration specifying > the exceptions that can be thrown), and this leaves me at loss - what > should be caught and where ? Which errors should be left to > propagate ? > > I've tried looking around the Python blogosphere, but there doesn't > seem to be much concern with this topic. > > Apologies for the not-too-coherent post, but I suspect you feel the > pain too and can understand my meaning. > > Eli > > P.S. There's a common case where a method is passed a filename, to do > something with a file (say, read data). Should the method catch the > errors possibly thrown by open(), or leave it to the caller ? > > P.P.S. There's a great post on conditions (Common Lisp's exceptions) > here:http://dlweinreb.wordpress.com/2008/03/24/what-conditions-exceptions-... > Not really CL specific, and can apply to Python's exceptions. Maybe I am oversimplifying (and I am here to learn), but I catch all exceptions which otherwise would be hard to understand as a user. In other words, when a better error message is useful. Again, this is probably too simple to help, but the only way to ignore certain types of exceptions, as far as I know, is to catch them and pass. e.g. this ignores type errors... try: somethingBad() except TypeError, err: pass except Exception, err: raise TypeError(err) I suppose you could write a decorator to do this if you want it at the function level, but that seems a bit to broad. Shouldn't exceptions be on a case-by-case basis to add protection and return information exactly where it is needed? - Rafe From steve at REMOVE-THIS-cybersource.com.au Mon Aug 4 19:12:49 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2008 23:12:49 GMT Subject: Check if module is installed References: <813a0a6f-2f4d-482a-a3c4-5664798c5c26@f63g2000hsf.googlegroups.com> Message-ID: <00a7883e$0$20302$c3e8da3@news.astraweb.com> On Mon, 04 Aug 2008 05:25:08 -0700, Kless wrote: > How to check is a library/module is installed on the system? I use the > next code but it's possivle that there is a best way. > > ------------------- > try: > import foo > foo_loaded = True > except ImportError: > foo_loaded = False > ------------------- The "best" way depends on what you expect to do if the module can't be imported. What's the purpose of foo_loaded? If you want to know whether foo exists, then you can do this: try: foo except NameError: print "foo doesn't exist" Alternatively: try: import foo except ImportError: foo = None x = "something" if foo: y = foo.function(x) If the module is required, and you can't do without it, then just fail gracefully when it's not available: import foo # fails gracefully with a traceback Since you can't continue without foo, you might as well not even try. If you need something more complicated: try: import foo except ImportError: log(module not found) print "FAIL!!!" sys.exit(1) # any other exception is an unexpected error and # will fail with a traceback Here's a related technique: try: from module import parrot # fast version except ImportError: # fallback to slow version def parrot(s='pining for the fjords'): return "It's not dead, it's %s." % s -- Steven From gminick at nie.ma.takiego.adresu.w.sieci.pl Tue Aug 12 04:45:07 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Tue, 12 Aug 2008 08:45:07 +0000 (UTC) Subject: Looking out a module for Subversion References: Message-ID: Dnia Tue, 12 Aug 2008 04:25:50 -0400, Dudeja, Rajat napisa?(a): > Hi, > > I'm new to Python. I only have read "Byte of Python" by Swaroop C H just > to be familiar with sytax of python. I've installed Python 2.5 from > Active State and using its PythonWin Editor / interpreter. This, > unfortunaltely, does not help in debugging. > > I'm looking for an open source IDE / editor that has source level > debugging. Please suggest some tool. > > I'm intending to write a testing tool that uses Subversion. Is there > some module available for subversion, out of the box, that I can import > in my script? There is no such module in standard library, but you can try an external one. Check: http://pysvn.tigris.org/ -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From williamhpurcell at gmail.com Tue Aug 12 13:46:31 2008 From: williamhpurcell at gmail.com (William Purcell) Date: Tue, 12 Aug 2008 12:46:31 -0500 Subject: Checking a file's time stamp. Message-ID: Hi all, I am wanting to check to see the last time a file was edited. For example, I have a directory containing two text files, file1.txt and file2.txt. I want to be able to process these files but only if they have been edited since the last time they were processed. I think that I want to be able to check the time stamp of each file. Can anyone tell me how to do that or point me in a better direction of checking the last time a file was edited? Thanks, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Aug 22 00:56:44 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 21 Aug 2008 21:56:44 -0700 (PDT) Subject: Address-Of operator equivalent, PAVL search tree References: <82007443-29e3-47ae-8928-554b4170947b@z72g2000hsb.googlegroups.com> Message-ID: <3857fcf8-120a-4577-a017-967fadb14f36@m73g2000hsh.googlegroups.com> On Aug 21, 11:03?pm, castironpi wrote: > Hi, > > I am translating the GNU library's PAVL search tree implementation > into Python. ?I can't use it directly because a delete function I need > uses a different method of finding the node to delete. > > It contains this line: > > ? ? ? q = (struct pavl_node *) &tree->pavl_root; > > line 276 in http://www.sfr-fresh.com/unix/misc/avl-2.0.3.tar.gz:a/avl-2.0.3/pavl.c It seems the only property that's accessed is q->pavl_link[ 0 ], done in order to generically set the tree's root along with other nodes. I will use a proxy class to reroute set operations on q.link[ 0 ] to tree.root. It is also accessible via q.left. Here is a tentative implementation: class RootProxy: __slots__= '_tree' class RootLink: __slots__= '_tree' def __init__( self, tree ): self._tree= tree def __getitem__( self, key ): assert key== 0 return self._tree.root def __setitem__( self, key, val ): assert key== 0 self._tree.root= val def __init__( self, tree ): self._tree= tree def _getleft( self ): return self._tree.root def _setleft( self, val ): self._tree.root= val left= property( _getleft, _setleft ) def _getlink( self ): return self.RootLink( self._tree ) link= property( _getlink ) The line then becomes: > q = (struct pavl_node *) &tree->pavl_root; q= RootProxy( tree ) Thanks for your attention. Any questions or comments please share. From fredrik at pythonware.com Mon Aug 18 04:51:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 18 Aug 2008 10:51:25 +0200 Subject: Bizarre method keyword-arg bug. In-Reply-To: References: Message-ID: Jasper wrote: > I'm stumped. I'm calling a method that has keyword args, but not > setting them, and yet one of them starts off with data?! > > The class definition begins like so: > > class BattleIntentionAction( BattleAction ): > def __init__( self, factionName, location, tactic='hold', > targetFacName='', terrainArgs=[], garrisonIds=[] ): > self.terrainArgs = terrainArgs > print terrainArgs > > The constructor is called somewhere else, like so: > act = BattleIntentionAction( facName, self.location ) > > During this object's construction, terrainArgs is set to a list with > values corresponding to a previously created BattleIntentionAction! default argument values are evaluated when the function object is created (by the "def" statement, that is), not when the resulting function is called. if you mutate the default values, the mutations will stick. this is explained in the FAQ, the tutorial, and the reference manual, and hopefully in your favourite python book as well; see e.g. http://docs.python.org/tut/node6.html#SECTION006710000000000000000 http://docs.python.org/ref/function.html From Lie.1296 at gmail.com Sat Aug 30 13:01:12 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 30 Aug 2008 10:01:12 -0700 (PDT) Subject: Which is faster? References: Message-ID: On Aug 30, 5:30?pm, cnb wrote: > how does doing something twice not change complexity? yes it maybe > belongs to the same complexity-class but is still twice as slow no? Who is doing something twice? Definitely not sum(). sum() does not create intermediate list, and if you pass generator expressions in it you wouldn't make any intermediate list at all, thus simple looping but in interpreter code. sum() that is passed a list comprehension should be faster for extremely small numbers of values to sum, but we don't care about small things, do we? But using intermediate list should be fast enough for even large numbers of values, the time when it can't cope anymore would be when the intermediate list takes half of your memory (how often is that for regular applications?). From slfdsasdssaf at spam.not Wed Aug 27 21:51:52 2008 From: slfdsasdssaf at spam.not (RgeeK) Date: Wed, 27 Aug 2008 21:51:52 -0400 Subject: Global var access in imported modules? In-Reply-To: References: <48b5b72f$1@news.alcatel.com> Message-ID: Dennis Lee Bieber wrote: > On Wed, 27 Aug 2008 16:21:03 -0400, RgeeK > declaimed the following in comp.lang.python: > >> I have a main module doStuff.py and another module utility.py. At the >> start of doStuff.py I call >> >> import utility.py > > I hope not... import utility no .py >> Then I also proceed to initiallize some global variables >> > Python does not have global variables. Names belong within a module > (or within functions defined within the module). > >> sName = "" >> >> Then I create a class, some methods etc. In one of the methods I assign >> a value to my variable sName. Then I call a function from within >> my utility.py file: >> >> utility.makeOne(stuff) >> >> >> Within my utility.py file, I define the makeOne function. But I want to >> use that same global variable "sName" In utility.py I have tried to >> indicate that I'm using the global "sName" through the statement: >> >> global sName >> > The global statement is only used within functions (def blocks) to > indicate that "writes" to the specified name are to modify the MODULE > level version of the name, otherwise a write modifies a function local > version of the name (you don't need global for read-only access of > names, the search for names first looks inside the function, then out to > the module) > >> But when I go to use the variable it still gives me an error: >> >> NameError: global name 'sName' is not defined >> >> I thought perhaps I need to indicate 'globality' in my main module, so >> before I initiallized sName in doStuff.py I added: >> >> global sName >> >> But it doesn't help me. I had this issue before and resolved it by >> declaring the variable global in the sub-module utility.py, but then I >> needed to reference it in my main module with a prefix: >> >> utility.sName = "" >> >> It's more verbose,and defining globals in a submodule seems backward. >> But also, what if I need to access "sName" in another imported module, >> say "otherstuff.py"? I would do my "import otherstuff" call in my main >> module, but would I have to put an "import utility" into the >> otherstuff.py file? >> > If you really need "globals" the common solution is to create a > module such as "myglobals", define all the shared names within that > module, and import that module where ever you need access to one of the > names. And yes, you will need to qualify all those names with the module > name (though you can do things like: > > import myglobals as mg > > and then use > > mg.somename > > instead of > > myglobals.somename) > Thanks for the reply. Good to see that approach has broad support :) I'll do that. I like the idea of a nice short alias for the import to keep the qualifications brief. Ross. From grante at visi.com Fri Aug 15 11:10:41 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 15 Aug 2008 10:10:41 -0500 Subject: How do I control output buffering on Win32? References: <1I-dndTLBfGbCjjVnZ2dnUVZ_hCdnZ2d@posted.visi> Message-ID: On 2008-08-15, Fredrik Lundh wrote: > Grant Edwards wrote: > >> When I ssh in to my Windows XP box and run Python apps, output >> from "print" and and "sys.stdout.write()" is being buffered so >> that none of the output shows up until the program exits. >> >>>From within my program how do I set output buffering to either >> line-buffered or un-buffered? [I'm looking for the equivalent >> of the C stdio "setbuf" call.] > > I'm not sure you can do that from within the program [1]; to > do it from the outside, set the PYTHONUNBUFFERED environment > variable to something, or pass "-u" to the interpreter. I had seen references to PYTHONUNBUFFERED in my Google search, but it wasn't mentioned when I did a "python -h" -- so I assumed it was a Unix-only thing. > 1) well, I suppose you could replace sys.stdout with a thin > wrapper that does flush after each write, or play with > os.fdopen. I thought about that, but it seemed like there ought to be an easier, more obvious way. Is there some technical reason a Python program can't control the output buffering the way a C program can with setvbuf()? Or is it just something that's only wanted by weird people who do things like ssh into Windows boxes? That raises another question: what is the criteria that Python is using when it decides to run my program in block-buffered mode instead of line- or un-buffered mode? -- Grant Edwards grante Yow! I've read SEVEN at MILLION books!! visi.com From michaelmackus at gmail.com Sat Aug 16 03:40:27 2008 From: michaelmackus at gmail.com (Sonolin) Date: Sat, 16 Aug 2008 00:40:27 -0700 (PDT) Subject: You advice please References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> Message-ID: <1c03fef3-3abd-4369-962f-3773652fc785@z11g2000prl.googlegroups.com> On Aug 13, 4:14?am, Hussein B wrote: > Hey, > I'm a Java/Java EE developer and I'm playing with Python these days. > I like the Python language so much and I like its communities and the > Django framework. > My friends are about to open a Ruby/Rails shop and they are asking me > to join them. > I don't know what, sure I'm not leaving Java, but they are asking me > to stop learning Python and concentrate on Ruby/Rails. > The sad fact (at least to me), Ruby is getting a lot of attention > these days. > Why Python isn't getting this attention although is a much more mature > language and it is used by many big, big names? > And do I dare to say it is much more charming? > What do you think of Ruby/Rails? do they worth learning and working > with? > Any way, I'm not leaving Python and I will try to study it every time > I get a chance... > Thanks. Generally when developing something these days (Web App or not) I have found that the programming language really does not have a huge affect on the success of the product. If the developers are dedicated, they can generally make most programming languages work. It just comes down to what you prefer, or if something clearly is better than the others use it if at all possible. For example, when programming a game, you could easily code it in Python, or C++. Sure, C++ would be faster, but sometimes these days speed is not a large factor. And you can always just code the complex calculations in C, and the rest in Python. So, in short, if you are up to the challenge - take it. I do not know Ruby (at ALL), but if some of my friends wanted to develop a RoR app I would not turn them down for the language choice (Ruby). There has been successful Web Apps made in Ruby, Python, PHP, Perl, Java, etc. - they all have their place. I would much rather code in Python than in PHP, but most of my Web Programming is done in PHP due to client preference. And as for being afraid of "abandoning" Python... I know many programming languages, and have not abandoned my favorites. Just because I know how to code in Visual Basic does not mean I do regularly. Hopefully this made some sense - pretty tired ;) -- http://designandprogram.com http://twitter.com/sonolin From deets at nospam.web.de Sun Aug 31 03:41:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 31 Aug 2008 09:41:30 +0200 Subject: Mako --> Genshi In-Reply-To: <20080830205904.725f1bef@mail.asciiking.com> References: <20080830205904.725f1bef@mail.asciiking.com> Message-ID: <6hv09bFnvm0eU1@mid.uni-berlin.de> Chris Babcock schrieb: > Is there a cheap way to convert Myghty/Mako templates to Kid/Genshi? > There's some code written for Pylons that I want to incorporate into a > TurboGears 2 project and Genshi templates are more likely to behave > themselves with the tools I'm used to. Not that I'm aware of. And I think it's impossible to reliably do that, because mako allows broken XML or "pure" HTML, whereas KID/Genshi require well-formed XML. Diez From jeffober at gmail.com Mon Aug 4 12:45:20 2008 From: jeffober at gmail.com (Jeff) Date: Mon, 4 Aug 2008 09:45:20 -0700 (PDT) Subject: Bidirectional Generators References: <8e2cf6b7-4b5f-4701-8a4c-bc779ed7305c@m45g2000hsb.googlegroups.com> <976df308-3855-4f2b-a82a-dacba480e7d7@i76g2000hsf.googlegroups.com> <4f1ac687-2401-4ee7-acd9-b0eb3ef8e910@v39g2000pro.googlegroups.com> Message-ID: <914d16b4-efee-45cc-9751-b8156bdd943f@w7g2000hsa.googlegroups.com> On Aug 4, 12:39?pm, william tanksley wrote: > Paddy wrote: > > What's one of them then? > > I'm sorry, I don't know what you mean. > > Meanwhile, more pertinently: I did get my generator working, and then > I replaced it with a class that did the same thing in less than a > quarter of the number of lines. So... I'm not going to worry about > that anymore. My use case obviously wasn't the right one for them. > > I'm still curious, though, whether anyone's written any code that > actually uses yield _and_ send() to do anything that isn't in the > original PEP. > > > - Paddy. > > -Wm I have. An iterator that could backtrack itself without the user having to remember previous states. It would just send back something like reader.send('prev_token') or reader.send(-1). From jonas.esp at googlemail.com Sun Aug 3 04:12:18 2008 From: jonas.esp at googlemail.com (Kless) Date: Sun, 3 Aug 2008 01:12:18 -0700 (PDT) Subject: base-96 References: <094aaf8f-0d16-4f85-abd5-232f475b9785@x35g2000hsb.googlegroups.com> Message-ID: On 3 ago, 00:33, Terry Reedy wrote: > seehttp://en.wikipedia.org/wiki/Base-85 > for something more practical In this thread [1] --a mirror group of python-dev mailing list-- where I sent the same post, has been named too that enconding way. [1] http://groups.google.com/group/python-dev2/browse_thread/thread/c843ecf222948167 From claird at lairds.us Fri Aug 29 07:44:41 2008 From: claird at lairds.us (Cameron Laird) Date: Fri, 29 Aug 2008 11:44:41 +0000 Subject: Python in a Nutshell -- Book vs Web References: Message-ID: <924lo5-9u7.ln1@lairds.us> In article , Fredrik Lundh wrote: >Cameron Laird wrote: > >> No. No, to an almost libelous extent. > >No matter what you write about, there's always a certain subcategory of >potential readers who insist that collection, editing, filtering, >structuring, clarification, and the author's real-life experience of the >topic he's writing about has no value at all. My guess is that they >don't value their own time very highly. > > > Insightful. Well, I find it insightful; perhaps it's a personal blindness on my part. I expect programmers to understand, for example, that two lines of code can be a good day's production, in some circumstances, while it's "civilians" and managers who scorn their value on quantitative grounds. It's hard for me to conceive of an expert programmer who doesn't esteem what a high-quality book provides. From bidihall at gmail.com Fri Aug 29 18:44:32 2008 From: bidihall at gmail.com (BiDi) Date: Fri, 29 Aug 2008 15:44:32 -0700 (PDT) Subject: subclassing complex References: <3ce33299-e13c-4ce0-8a09-eab6d0359033@a3g2000prm.googlegroups.com> <0b908015-59c2-4dc9-a279-e42ce920fe03@d45g2000hsc.googlegroups.com> Message-ID: On Aug 30, 6:18?am, Patrick Maupin wrote: > On Aug 29, 4:24 am, Peter Otten <__pete... at web.de> wrote: > > > > > A minimal example is > > > >>> class Complex(complex): > > > ... ? ? def __radd__(self, other): print "radd" > > ...>>> 1j + Complex() > > > 1j > > > versus > > > >>> class Int(int): > > > ... ? ? def __radd__(self, other): print "radd" > > ...>>> 1 + Int() > > > radd > > > I think the complex subclass should behave like the int subclass. > > To get an authoritative answer you should file a bug report. > > Hmm, good point. ?I shouldn't look at newsgroups when I'm too tired to > see the whole problem. > > According to the documentation athttp://docs.python.org/ref/numeric-types.html: > > "Note: If the right operand's type is a subclass of the left operand's > type and that subclass provides the reflected method for the > operation, this method will be called before the left operand's non- > reflected method. This behavior allows subclasses to override their > ancestors' operations." > > I think this makes it pretty clear that the OP found a bug in how > complex works. ?(Before I read this note, I would have assumed that > the int() handling was broken, but it looks like a supportable design > decision. ?Probably whoever implemented it wasn't even thinking about > complex numbers, but for consistency, I would think they should be > made to work the same.) > > Regards, > Pat Thanks for the comments. I have filed it as an issue. Regards Blair From lee.walczak at gmail.com Mon Aug 18 08:47:39 2008 From: lee.walczak at gmail.com (lee.walczak at gmail.com) Date: Mon, 18 Aug 2008 05:47:39 -0700 (PDT) Subject: configuring temporary entry widget of TableList Cell using Python Message-ID: Hi, I am using Tkinter & the Kevin Walzer's TableList Wrapper for python implemented GUI: http://tkinter.unpythonic.net/wiki/TableListWrapper The TableList has been extremely useful in allowing me to create my GUI for my engineering requirements, but I have hit a brick wall and need some assistance. "I am unable to configure the Temporary Embedded ComboBox List when the specific TableList cell is selected for editing" I have a registered the Bwidget Combobox widget so I can use this as an alternative temporary Entry Widget ( depending on the specific cell usage) thanks to some assistance from Kevin Walzer ( Many thanks ). I configure the particular cell's edit window (-editwindow ) for ComboBox which is working successfully. The problem I have is I wish to change the "-values" of the Temporary Combobox Widget i.e. a List that I can specify. When my "-editstartcommand" is called I firstly get the pathname of the Temporary Embedded Widget using, TEW = editwinpath() I am then assuming (although I must be wrong!) that I can then do: TEW.configure( values=("my","list","of","Strings")) However, this leads to the exception error -> TEW does not contain such an attribute "configure". My reference for this procedure is (http://objectmix.com/tcl/377931- communicating-tablelist-embedded-widgets.html but also available from tcl.tk tablelist coding examples) : proc editStartCmd {tbl row col text} { set w [$tbl editwinpath] switch [$tbl columncget $col -name] { currency { # # Populate the ComboBox and make it non-editable # $w configure -values {Dollar Euro Yen ...} -editable no } . . . } return $text } It is this procedure I am trying to replicate in Python. Is it possible to guide help tell me the right approach here. Of course I can submit my code to help ( if this is useful ) but the problem I think clear to see from these summary details. Please take it easy on me, I am a HW engineer by trade and am slowly (but surely) gaining more knowledge & experience in the world of Python (and of course Tkinter)! B.Regards, Lee Walczak From h.goebel at goebel-consult.de Wed Aug 27 14:05:00 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Wed, 27 Aug 2008 20:05:00 +0200 Subject: Split function for host:port in standard lib In-Reply-To: <7nado5-0a4.ln1@nb2.stroeder.com> References: <7nado5-0a4.ln1@nb2.stroeder.com> Message-ID: <48b5974c$0$11749$9b4e6d93@newsspool1.arcor-online.net> Michael Str?der schrieb: > Examples IPv6 addresses: > '::1:389' -> ('::1',389) > '::1' -> ('::1',None) These are wrong, see http://tools.ietf.org/html/rfc2732 ("Format for Literal IPv6 Addresses in URL's?). Correct formats are: [::1]:389 [::1] From emile at fenx.com Thu Aug 7 18:43:50 2008 From: emile at fenx.com (Emile van Sebille) Date: Thu, 07 Aug 2008 15:43:50 -0700 Subject: Fastest way to store ints and floats on disk In-Reply-To: <489B41CE.8080909@shopzeus.com> References: <489B41CE.8080909@shopzeus.com> Message-ID: Laszlo Nagy wrote: > > Hi, > > I'm working on a pivot table. Hmm... I wrote an browser based analysis tool and used the working name pyvot... I found Numeric to provide the best balance of memory footprint and speed. I also segregated data prep into a separate process to avoid excessive memory use at run time. Turns out python For the site I'm at, I've got 10 years sales history recapped from 4327846 detail records into 458197 item by customer by month records and top shows a 240Mb memory footprint. I've got 21 cross indexed selection fields, and can display up to six data types (qty, price, sqft, cost, gp%, avg). At another site I've got approx 8.5M records recapped into 1M records with 15 indexes and 5 years monthly history living in a 540Mb memory footprint. It's reasonably quick: a query like 'select san mateo, foster city and san carlos accounts, sort by customer and product category and display this year's sales by month' selects 260 records and renders in the browser in about 2 seconds. Or on the larger installation 'Show sales for the past five years for product group 12 sorted by city within route' selects 160 records and renders in about 3 seconds. My objective was to keep the info in memory for fast response times. I played a lot of games getting this all to work well, including some c extensions, but Numeric's take, sum, tostring and fromstring ended up with 'pivotal' roles. :) Regards, Emile > I would like to write it in Python. I > know, I should be doing that in C, but I would like to create a cross > platform version which can deal with smaller databases (not more than a > million facts). > > The data is first imported from a csv file: the user selects which > columns contain dimension and measure data (and which columns to > ignore). In the next step I would like to build up a database that is > efficient enough to be used for making pivot tables. Here is my idea for > the database: > > Original CSV file with column header and values: > > "Color","Year","Make","Price","VMax" > Yellow,2000,Ferrari,100000,254 > Blue,2003,Volvo,50000,210 > > Using the GUI, it is converted to this: > > dimensions = [ > { 'name':'Color', 'colindex:0, 'values':[ 'Red', 'Blue', 'Green', > 'Yellow' ], }, > { 'name':'Year', colindex:1, 'values':[ > 1995,1999,2000,2001,2002,2003,2007 ], }, > { 'name':'Make', colindex:2, 'value':[ 'Ferrari', 'Volvo', 'Ford', > 'Lamborgini' ], }, > ] > measures = [ > { 'name', 'Price', 'colindex':3 }, > { 'name', 'Vmax', 'colindex':4 }, > ] > facts = [ > ( (3,2,0),(100000.0,254.0) ), # ( dimension_value_indexes, > measure_values ) > ( (1,5,1),(50000.0,210.0) ), > .... # Some million rows or less > ] > > > The core of the idea is that, when using a relatively small number of > possible values for each dimension, the facts table becomes > significantly smaller and easier to process. (Processing the facts would > be: iterate over facts, filter out some of them, create statistical > values of the measures, grouped by dimensions.) > > The facts table cannot be kept in memory because it is too big. I need > to store it on disk, be able to read incrementally, and make statistics. > In most cases, the "statistic" will be simple sum of the measures, and > counting the number of facts affected. To be effective, reading the > facts from disk should not involve complex conversions. For this reason, > storing in CSV or XML or any textual format would be bad. I'm thinking > about a binary format, but how can I interface that with Python? > > I already looked at: > > - xdrlib, which throws me DeprecationWarning when I store some integers > - struct which uses format string for each read operation, I'm concerned > about its speed > > What else can I use? > > Thanks, > > Laszlo > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From gminick at bzt.bzt Thu Aug 14 17:31:42 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Thu, 14 Aug 2008 21:31:42 +0000 (UTC) Subject: negative numbers are not equal... References: <48A4932F.4010302@gmail.com> Message-ID: On Thu, 14 Aug 2008 18:23:21 -0300, ariel ledesma wrote: > i see now, so i guess that's also why id() returns the same address for > them as well... It just have to work like this. a is b is actually equal to: id(a) == id(b) so there is no other way for id() in such case. Hope this helps. -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From larry.bates at websafe.com` Wed Aug 13 17:07:52 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 13 Aug 2008 16:07:52 -0500 Subject: callbacks in python In-Reply-To: <2b3a25c6-9985-4d05-8721-5a57a020e845@w7g2000hsa.googlegroups.com> References: <2b3a25c6-9985-4d05-8721-5a57a020e845@w7g2000hsa.googlegroups.com> Message-ID: Alexandru Mosoi wrote: > does anyone know a nice implementation of callbacks in python? i have > issues mixing named & unamed parameters. i want build a callback over > a function such that some parameters are passed when callback is > created and the rest are passed when the function is called. > > example: > callback = Callback(function, x=1, y) > callback(z, t=4, u) First problem is that all unnamed arguments must come BEFORE named ones (Python limitation). To do what you want define you callback as a class instead. class Callback(object): def __init__(x, y): self.x = x self.y = y def __call__(z, t, u): # # Do what you want done at every callback # callback = Callback(x, y) callback(z, t, u) -Larry From rowen at u.washington.edu Thu Aug 14 12:20:11 2008 From: rowen at u.washington.edu (Russell E. Owen) Date: Thu, 14 Aug 2008 09:20:11 -0700 Subject: ActiveState Python v2.5 doesn't come with Tkinter or Tk installed. References: Message-ID: In article , "Dudeja, Rajat" wrote: > Hi, > > So, now I've finally started using Eclipse and PyDev as an IDE for my > GUI Application. I just wrote some sample programs as an hands on. > > Now I would like to take up Tkinter. I'm using Active State Python > version 2.5 and found that there is not Tkinter and Tk module in it. > > To use Tkinter do I actually require Tk installed on my machine? Please > suggest and where can I find both these modules? > > Also, please direct me to a good and short document on using Tkinter or > Tk in Python. What operating system? For MacOS X this should not happen because Tcl/Tk is already available. But the best Python for MacOS X is the binary installer from python.org and the best Tcl/Tk is ActiveState version 8.4.19 (the Tcl/Tk that comes with MacOS X 10.4 and 10.5 is rather old and buggy). For Windows: the standard python.org binary Python includes its own Tcl/Tk. So the simplest solution is to use that. I know nothing about ActiveState's Python for Windows but it is possible that it requires ActiveState Tcl/Tk to use Tkinter. For unix: I'm not sure about ActiveState and unix. But the standard package installer that comes with your unix should offer tcl/tk, python and _tkinter (possibly as 3 separate packages, possibly not) and at least tcl/tk and python should be installed by default. In general ActiveState puts out a very nice Tcl/Tk installer that includes many useful extra packages. But I've never seen the point to ActiveState's Python installer. When I last tried it, their Python was missing readline and did not add any useful packages to the standard python.org version. For info on Tkinter: -- Russell P.S. if you do install Tcl/Tk to use with Tkinter, please use 8.4.x, NOT 8.5. Python 2.5.x is not fully compatible with Tcl/Tk 8.5. From brennan.ron at gmail.com Thu Aug 28 13:02:55 2008 From: brennan.ron at gmail.com (Ron Brennan) Date: Thu, 28 Aug 2008 13:02:55 -0400 Subject: Multiple values for one key In-Reply-To: <48b6ca75$0$5088$426a74cc@news.free.fr> References: <26c69b160808271326w2f53b6b8s6e4aa7f91071ac71@mail.gmail.com> <48b6ca75$0$5088$426a74cc@news.free.fr> Message-ID: <26c69b160808281002l262e4824y60b8d3cb3369ee91@mail.gmail.com> I have another question. How would like to be able to add the contents on the values for one key. key['20001']:[978, 345] How can I do this? Thanks, Ron On Thu, Aug 28, 2008 at 11:56 AM, Bruno Desthuilliers wrote: > norseman a ?crit : > >> Terry Reedy wrote: >> >>> >>> >>> Ron Brennan wrote: >>> >>>> Hello, >>>> How would I create a dictionary that contains multiple values for one >>>> key. >>>> >>> >>> Make the value a collection object (set or list if you plan to add and >>> delete). >>> >>> I'd also like the key to be able to have duplicate entries. >>>> >>> >>> Dict keys must be hashable and unique. >>> >>> tjr >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> ================ >> First part I understand, second is still giving me a problem. >> >> For some reason I still want keys to be dbf column headers. >> like: >> >> name:address:zip so forth >> ---- ------- --- ------------------ >> guy: unknown:00000 >> girl: 123 tiny street:12345 >> boy:321 here:33333 >> gal:999 over there: 55555 >> so forth >> >> Thus one key has many values. And you can then index on whatever key(s) >> you wish - name,zip... >> > > You can either use 1/ a list of dicts, or 2/ a dict mapping keys to lists. > > 1/ > records = [ > {"name":"guy", "address":"unknown","zip":"00000"}, > {"name":"girl", "address":"123 tiny street","zip":"12345"}, > {"name":"boy", "address":"321 here","zip":"33333"}, > {"name":"gal", "address":"999 over there","zip":"55555"}, > ] > > keys = ("name", "address", "zip") > > print ":".join(keys) > print "-" * len(":".join(keys)) > for record in records: > data = [record[key] for key in keys] > print ":".join(data) > > > 2/ > records = dict( > name=["guy", "girl", "boy", "gal"], > address=["unknown","123 tiny street","321 there","999 over there"], > zip=["00000", "12345", "33333", "55555"] > ) > > keys = ("name", "address", "zip") > nb_records = len(records[keys[0]]) > > print ":".join(keys) > print "-" * len(":".join(keys)) > for i in xrange(nb_records): > data = [data[key][i] for key in keys] > print ":".join(data) > > > You are of course entitled the right to prefer the second solution, but > then I hope I'll never have to maintain your code, since it's obviously not > an appropriate data structure. > > With billions plus records, >> > > With billions plus records, it may be time to move to a serious RDBMS. > Which btw will provide solution 1, or a lighter version of it using a list > of tuples, ie: > > cursor = connection.cursor() > cursor.execute("select name, address, zip from peoples") > records = cursor.fetchall() > > # at this time, you have : > #records = [ > # ("guy", "unknown","00000",), > # ("girl", "123 tiny street","12345",), > # ("boy", "321 here","33333",), > # ("gal", "999 over there", "55555",), > #] > > > (snip) > > OK - I know I missed the whole concept of a Python Dictionary. >> > > Bad thing for you, since it's the central datastructure in Python. > > I haven't read anything as yet that gives a clear picture of what it is and >> what it is for. >> > > Then you failed to read the FineManual's tutorial, which is where you > should have started: > > http://docs.python.org/tut/node7.html#SECTION007500000000000000000 > > Do yourself a favour : read the above first, then if you still have > questions about dicts, we'll gladly try to help. > > And do yourself another favour : learn about SQL, relational model and > RDBMS. > > (snip description of why the OP *really* wants a RDBMS) > > -- > http://mail.python.org/mailman/listinfo/python-list > -- FYI, my email address is changing. My rogers account will be deactivated shortly. From now on please use: brennan.ron at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rcn.com Sat Aug 30 18:33:36 2008 From: python at rcn.com (Raymond Hettinger) Date: Sat, 30 Aug 2008 15:33:36 -0700 (PDT) Subject: Which is faster? References: Message-ID: <14014a96-78d3-4070-8464-39cfea95f0f5@r15g2000prh.googlegroups.com> On Aug 29, 9:26?pm, cnb wrote: > def av_grade(self): > ? ? ?return sum(review.grade for review in self.reviews) / \ > ? ? ? ? ? ? ? len(self.reviews) Minor point. Consider making the divisor: float(len(self.reviews)). It would be a bummer to throw-off the average because of floor division. Also consider an itertools approach: sum(itertools.imap(operator.itemgetter('review'), self.reviews)) BTW, the sum() in Py2.6 is *much* faster than before. It should run circles around any other approach. As Effbot says, if you really care about speed, then just time both approaches. However, it's a good run of thumb that builtins are hard to beat by simulating them in pure python (unless you're using Psyco as an optimizer). Raymond From frankrentef at yahoo.com Wed Aug 6 15:42:12 2008 From: frankrentef at yahoo.com (frankrentef) Date: Wed, 6 Aug 2008 12:42:12 -0700 (PDT) Subject: Run program from within Python Message-ID: <47eee9f1-c85d-4816-a204-8a11f178267d@d1g2000hsg.googlegroups.com> Greetings all... Newbie to Python... need help with opening a file from within Python... see the following code. import popen2 stdout, stdin = popen2.popen2('c:\test\OpenProgram.exe 1 1') keygen = stdout.read() print "The keygen value is: %s" % keygen from the command line if I execute "OpenProgram.exe 1 1" a number is returned. ("1 1" are required to return the value needed.) Ultimately I want to take that number and apply it to another script, but the program is not running. Suggestions? NEWBIE to Python.. From PaulAlexWilson at gmail.com Tue Aug 12 10:35:08 2008 From: PaulAlexWilson at gmail.com (Wilson) Date: Tue, 12 Aug 2008 07:35:08 -0700 (PDT) Subject: Manipulating Python Source Message-ID: <8257ff71-4f67-405e-ada8-35ba8879ddca@e39g2000hsf.googlegroups.com> Hi, I'm wondering if there are any tools available or simple methods for taking a python source file and parsing into some hierarchical format, like the ConfigParser. I'd like to be able to do something like the following: test.py: ------------------------------------------------------- """ This is an example """ class MyClass(ParentA, ParentB): def some_func(self, foo, bar): self.baz = "batman" class MyClass2(object): """ This is an example class """ def __init__(self): self.a = "Blablabla" And from the interpreter: >>> import magicalParser >>> parsed = magicalParser.parse(test.py) >>> parsed.getClasses() ["MyClass", "MyClass2"] >>> parsed.docString " This is an example " >>> parsed.removeClass("MyClass2") >>> parsed.getClasses() ["MyClass"] >>> parsed.MyClass.getFuncs() ["some_func"] >>> parsed.MyClass.some_func.addParam("baz") >>> parsed.printSource() """ This is an example """ class MyClass(ParentA, ParentB): def some_func(self, foo, bar, baz): self.baz = "batman" >>> exit() Or something that would yield the above effect. Any ideas? Thanks, Paul From deets at nospam.web.de Tue Aug 12 02:49:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 12 Aug 2008 08:49:29 +0200 Subject: File reading across network (windows) In-Reply-To: References: Message-ID: <6gcq3qFehr5kU1@mid.uni-berlin.de> Prof. William Battersea schrieb: > Hello, > > Suppose I have a Vista machine called VISTA and an XP machine called > XP in a workgroup named WORKGROUP. Physically they're connected to a > router and I can see lists of public and shared files on each of them. > How do I address these for IO? > > A search suggested that the form open(r"\\server\folder\folder"), but > I tried many combinations guessing what it wants for that path in my > case (r"\\WORKGROUP\VISTA", "\\VISTA\PUBLIC", etc), and none have > worked so far. You need to create network shares in windows first. Once these are established, *all* programs using file-IO - including python - can access files. Diez From __peter__ at web.de Tue Aug 12 04:56:29 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 12 Aug 2008 10:56:29 +0200 Subject: module import search path strangeness References: <4a15ac45-aef6-458f-91b6-bcaf14e10412@56g2000hsm.googlegroups.com> Message-ID: tow wrote: >>> > I have a python script (part of a django application, if it makes any >> > difference) which is exhibiting the following behaviour: >> >> > import my_module # succeeds >> > imp.find_module("my_module") # fails, raising ImportError >> >> > which is completely baffling me. According to sys.path, both should >> > fail; the directory containing my_module is not in sys.path (though >> > the my_module directory itself is). > The current directory is actually a subdirectory of /home/tow/test/ > my_module, > but ".." is not in sys.path (nor is anything containing "..") In any > Basically, I had thought that import and imp.find_module used exactly > the same > search path, but the above example shows that at least in this > circumstance they > don't; import is picking up additional search paths from somewhere - > what am I missing? Grepping through the django source finds ./trunk/django/core/management/__init__.py: sys.path.append(os.path.join(project_directory, os.pardir)) sys.path could be changed as a side effect of an import, so I ask you to verify (again) that import and imp.find_module() see the same sys.path. assert all(".." not in p for p in sys.path) import my_module assert all(".." not in p for p in sys.path) imp.find_module("my_module") Peter From musiccomposition at gmail.com Fri Aug 1 22:47:42 2008 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 1 Aug 2008 19:47:42 -0700 (PDT) Subject: Class definition attribute order References: Message-ID: <5fb776ae-e3d7-49ec-9ebf-350b9bf9cac1@l42g2000hsc.googlegroups.com> On Aug 1, 6:23?pm, Andrew Lentvorski wrote: > How do I determine the order of definition of class attributes? > > For example, if I have a class > > class Test(object): > ? ? ?y = 11 > ? ? ?x = 22 > > How do I tell that y was defined before x? You wait until Python 3.0 where you can do this sort of thing with metaclasses. > > Thanks, > -a From saluk64007 at gmail.com Sun Aug 10 15:42:27 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sun, 10 Aug 2008 12:42:27 -0700 Subject: Wouldn't it be nice if this worked? In-Reply-To: References: Message-ID: How about: class A: def add(self,x,y): return x+y class B(A): pass print B().add(1, 2) This also works: class A: def add(self, x, y): return x+y class B: pass B.add = A.add.im_func print B().add(1, 2) From notvalid2 at sbcglobal.net Sat Aug 30 13:37:44 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Sat, 30 Aug 2008 10:37:44 -0700 Subject: Date Comparison and Manipulation Functions? In-Reply-To: <_vfuk.36060$co7.14057@nlpi066.nbdc.sbc.com> References: <6cdf0c14-80b6-42c4-8047-8c01fda8b87c@r15g2000prh.googlegroups.com> <9U8tk.19080$cW3.13729@nlpi064.nbdc.sbc.com> <8AVtk.8079$np7.5970@flpi149.ffdc.sbc.com> <4ad1c85c-479c-44e5-ac1b-ca0509d40c42@s20g2000prd.googlegroups.com> <_vfuk.36060$co7.14057@nlpi066.nbdc.sbc.com> Message-ID: The author has updated the Tutorial and added a flex method. From toby at tobiah.org Mon Aug 11 16:46:10 2008 From: toby at tobiah.org (Tobiah) Date: Mon, 11 Aug 2008 13:46:10 -0700 Subject: list question... unique values in all possible unique spots References: <57fcf019-1afd-4c48-b329-42a0ffc4c5ac@x35g2000hsb.googlegroups.com> Message-ID: On Sat, 09 Aug 2008 08:07:26 -0700, Mensanator wrote: > 403291461126605635584000000 I think it's only 4 septillion. Perfectly manageable. ** Posted from http://www.teranews.com ** From cito at online.de Sun Aug 17 09:56:09 2008 From: cito at online.de (Christoph Zwerschke) Date: Sun, 17 Aug 2008 15:56:09 +0200 Subject: Missing exceptions in PEP 3107 In-Reply-To: References: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> <8800beb6-c07b-44af-b9ac-fcb00f35dc3a@f36g2000hsa.googlegroups.com> Message-ID: Terry Reedy wrote: > I would agree... but... > The problem is that code that uses a function hardly cares whether an > exception that replaces the normal return is raised explicitly, by a > syntax operation (and these are not yet completely documented, though > perhaps they should be), or by a function called within the function. I often read that argument that info on thrown exceptions does not matter in Python, but I beg to differ. Just as a simple and well-known example, it is absolutely important to know that the str.index() method throws a ValueError if nothing is found, while the str.find() method should never throw a ValueError. -- Christoph From nytrokiss at gmail.com Wed Aug 27 16:19:20 2008 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 27 Aug 2008 13:19:20 -0700 Subject: Books about Python. In-Reply-To: <48b5a19a$0$10445$426a74cc@news.free.fr> References: <7acfbe5e-ccb7-4fcf-b775-4ff65ff6281d@i76g2000hsf.googlegroups.com> <48b5a19a$0$10445$426a74cc@news.free.fr> Message-ID: <8a6b8e350808271319g4542502bt4aeba2ed751cc9be@mail.gmail.com> I really liked Core python programming 2nd edition On Wed, Aug 27, 2008 at 9:49 AM, Bruno Desthuilliers wrote: > cscorley at gmail.com a ?crit : >> >> I'm up to write a 20-30 research paper for my computer science course, >> and I was considering choosing to do mine on Python. I was curious if >> anybody knows of any good books about python they could recommend that >> have more of a technical view rather than a Teach-yourself-in-24-hours >> type. > > May I recommand the fine manual and this newsgroup ? > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 13 08:34:15 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 13 Aug 2008 14:34:15 +0200 Subject: __getattr__, __setattr__ and pickle In-Reply-To: References: <48a1cdce$0$14748$426a74cc@news.free.fr> <48a21029$0$15610$426a74cc@news.free.fr> Message-ID: <48a2d4bb$0$9737$426a74cc@news.free.fr> mwojc a ?crit : > Bruno Desthuilliers wrote: > >> >>> class Prop(object): >> ... @apply >> ... def prop(): >> ... def fget(self): return self._prop >> ... def fset(self, val): self._prop = val >> ... return property(**locals()) >> ... def __init__(self, val): self.prop=val >> ... >> >>> class Hook(object): >> ... def __getattr__(self, name): >> ... if name == 'prop': >> ... return self._prop >> ... raise AttributeError("yadda") >> ... def __setattr__(self, name, val): >> ... if name == 'prop': >> ... self.__dict__['_prop'] = val >> ... else: >> ... # XXX : INCORRECT IMPLEMENTATION, DONT DO THIS ! >> ... self.__dict__[name] = val >> ... # correct implementation: >> ... # super(Hook, self).__setattr__(name, value) >> ... def __init__(self, val): self.prop=val > > Hi! > Finally i ended up with all the suggestions you gave me. The speed is > important to me besause i get/set my attribute a lot... The only doubts i > have are with the @apply decorator, because 'apply' seems to be depreciated > since python 2.3... As far as I can tell, it should stay until Python 3.0. But you don't have to write your properties that way anyway - it's just something I personnaly find to be a convenient shortcut, period. FWIW, the above code is just a copy/paste from an interactive session, not an example of "clean" Python coding. > And another thing: why writing for all > attributes 'self.__dict__[name] = val' in __setattr__ is incorrect? Because __setattr__ is *always* called. With your above solution, read/write properties setters won't be called. Python 2.5.1 (r251:54863, Mar 7 2008, 03:41:45) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo(object): @apply def bar(): def fget(self): print "bar get" return self._bar def fset(self, val): print "bar set" self._bar = val def __getattr__(self, name): print "__getattr__", name if name == 'baaz': return self._baaz raise AttributeError("yadda") def __setattr__(self, name, val): print "__setattr__", name self.__dict__[name] = val >>> foo = Foo('bar', 'baaz') __setattr__ bar __setattr__ baaz >>> foo.baaz 'baaz' >>> foo.bar 'bar' >>> foo.__dict__ {'baaz': 'baaz', 'bar': 'bar'} From deets at nospam.web.de Mon Aug 25 19:15:46 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Aug 2008 01:15:46 +0200 Subject: swig or ctypes , under the gun and need help In-Reply-To: References: Message-ID: <6hgsp2FlnrehU1@mid.uni-berlin.de> Sells, Fred schrieb: > Diez wrote... >> I don't know swig, but if all you have is a real C-API, try & >> use ctypes. >> It's much easier to create bindings for, keeps you fully in >> the warm and >> cozy womb of python programming and doesn't need no >> compilation to create >> the actual binding. >> > You're right the ctypes does seem more pythonesque; however I'm still stuck trying return all these parameters > that the c api uses. my ctypes code is below. It just quits running when I try to print > one of the args I did a pass byref on, no error out, nothing. admittedly I'm a newbie to ctypes and not much of a c programmer > but I could sure use some help. my ctypes test code follows... > > from ctypes import * > > ''' > create shared object file like so. > gcc -shared -o rug520.so rug520.c You need to create a proper library. The above doesn't do that - it creates as simple object file. I don't know how to really do that without using autoconf/automake. Diez From gminick at nie.ma.takiego.adresu.w.sieci.pl Wed Aug 13 18:50:29 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Wed, 13 Aug 2008 22:50:29 +0000 (UTC) Subject: Replace Several Items References: <513926b0-64fe-4fdc-bb33-bc4b8ad3ab10@a70g2000hsh.googlegroups.com> Message-ID: Dnia Thu, 14 Aug 2008 00:31:00 +0200, Fredrik Lundh napisa?(a): >>> if ch in my_string: >>> my_string = my_string.replace(ch, "") >>> >>> on representative data. >> >> I don't have to, I can anticipate the results. > > Chances are that you're wrong. At the moment my average is about 0.75 of mistake per post on comp.lang.python (please, bare with me ;-)). I strongly believe that the statement I made above won't make this number rise. :) -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From mbrkic at invalid_mail.adress Sat Aug 30 21:32:37 2008 From: mbrkic at invalid_mail.adress (Marin Brkic) Date: Sun, 31 Aug 2008 03:32:37 +0200 Subject: Writing to ms excel References: <56aeb3cd-1e37-4242-aefe-8a33452d61a2@q26g2000prq.googlegroups.com> Message-ID: <3msjb412b55hf4i00fvs3gto8lt6kv05na@4ax.com> On Sat, 30 Aug 2008 17:18:19 -0700 (PDT), John Machin wrote: Hello John (and everyone else), thanks for answering. >It helps in situations like this to mention details of your >environment >(1) what version of what operating system (Linux, OS X, Windows, etc) >(2) what version of Python >as the available solutions are often dependent on the answers. Yes, of course. I sometimes forget the most essential of things. - winxp, sp2 - python 2.5.2 > >For Python version 2.[345] on any platform, you can use xlwt, which is >as simple as this for writing a 1-worksheet Excel 97-to-2003 XLS file >(without any formatting): Actually, that might work. What I was needing (aiming for) was a way to write to excel 2003 files. Formatting is not necessary, since what I'm trying to write is some tabular data; results from fortran-python simulation (I can explain, but the details seem irrelevant for this case). I'm trying to avoid the text file - import to excel - mechanism, since there is quite a lot of files written. > >def write_xls(file_name, sheet_name, data): > import xlwt > book = xlwt.Workbook() > sheet = book.add_sheet(sheet_name) > rowx = 0 > for row in data: > rowx += 1 > for colx, value in enumerate(row): > sheet.write(rowx, colx, value) > book.save(file_name) ># data can be any of the following Python types: int, long, float, >decimal.Decimal, datetime.date, datetime.datetime, bool, str, and >unicode. > >xlwt is available from https://secure.simplistix.co.uk/svn/xlwt/trunk > >I suggest that you join the python-excel group (http:// >groups.google.com.au/group/python-excel?hl=en) or at least read some >of the questions and responses. Please, one more question. As you have noticed, I posted my message to comp.lang.python, using a newsreader. Is there a way to access google groups through a similiar interface program as a newsreader. Never used them before, and getting a lot of messages to my email every day does not sound very appealing to me. Best regards Marin > >HTH, > >John From poojaangali at gmail.com Fri Aug 15 06:00:17 2008 From: poojaangali at gmail.com (pooja) Date: Fri, 15 Aug 2008 03:00:17 -0700 (PDT) Subject: EARN MONEY $1500-$5000 PER MONTH Message-ID: <44213a03-09f5-4373-bec8-e84e5372dd6e@j1g2000prb.googlegroups.com> EARN MONEY $1500-$5000 PER MONTH SIMPLE ONLINE SURVEY CREATE UR ACCOUNT AND EARN IMMEDIATLY ************************************************************************* http://www.AWSurveys.com/HomeMain.cfm?RefID=kingraja666 ************************************************************************* From darcy at druid.net Tue Aug 26 09:11:30 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 26 Aug 2008 09:11:30 -0400 Subject: Sharing common memory space (In form of List) across the python processes. In-Reply-To: References: Message-ID: <20080826091130.d692951b.darcy@druid.net> On Tue, 26 Aug 2008 18:18:53 +0530 Piyush Chechani wrote: > Please suggest how to share a in-memory list object across two different > programs? Perhaps you want to investigate XML-RPC. Check the docs for some example scripts for both client and server. P.S. Please drop the legal crap from your postings. This is a public list and such things are just a waste of space. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From dangets at gmail.com Fri Aug 8 13:37:40 2008 From: dangets at gmail.com (DG) Date: Fri, 8 Aug 2008 10:37:40 -0700 (PDT) Subject: relative imports improve program organization... suggestions? Message-ID: <1a0a7d3c-4d65-4c50-823e-f8d8be61592f@1g2000pre.googlegroups.com> Alright, I have searched and searched and read many conversations on the topic of relative and absolute imports and am still not getting the whole thing through my skull. Highlights of what I've read: http://mail.python.org/pipermail/python-list/2007-January/422973.html http://groups.google.com/group/comp.lang.python/browse_thread/thread/b1e8dc93471a7079/8751c82cfe1ca3f2?lnk=gst&q=absolute+import#8751c82cfe1ca3f2 http://www.python.org/dev/peps/pep-0328/ http://docs.python.org/whatsnew/pep-328.html So my problem and argument: I want to create a package organized as the following: pckg/ __init__.py main.py moduleA/ __init__.py A_base.py A1/ __init__.py A_inherit1.py other_A1_files... A2/ __init__.py A_inherit2.py other_A2_files... moduleB/ ... Explanation: The main program is located in main.py and it implements the different modules (A, B). Within the modules the basic organization is; the base class for all different types of A is directly within the moduleA directory. All of the different inherited classes of A are within their own subdirectory with a mess of their own files. This is done so that a new subclass of A can be added/removed by just adding/ removing the subdirectory and each of these subclasses may have their own maintainer, but they should all inherit from A_base.py If I am developing the A1 directory, I want to be able to test A_inherit1.py by using 'if __name__ == "__main__"' within the A_inherit1.py file and by typing 'python A_inherit1.py' on the command line. I prefer this simply to keep all unit tests within the same directory and same file as the inherited class. My Problem: A_inherit1.py has the line: 'from ..A_base import A_Base_Class' so that I can later declare the inherited class as such: 'A1_Inherited_Class(A_Base_Class):' *BUT* I get the 'attempted relative import in non-package' error even when I try the 'from __future__ import absolute_import' command. I would prefer to be able to test the file without adding anything to the PYTHONPATH, like I said by using the name == main trick. So could someone explain to me what the rationale behind not allowing parent directory relative imports is? And possibly what I can do to get around it? (I really don't like messing with the sys.path for something like this) Thanks, Danny G From deets at nospam.web.de Thu Aug 7 11:58:24 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 07 Aug 2008 17:58:24 +0200 Subject: python-mode is missing the class browser References: <6361fac8-3bfb-4d7e-b13b-84261ebeea10@b1g2000hsg.googlegroups.com> <489b1509$0$3481$426a74cc@news.free.fr> Message-ID: <6g0kf5FdoskeU1@mid.uni-berlin.de> Bruno Desthuilliers wrote: > Michele Simionato a ?crit : >> I have noticed that the python-mode for Emacs that comes with the >> latest Ubuntu is missing the class browser. Moreover if works >> differently from the python-mode I was used to (for instance CTRL-c-c >> works as CTRL-c-! whereas CTRL-c-! is missing, etc). How can I go back >> to the old python-mode >> or at least how do I get back the class browser? > > I'm not really up2date wrt/ my ubuntu station here, but I remember > having seen this somewhat different (emacs-provided IIRC) python-mode > which I didn't like. I don't quite remember what I did, but I can at > least tell you what I have actually have: I've got the same, and a IM-Python-menu that contains the class-browser. > FWIW and talking about class-browser, there's the IMHO very excellent > emacs-code-browser too. Yes, it sure is cool. And I have no idea how I ever worked without flymake & pylint :) Emacs just rocks... Diez From simon at mullis.co.uk Wed Aug 13 08:45:31 2008 From: simon at mullis.co.uk (Simon Mullis) Date: Wed, 13 Aug 2008 14:45:31 +0200 Subject: From Ruby to Python? Message-ID: <23d7e1bb0808130545w28fb4c04s205c1de2a39dcb36@mail.gmail.com> Hi All, I just finally found 30 minutes to try and write some code in Python and realized after a couple of minor syntactic false starts that I'd finished my initial attempt without needing to refer to any documention... And after the first few minutes I stopped noticing the whitespace thing that had scared me off previously. (Admittedly it's a very basic script using telnetlib to log into a bunch of network devices via a few console servers and put the results of some remote commands into a data-structure). So, after this initially promising start: Are there any good cheatsheets / guides for a Ruby programmer to learn Python? I searched this list and couldn't find anything, and wasn't successful with google either... Many thanks in advance, SM -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon at brunningonline.net Wed Aug 13 14:32:42 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 13 Aug 2008 19:32:42 +0100 Subject: gasp In-Reply-To: <1ee11ba30808131006p22edb17ap206d42c9ffc2ef1d@mail.gmail.com> References: <65dba773-6441-424e-a019-dc1e493dddb7@v57g2000hse.googlegroups.com> <8c7f10c60808130956l19553772u62d8f993f610a0bc@mail.gmail.com> <1ee11ba30808131006p22edb17ap206d42c9ffc2ef1d@mail.gmail.com> Message-ID: <8c7f10c60808131132y577b7888lf7958d4534c6e770@mail.gmail.com> 2008/8/13 Cyprian Kumwaka : > No, it doesn't! I have even tried uninstalling and installing it but still > it doesn't not work. Any more ideas! What error message do you get when you try it? "Doesn't work" isn't anything like enough to go on. And please keep the conversation on-list. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From timr at probo.com Sat Aug 2 19:31:30 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 02 Aug 2008 23:31:30 GMT Subject: base-96 References: <094aaf8f-0d16-4f85-abd5-232f475b9785@x35g2000hsb.googlegroups.com> Message-ID: Kless wrote: >I think that would be very interesting thay Python would have a module >for working on base 96 too. [1] > >It could be converted to base 96 the digests from hashlib module, and >random bytes used on crypto (to create the salt, the IV, or a key). > >As you can see here [2], the printable ASCII characters are 94 >(decimal code range of 33-126). So only left to add another 2 >characters more; the space (code 32), and one not-printable char >(which doesn't create any problem) by last. Whether it creates problems depends on how you intend to use it. The biggest use for Base64, for instance, is in translating binary files to a form where they can be send via email using only printable characters. If you use a non-printable character, that's a problem for email. With Base64, 3 bytes becomes 4. With Base96, 5 bytes becomes 6. So, you would reduce the conversion penalty from 1.33 down to 1.17. It's not hard to write modules to translate from binary to Base96 and back again, and doing so would be a great exercise to explore the issues in this kind of encoding. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sln at netherlands.com Wed Aug 20 22:36:39 2008 From: sln at netherlands.com (sln at netherlands.com) Date: Thu, 21 Aug 2008 02:36:39 GMT Subject: The Importance of Terminology's Quality References: <48a8df27$0$7362$607ed4bc@cv.net> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: On Thu, 21 Aug 2008 02:30:27 GMT, sln at netherlands.com wrote: >On Wed, 20 Aug 2008 21:18:22 -0500, rpw3 at rpw3.org (Rob Warnock) wrote: > >>Martin Gregorie wrote: >>+--------------- >>| I was fascinated, though by the designs of early assemblers: I first >>| learnt Elliott assembler, which required the op codes to be typed on >>| octal but used symbolic labels and variable names. Meanwhile a colleague >>| had started on a KDF6 which was the opposite - op codes were mnemonics >>| but all addresses were absolute and entered in octal. I always wondered >>| about the rationale of the KDF6 assembler writers in tackling only the >>| easy part of the job. >>+--------------- >> >>In the LGP-30, they used hex addresses, sort of[1], but the opcodes >>(all 16 of them) had single-letter mnemonics chosen so that the >>low 4 bits of the character codes *were* the correct nibble for >>the opcode! ;-} >> >>[Or you could type in the actual hex digits, since the low 4 bits >>of *their* character codes were also their corresponding binary >>nibble values... "but that would have been wrong".] >> >> >>-Rob >> >>[1] The LGP-30 character code was defined before the industry had >> yet standardized on a common "hex" character set, so instead of >> "0123456789abcdef" they used "0123456789fgjkqw". [The "fgjkqw" >> were some random characters on the Flexowriter keyboard whose low >> 4 bits just happened to be what we now call 0xa-0xf]. Even worse, >> the sector addresses of instructions were *not* right-justified >> in the machine word (off by one bit), plus because of the shift- >> register nature of the accumulator you lost the low bit of each >> machine word when you typed in instructions (or read them from >> tape), so the address values you used in coding went up by *4*! >> That is, machine locations were counted [*and* coded, in both >> absolute machine code & assembler] as "0", "4", "8", "j", "10", >> "14", "18", "1j" (pronounced "J-teen"!!), etc. >> >>----- >>Rob Warnock >>627 26th Avenue >>San Mateo, CA 94403 (650)572-2607 > > >Whats os interresting about all this hullabaloo is that nobody has >coded machine code here, and know's squat about it. > >I'm not talking assembly language. Don't you know that there are routines >that program machine code? Yes, burned in, bitwise encodings that enable >machine instructions? Nothing below that. > >There is nobody here, who ever visited/replied with any thought relavence that can >be brought foward to any degree, meaning anything, nobody.... > >sln At most, your trying to validate you understanding. But you don't pose questions, you pose terse inflamatory declarations. You make me sick! sln From tomchelan at msn.com Wed Aug 20 21:11:16 2008 From: tomchelan at msn.com (TOM MCCULLOUGH) Date: Wed, 20 Aug 2008 18:11:16 -0700 Subject: Delivery Status Notification (Failure) Message-ID: You Suck big time! -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Emoticon7.gif Type: image/gif Size: 250 bytes Desc: not available URL: From thegiantsden at gmail.com Wed Aug 13 21:25:53 2008 From: thegiantsden at gmail.com (Shemia Miller) Date: Wed, 13 Aug 2008 21:25:53 -0400 Subject: JOB: Python Programmer Message-ID: <67d1651f0808131825k6ce7e0e1n992d5649028f0f40@mail.gmail.com> Greetings, I would like to hire a python expert who can quickly install the database with accuracy. It is only one script, and it shouldn't take no more than an hour. The script is at http://www.askspree.de My hosting provider doesn't have turbo, so I have vps. Quick way to earn $50.00. It is an hour job. Thank you for your immediate attention to this matter. -- Phone Number: (641) 715-3900 Extension: 66984# Please allow 24-48 hrs. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Thu Aug 28 20:00:57 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2008 00:00:57 GMT Subject: [Q] How to ignore the first line of the text read from a file References: <6hocqtFmpekqU5@mid.uni-berlin.de> Message-ID: <00c736d5$0$20302$c3e8da3@news.astraweb.com> On Thu, 28 Aug 2008 15:11:39 -0700, Dennis Lee Bieber wrote: > On 28 Aug 2008 19:32:45 GMT, Marc 'BlackJack' Rintsch > declaimed the following in comp.lang.python: > >> On Thu, 28 Aug 2008 10:16:45 -0700, norseman wrote: >> > import os >> > >> > file = open(filename, 'r') >> > for line in file: >> > dummy=line >> > for line in file: >> > print line >> > >> > >> > is cleaner and faster. >> >> That's not cleaner, that's a 'WTF?'! A ``for`` line over `file` that >> does *not* iterate over the file but is just there to skip the first >> line and a completely useless `dummy` name. That's seriously ugly and >> confusing. >> > Nice to see someone else was as, uhm, offended by that code sample > as I was -- I just lacked the vocabulary to put it across cleanly, so > didn't respond. > > Yes, the "dummy" statement could be completely dropped to the same > effect -- still leaving the useless outer loop... Nevertheless, I've just done some timeit tests on the two code snippets, and to my *great* surprise the second ugly snippet is consistently a smidgen faster even with the pointless import and dummy statement left in. That is so counter-intuitive that I wonder whether I've done something wrong, or if it's some sort of freakish side-effect of disk caching or something. But further investigation will have to wait for later. If anyone wants to run their own timing tests, don't forget to close the file explicitly, otherwise timeit() will (I think...) simply iterate over the EOF for all but the first iteration. -- Steven From siona at chiark.greenend.org.uk Fri Aug 1 09:47:17 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 01 Aug 2008 14:47:17 +0100 (BST) Subject: very large dictionary References: <5c5e6d6e-04ef-4340-963f-d3825875b32c@e39g2000hsf.googlegroups.com> Message-ID: Simon Strobl wrote: >I tried to load a 6.8G large dictionary on a server that has 128G of >memory. I got a memory error. I used Python 2.5.2. How can I load my >data? Let's just eliminate one thing here: this server is running a 64-bit OS, isn't it? Because if it's a 32-bit OS, the blunt answer is "You can't, no matter how much physical memory you have" and you're going to have to go down the database route (or some approach which stores the mapping on disk and only loads items into memory on demand). -- \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" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From bsder at allcaps.org Fri Aug 1 19:23:02 2008 From: bsder at allcaps.org (Andrew Lentvorski) Date: Fri, 01 Aug 2008 16:23:02 -0700 Subject: Class definition attribute order Message-ID: <48939AD6.8060703@allcaps.org> How do I determine the order of definition of class attributes? For example, if I have a class class Test(object): y = 11 x = 22 How do I tell that y was defined before x? Thanks, -a From fredrik at pythonware.com Sat Aug 30 09:32:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 30 Aug 2008 15:32:06 +0200 Subject: How to delete elements from Tix Combo Box? In-Reply-To: References: Message-ID: dudeja.rajat at gmail.com wrote: > I'm using a Tix combo box (I call it combo2), the contents of which > are loaded depeding on the selection in another Tix combo box(I call > it combo1) > I have used the commands: > > self.cbAnalysisLibVersion.insert(END, results) > > to insert elements to the combo box. > > I'm looking for some similar option to delete elements from the combo > box. I mean, as soon as I change selection in > combo1 the previous elements in the combo2 should get cleared up( or > deleted) and | shall be able to the above insert command to add new > elements to the combo2 ( depending upon selection in combo1) > > Please suggest how can I clear up the ( delete the entries) in combo2. no time to test this, but iirc, the combobox content is held in an ordinary listbox widget, so you should be able to use the subwidget method to fetch that widget, and then use ordinary listbox methods to change the content. Something like this: lb = w.subwidget("listbox") lb.delete(0, END) # delete all items From tjreedy at udel.edu Tue Aug 5 15:03:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 05 Aug 2008 15:03:27 -0400 Subject: Difference between type and class In-Reply-To: References: <87myjy2vc6.fsf@nokile.rath.org> <12072cbe-139a-430f-81aa-b64bc31b43e5@e39g2000hsf.googlegroups.com> <87zlny8cdg.fsf@nokile.rath.org> Message-ID: Gabriel Genellina wrote: A decade ago, in 1.x, 'types' were built-in classes. They were instances of class 'type'. 'Classes' were user-defined classes. They were instances of (built-in) class 'classob'. User classes had the same status as instances of any other built-in class. They could only inherit from other instances of 'UserClass'. Instances of user classes were actually instances of built-in class 'instance'. They could not be instances of the user class because user classes were, in a sense, not really classes, just instances of 'classob' that emulated 'real' classes. >>> class C(): pass ... >>> c=C() >>> type(C) >>> type(c) Many users found the distinction between built-in classes and user classes confusing and limiting. Users wanted to be able to use built-in classes as base classes for user classes. So in 2.2 'object' was added as the base-class for all built-in classes and user-classes with 'object' in the base-class tree became instances of type (or of some other meta-class derived from type) instead of classob. But the representation of new-style classes matched that of old-style classes rather than that of the other instances of 'type' that happened to be built in. In 3.0, built-in classes 'classob' and 'instance' are gone, along with the confusion of having two categories of user classes along with an apparently separate category of built-in classes. User-classes are real classes on a par with C-coded classes. >>> class C(): pass # 3.0, in 2.x, class c(object) >>> c=C() >>> type(C) # same as >> type(int) >>> type(c) > If it helps you to understand the issue, in Python 3.0 that > difference is gone - the word "class" is used on both cases. See > http://bugs.python.org/issue2565 The only visible difference now (in 3.0) is that C-coded built-in classes that are present as startup and which do not live in any particular module do not have a module name as part of their representation. Imported C-coded classes show no difference (and indeed, in other implementations, they might be coded in Python or ?? rather than C). >>> int >>> c >>> import itertools as i >>> i.product I believe this should mean that if one write a module in Python and later rewrites part of it in C for speed, with identical API, the change of implementation will otherwise be transparent to user code and users, as it ought to be. Terry Jan Reedy From ironfroggy at gmail.com Wed Aug 13 23:40:50 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Wed, 13 Aug 2008 23:40:50 -0400 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> <76fd5acf0808120651u259e5d8dt32a8d49bb5d77add@mail.gmail.com> <200808122240.22517.maric@aristote.info> <76fd5acf0808121415h41cc580bj85d96e648c54ab4b@mail.gmail.com> <74583B8642AB8841B30447520659FCA92CC054B5@dnce01.ent.ti.com> Message-ID: <76fd5acf0808132040n22fd51f2seb12c403162f5d8b@mail.gmail.com> On Wed, Aug 13, 2008 at 10:49 PM, Carl Banks wrote: >> There is no point of nested classes because nested classes _are not_ >> supported by python. They are simply an artifact of not actively >> denying the syntax non-globally. I would fully support a change to the >> language to actively forbid a class definition that is not >> module-level. > > I think that's taking it a little too far. It's not unreasonable to > throw small, private use classes into the class definition, like so: > > class Someting(object): > class PrivateException(Exception): > pass > > And inside function a class definition can make a lot of sense. > Oftentimes I write a quick adaptor class because I want to pass > something to code that expects something else, for instance: > > def some_function(lines): > class FileMimicker(object): > def __init__(self): > self.index = 0 > def readline(self): > line = lines[self.index] > self.index += 1 > return line > function_that_calls_readline(FileMimicker()) > > > (Why would I want to clutter up my module's namespace for that silly > thing?) > > So I see no good reason for the compiler to disallow nested class > statements; it's occasionally useful and not a common pitfall. > > Carl Banks I know every rule has its exceptions. I put "don't nest classes" in with other similar rules I will claim, where I think its safest to say "Never do this!", because only then will you know that, should you actually do it at some point, you've got a reason good enough to break a "rule". As for the cluttering of the namespace, I don't buy it. Sure there are cases to be made to reduce the number of names in any scope, but I don't see a big advantage here. Its still accessible from the module, just though the class. I also don't see any examples of nested classes that wouldn't be useful elsewhere, your example included. For that matter, your example should just being using StringIO. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy From boblatest at yahoo.com Fri Aug 1 15:22:14 2008 From: boblatest at yahoo.com (Robert Latest) Date: 1 Aug 2008 19:22:14 GMT Subject: Pointers/References in Python? References: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Message-ID: <6fh636Fb67ejU1@mid.uni-berlin.de> Gary Herron wrote: > No need. A Python list contains *references* to objects, not copies of > objects. (The same is true of variables, dictionaries, sets, and so > on...). Good to know. I just wanted to make sure before writing more code which in the end might not scale well. Thanks to all for the help! robert From sthembilengidi at gmail.com Mon Aug 25 04:58:36 2008 From: sthembilengidi at gmail.com (Amie) Date: Mon, 25 Aug 2008 01:58:36 -0700 (PDT) Subject: For loop inside an xml template Message-ID: <57deb346-9326-4d97-9c88-7475baf0a30f@c58g2000hsc.googlegroups.com> Hi, Is it possible to have a for loop within an xml template? From msakibkhan at gmail.com Sat Aug 23 02:33:32 2008 From: msakibkhan at gmail.com (SaqibKhan) Date: Fri, 22 Aug 2008 23:33:32 -0700 (PDT) Subject: Error accessing the system registery Message-ID: Hello members ! a message box is appearing when I goto 'Tools> References' in VBA or VB6. I have tried many options but issue is not resolved yet. I have no administrator's rights in PC. can anybody resolve my problem ??? Best Regards M. Saqib Khan From cvrebert+clp at gmail.com Thu Aug 28 14:25:43 2008 From: cvrebert+clp at gmail.com (Chris Rebert) Date: Thu, 28 Aug 2008 11:25:43 -0700 Subject: epoch seconds from a datetime In-Reply-To: <40ab500b-f33f-4d6a-9c7c-fecee0119ba0@s50g2000hsb.googlegroups.com> References: <40ab500b-f33f-4d6a-9c7c-fecee0119ba0@s50g2000hsb.googlegroups.com> Message-ID: <47c890dc0808281125r4af5aa3ex1f44fc122cba06cf@mail.gmail.com> On Thu, Aug 28, 2008 at 10:18 AM, Richard Rossel wrote: > Hi friends, > I need a little help here, I 'm stuck with epoch calculation issue. > I have this datetime: > date_new = datetime(*time.strptime('20080101T000000','%Y%m%dT%H%M%S') > [0:6]) > This date_new is in UTC > Now I need to know the seconds since epoch of this new date, so I run > this: > seconds = int(time.mktime(date_new.timetuple())) > but the seconds returned belongs to : > Tue, 01 Jan 2008 03:00:00 GMT > because the localtime is in timezone 'America/Santiago': -3 > > I fix this trying to alter the TZ with time.tzset(): > os.environ['TZ'] = 'UTC' > time.tzset() > > .... and now I can gets the right epoch, but I can't restore the > previous TimeZone, I try with: > os.environ['TZ'] = '', but the time.tzset() doesn't back to the > original ( America/Santiago) I think you need to del os.environ['TZ'] rather than setting it to the empty string. On my box: Python 2.5.1 (r251:54863, Feb 4 2008, 21:48:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin >>> import os, time >>> time.asctime() 'Thu Aug 28 11:19:57 2008' >>> #that's my correct local time >>> time.tzname ('PST', 'PDT') >>> #that's my correct timezone >>> os.environ['TZ'] = 'UTC' >>> time.tzset() >>> time.tzname ('UTC', 'UTC') >>> time.asctime() 'Thu Aug 28 18:20:33 2008' >>> #we're clearly in UTC now >>> del os.environ['TZ'] #this is the key line >>> time.tzset() >>> time.tzname ('PST', 'PDT') >>> time.asctime() 'Thu Aug 28 11:21:05 2008' >>> #and now we're back to my original timezone Regards, Chris ======== Follow the path of the Iguana... Rebertia: http://rebertia.com Blog: http://blog.rebertia.com > > A solution should be set the os.environ['TZ'] to 'America/Santiago' > but I can't make a TZ hardcode because > the software should works on different timezones. > > So the question, how can restore the system into original timezone, or > how to know the seconds since epoch > from UTC datetime without change the local system TIMEZONE. > > please help > > -- > http://mail.python.org/mailman/listinfo/python-list > From musiccomposition at gmail.com Fri Aug 15 23:13:25 2008 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 15 Aug 2008 20:13:25 -0700 (PDT) Subject: python interpreter References: <29e59f7a-af87-40b4-9c5e-58abe1a28721@t1g2000pra.googlegroups.com> <1a514d18-579f-4372-bf9d-0c7b8e45a24f@f63g2000hsf.googlegroups.com> Message-ID: <0058c2b4-1489-4d31-bb8a-f8b7bb0f8d6e@2g2000hsn.googlegroups.com> On Aug 12, 10:06?am, Wojtek Walczak wrote: > > And keep in mind that reload() is removed in Py3k. Hope this helps. It's not gone; it's just renamed to imp.reload. > > -- > Regards, > Wojtek Walczak,http://www.stud.umk.pl/~wojtekwa/ From mensanator at aol.com Tue Aug 12 00:25:55 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 11 Aug 2008 21:25:55 -0700 (PDT) Subject: list question... unique values in all possible unique spots References: <57fcf019-1afd-4c48-b329-42a0ffc4c5ac@x35g2000hsb.googlegroups.com> <90f040d9-ce7e-440f-96e1-785c47242bdb@k30g2000hse.googlegroups.com> <8471c20a-06f6-4927-967a-7eae395c3055@79g2000hsk.googlegroups.com> Message-ID: <2b0bd9b5-e5b6-4924-a0ce-b4d2a3bae63b@w7g2000hsa.googlegroups.com> On Aug 11, 7:34?pm, bearophileH... at lycos.com wrote: > Mensanator: > > > Ever tried to iterate 403 septillion times? > > The OP is talking about formulas, like: > X + Y * Z = W > Where X, Y, Z, W distinct and in [1, 26], so you have C(26, 4) > combinations that's way less than 26! > > >>> binomial(26, 4) > > 14950 > > So this can be solved with a xcombinations() generator. How did you surmise it's C(26,4)? > > Bye, > bearophile From anishchapagain at gmail.com Fri Aug 29 07:48:27 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Fri, 29 Aug 2008 04:48:27 -0700 (PDT) Subject: problem with plotting References: <418c1e73-f6ac-4a3c-bd56-f461f9209e03@2g2000hsn.googlegroups.com> <49907d0b-b880-4c65-bdb3-70b6f5b6144f@k37g2000hsf.googlegroups.com> Message-ID: On Aug 29, 12:24?pm, "Eric_Dex... at msn.com" wrote: > On Aug 29, 6:01?am, Anish Chapagain wrote: > > > > > > > hi, > > I'm getting problem with the code below which after displaying graph > > plotted in external window, doesnot closes itself, even after closing > > the window of plotting the main python window shows processing. > > code goes like this... > > > plot(col1, col2, linewidth=1.0) > > xlabel('col1') > > ylabel('col2') > > title('Values from List created with file read') > > grid(True) > > savefig('col1 col2.pdf') > > show() > > > is there any other function to be called after show() to close it > > properly. > > > thank's for any help. > > > anish > > what library/system are you using???- Hide quoted text - > > - Show quoted text - Hi.. am using pylab and have added the print "plotting finished" after show() which get's printed in python main window but then doesnot return to prompt and have to kill the window again. regard's# anish From attn.steven.kuo at gmail.com Fri Aug 1 14:54:27 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Fri, 1 Aug 2008 11:54:27 -0700 (PDT) Subject: mapping a string to an instancemethod References: <7wIkk.16976$mh5.6016@nlpi067.nbdc.sbc.com> Message-ID: <02639d28-e074-406e-a954-ace3d9db694a@w1g2000prk.googlegroups.com> On Aug 1, 11:22 am, m... at pixar.com wrote: > The following bit of code will allow an instance member to > be called by reference. How can I map a string (e.g. > "hello1" or "Foo.hello1" to a the instance member? > > class Foo: > def hello1(self, p): > print 'hello1', p > def hello2(self, p): > print 'hello2', p > def dispatch(self, func, p): > func(self,p) > > f=Foo() > f.dispatch(Foo.hello1, 23) > f.dispatch(Foo.hello1, 24) > > f.dispatch_as_string("hello1", 23) ## this is what I want to do. > > Many TIA and apologies if this is a FAQ, I googled and couldn't > find the answer. Use getattr; add exception handling as needed. E.g., class Foo(object): def __init__(self): self.fake = None def hello1(self, p): print 'hello1', p def hello2(self, p): print 'hello2', p def dispatch_as_string(self, fname, p): try: inst_method=getattr(self, fname) inst_method(p) except AttributeError: # maybe no such attribute raise except TypeError: # maybe the attribute is not callable (wrong type) raise f = Foo() f.dispatch_as_string('hello1', 12) -- Hope this helps, Steven From bdesth.quelquechose at free.quelquepart.fr Sun Aug 17 06:09:43 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 17 Aug 2008 12:09:43 +0200 Subject: how to add property "dynamically"? In-Reply-To: References: Message-ID: <48a814d9$0$10444$426a74cc@news.free.fr> akonsu a ?crit : > hello, > > i need to add properties to instances dynamically during run time. > this is because their names are determined by the database contents. > so far i found a way to add methods on demand: > > class A(object) : > def __getattr__(self, name) : > if name == 'test' : > def f() : return 'test' > setattr(self, name, f) > return f > else : > raise AttributeError("'%s' object has no attribute '%s'" % > (self.__class__.__name__, name)) > this seems to work and i can invoke method test() on an object. Nope. This adds per-instance *function* attributes - not *methods*. class A(object) : def __getattr__(self, name) : if name == 'test' : def f(self) : return "%s.test" % self setattr(self, name, f) return f else : raise AttributeError( "'%s' object has no attribute '%s'" \ % (self.__class__.__name__, name) ) a = A() a.test() => Traceback (most recent call last): File "", line 1, in TypeError: f() takes exactly 1 argument (0 given) To add methods on a per-instance basis, you have to manually invoke the descriptor protocol's implementation of function objects: class A(object) : def __getattr__(self, name) : if name == 'test' : def f(self) : return "%s.test" % self m = f.__get__(self, type(self)) setattr(self, name, m) return m else : raise AttributeError( "'%s' object has no attribute '%s'" \ % (self.__class__.__name__, name) ) > it > would be nice to have it as property though. so i tried: > > class A(object) : > def __getattr__(self, name) : > if name == 'test' : > def f() : return 'test' > setattr(self, name, property(f)) > return f > else : > raise AttributeError("'%s' object has no attribute '%s'" % > (self.__class__.__name__, name)) > > but this does not work, instance.test returns a callable but does not > call it. Properties must be class attributes. The only way (the only way I know) to get them to work as instance-attributes is to overload __getattribute__, which is tricky and may have pretty bad impact on lookup perfs - and ruins the whole point of using properties FWIW. > i am not an expert in python, would someone please tell me what i am > doing wrong? Wrong solution to your problem, I'd say. Let's start again: """ > i need to add properties to instances dynamically during run time. > this is because their names are determined by the database contents. """ Care to elaborate ? I may be wrong, but I suspect you're trying to roll your own python/database mapper. If so, there are quite a couple Python ORMs around. Else, please tell us more. From Edwin.Madari at VerizonWireless.com Tue Aug 19 11:56:28 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Tue, 19 Aug 2008 11:56:28 -0400 Subject: who to call a list of method inside the class itself In-Reply-To: Message-ID: <20080819155641.63F621E4006@bag.python.org> fredrik at pythonware.com wrote: > > Edwin.Madari at VerizonWireless.com wrote: > > > 1. return string names of required methods in getAllMethod > > return ['method1', 'method2', 'method3'] > > 2. use gettattr on self and then exetute methods in applyAll > > def applyAll(self): > > for method_name in self.getAllMethod(): > > method = gettattr(self,method_name) > > method() #execute method now > > why? ensure instance's method invocation with all state information to that point, rather than relying on implemenation. regards. Edwin The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From ironfroggy at gmail.com Tue Aug 12 09:51:30 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Tue, 12 Aug 2008 09:51:30 -0400 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> Message-ID: <76fd5acf0808120651u259e5d8dt32a8d49bb5d77add@mail.gmail.com> The simple answer is "Dont nest classes. It is not supported." What you are seeing is really an artifact of how classes are built. Basically, everything inside the class body has to exist before it can run, so the inner classes code objects are actually created first. However, the class object itself isnt created out of that until the body of the outer class is evaluated. On Tue, Aug 12, 2008 at 5:29 AM, Cousson, Benoit wrote: > Hi, > > I'd like to be able to use a nested class (C1) from another sibling nested class (C3). This looks very similar to the nested scopes of functions except that it does not work. > > class A(object): > pass > > class B(object): > > class C1(object): > pass > > class C2(C1): > foo = A > > class C3(object): > foo = C1 > > The funny thing is that C2 can inherit from C1 but C3 cannot reference C1. B.C1 does not work either, but in that case it makes sense since B is still being defined. > Is this a language limitation or something that does not make sense at all? > > I'm wondering as well if the new nonlocal statement will fix that in py3k? > > Thanks in advance, > Benoit > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From apardon at forel.vub.ac.be Fri Aug 1 04:35:12 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 1 Aug 2008 08:35:12 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <9f4b1c12-d010-45f6-91ee-d490e2f850dc@79g2000hsk.googlegroups.com> Message-ID: On 2008-08-01, Erik Max Francis wrote: > Antoon Pardon wrote: > >> I now have the following question for people who argue that "if x" >> is more polymorphic. I could subclass list, so that instances >> of this new sequence would always behave as true, even if they are >> empty. I could then rewrite my loop as follows: >> >> while 1: >> extra = produce() >> if not extra: >> break >> for el in extra: >> adjust_with(el) >> calculate() >> >> Is this second loop now more polymorphic as the first? > > It's more confusing since you've changed the standard behavior of a > standard type, which doesn't really have anything to do with > polymorphism. It's more confusing, if that's a benefit. So you accept my point that "if x" can be less polymorphic and in fact can be more confusing than a more specific test. -- Antoon Pardon From hubaghdadi at gmail.com Sun Aug 24 04:32:34 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Sun, 24 Aug 2008 01:32:34 -0700 (PDT) Subject: What is class method? Message-ID: Hi, I'm familiar with static method concept, but what is the class method? how it does differ from static method? when to use it? -- class M: def method(cls, x): pass method = classmethod(method) -- Thank you for your time. From mattheww at chiark.greenend.org.uk Fri Aug 1 13:24:34 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 01 Aug 2008 18:24:34 +0100 (BST) Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> <00a23ad3$0$20313$c3e8da3@news.astraweb.com> Message-ID: Thomas Troeger wrote: > Will this disappear in Python 3.0., i.e. can you again simply write > > class A: > > and inherit from object automagically? Short answer: yes. -M- From Nikolaus at rath.org Mon Aug 4 09:30:51 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 04 Aug 2008 15:30:51 +0200 Subject: Locking around Message-ID: <87ej547vqs.fsf@nokile.rath.org> Hello, I need to synchronize the access to a couple of hundred-thousand files[1]. It seems to me that creating one lock object for each of the files is a waste of resources, but I cannot use a global lock for all of them either (since the locked operations go over the network, this would make the whole application essentially single-threaded even though most operations act on different files). My idea is therefore to create and destroy per-file locks "on-demand" and to protect the creation and destruction by a global lock (self.global_lock). For that, I add a "usage counter" (wlock.user_count) to each lock, and destroy the lock when it reaches zero. The number of currently active lock objects is stored in a dict: def lock_s3key(s3key): self.global_lock.acquire() try: # If there is a lock object, use it if self.key_lock.has_key(s3key): wlock = self.key_lock[s3key] wlock.user_count += 1 lock = wlock.lock # otherwise create a new lock object else: wlock = WrappedLock() wlock.lock = threading.Lock() wlock.user_count = 1 self.key_lock[s3key] = wlock finally: self.global_lock.release() # Lock the key itself lock.acquire() and similarly def unlock_s3key(s3key): # Lock dictionary of lock objects self.global_lock.acquire() try: # Get lock object wlock = self.key_lock[s3key] # Unlock key wlock.lock.release() # We don't use the lock object any longer wlock.user_count -= 1 # If no other thread uses the lock, dispose it if wlock.user_count == 0: del self.key_lock[s3key] assert wlock.user_count >= 0 finally: self.global_lock.release() WrappedLock is just an empty class that allows me to add the additional user_count attribute. My questions: - Does that look like a proper solution, or does anyone have a better one? - Did I overlook any deadlock possibilities? Best, Nikolaus [1] Actually, it's not really files (because in that case I could use fcntl) but blobs stored on Amazon S3. -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From fredrik at pythonware.com Tue Aug 5 10:37:07 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 05 Aug 2008 16:37:07 +0200 Subject: Python FTP - NameError: name 'mydpa' is not defined In-Reply-To: References: Message-ID: Ej wrote: > I have a similar problem. I need to download the same file every hour > so it will be nice to be able to rename the downloads with a variable > name. > > For example in this case: > > from ftplib import FTP > ftp=FTP('tgftp.nws.noaa.gov') > ftp.login() > ftp.cwd('SL.us008001/DF.of/DC.radar/DS.81dpr/SI.kbuf') > ftp.retrbinar('RETR sn.last', open('sn','wb').write) > ftp.quit() > > Question: How to achive rename the downloaded files as sn1, sn2, > sn3.... or with a timestamp? you're downloading to the file name you pass to open ("sn" in your case), so to download to a different file, just pass in another name. to rename an existing file on the local file system, use os.rename. From claird at lairds.us Sat Aug 23 11:29:35 2008 From: claird at lairds.us (Cameron Laird) Date: Sat, 23 Aug 2008 15:29:35 +0000 Subject: rules of thumb for cross os code References: <76c97ae9-2ca0-4419-8630-c7cf6159811a@v16g2000prc.googlegroups.com> Message-ID: In article <76c97ae9-2ca0-4419-8630-c7cf6159811a at v16g2000prc.googlegroups.com>, DwBear75 wrote: >I am considering using python as a replacement for a lot of bash >scripting that I have been doing. I would like to be as cross platform . . . >2) nifty lambda's or other things to create functions fit for the >environment >3) capturing return codes of other executables called from python; ie >use os.system, or popen? or ? I don't understand 2); maybe is a response, although I suspect it's at a different level than you had in mind. For 3), read on "Replacing os.system()", although I have several personal quibbles with details of the subprocess reference documentation. From deets at nospam.web.de Fri Aug 22 10:49:46 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 22 Aug 2008 16:49:46 +0200 Subject: Should Python raise a warning for mutable default arguments? In-Reply-To: <00becb2d$0$20312$c3e8da3@news.astraweb.com> References: <00becb2d$0$20312$c3e8da3@news.astraweb.com> Message-ID: <6h820aFjrnqtU1@mid.uni-berlin.de> Steven D'Aprano schrieb: > Sometimes it seems that barely a day goes by without some newbie, or not- > so-newbie, getting confused by the behaviour of functions with mutable > default arguments. No sooner does one thread finally, and painfully, fade > away than another one starts up. > > I suggest that Python should raise warnings.RuntimeWarning (or similar?) > when a function is defined with a default argument consisting of a list, > dict or set. (This is not meant as an exhaustive list of all possible > mutable types, but as the most common ones that I expect will trip up > newbies.) The warning should refer to the relevant FAQ or section in the > docs. I just suggested a documentation enhancement in one of the plethora of threads... so I'm certainly +1 for any enhancement in this area. Diez From siona at chiark.greenend.org.uk Fri Aug 29 09:14:03 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 29 Aug 2008 14:14:03 +0100 (BST) Subject: file data to list References: <8804b75e-0dd9-4d3a-be69-ccb6c12f6a9d@b1g2000hsg.googlegroups.com> Message-ID: Emile van Sebille wrote: >data = zip(*[xx.split() for xx in open('data.txt').read().split("\n")]) Files are iterable: data = zip(*[xx.rstrip().split() for xx in open('data.txt')]) saves you creating the extra intermediate list resulting from split("\n"). -- \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" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From http Wed Aug 27 01:39:56 2008 From: http (Paul Rubin) Date: 26 Aug 2008 22:39:56 -0700 Subject: atomic increment References: <6297cf93-5eec-4bf3-9104-0605a82f7186@p10g2000prf.googlegroups.com> <6hinduFmfmsrU1@mid.uni-berlin.de> <63533495-5cca-4430-9c9d-fbe1cfee0e1e@s50g2000hsb.googlegroups.com> Message-ID: <7xd4jvqamr.fsf@ruckus.brouhaha.com> Frank Millman writes: > Just out of interest, would the following, without a lock, be safe? > old, atomic_int = atomic_int, atomic_int+1 No I don't think so. But I'm told that in CPython, you can say counter = iter(xrange(10000000)) # some number that exceeds what you'll use ... atomic_int = counter.next() and the GIL keeps it safe. When in doubt, use a lock or communicate with other threads through Queues. From sln at netherlands.com Fri Aug 22 18:56:09 2008 From: sln at netherlands.com (sln at netherlands.com) Date: Fri, 22 Aug 2008 22:56:09 GMT Subject: The Importance of Terminology's Quality References: <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: On Thu, 21 Aug 2008 09:11:48 -0500, rpw3 at rpw3.org (Rob Warnock) wrote: >sln at netherlands.com> wrote: >+--------------- >| rpw3 at rpw3.org (Rob Warnock) wrote: >| >In the LGP-30, they used hex addresses, sort of[1], but the opcodes >| >(all 16 of them) had single-letter mnemonics chosen so that the >| >low 4 bits of the character codes *were* the correct nibble for >| >the opcode! ;-} >... >| >[1] The LGP-30 character code was defined before the industry had >| > yet standardized on a common "hex" character set, so instead of >| > "0123456789abcdef" they used "0123456789fgjkqw". [The "fgjkqw" >| > were some random characters on the Flexowriter keyboard whose low >| > 4 bits just happened to be what we now call 0xa-0xf]. Even worse, >| > the sector addresses of instructions were *not* right-justified >| > in the machine word (off by one bit), plus because of the shift- >| > register nature of the accumulator you lost the low bit of each >| > machine word when you typed in instructions (or read them from >| > tape), so the address values you used in coding went up by *4*! >| > That is, machine locations were counted [*and* coded, in both >| > absolute machine code & assembler] as "0", "4", "8", "j", "10", >| > "14", "18", "1j" (pronounced "J-teen"!!), etc. >| >| Whats os interresting about all this hullabaloo is that nobody has >| coded machine code here, and know's squat about it. >+--------------- > >Think again! *BOTH* of the two examples I gave -- for the LGP-30 & the >IBM 1410 -- *WERE* raw machine code, *NOT* assembler!!! Please read again >what I wrote about the character codes for the instruction mnemonics >*BEING* the machine instruction codes. For the IBM 1410, the bootstrap >code that ones types in: > > v v > L%B000012$N > >*IS* raw machine code, *NOT* assembler!! [snip] I don't see the distinction. Just dissasemble it and find out. > >you're typing *RAW* machine code, *NOT* assembler!! You see, the >lower 4 bits of character "b" -- the "mnemonic" for "Bring" -- were >binary 0001, the *same* as the lower 4 bits of the digit "1" (and two >other characters as well). So when you typed a "b" in that position >in "4-bit input mode" you were typing the same thing as the character "1" >which was the same thing as *binary* 0001 which was the absolute machine >opcode for the ""Bring" instruction!! "No assembler required" (pardon >the pun). > >+--------------- >| I'm not talking assembly language. >+--------------- > >Neither was I. The fact that for the two machines I mentioned >absolute machine code was somewhat readable to humans seems to >have confused you, but that's the way some people liked to design >their hardware back in those days -- with clever punning of character >codes with absolute machine opcodes (for the convenience of the user). > >+--------------- >| Don't you know that there are routines that program machine code? >+--------------- > >What do you mean "routines"?!? For the above two machines, you can >enter machine code with *no* programs ("routines?") running; that is, >no boot ROM is required (or even available, as it happened). > [snip all the bullshit] Each op is a routine in microcode. That is machine code. Those op routines use machine cycles. You hit the wall of understanding along time ago, a wall you never looked past. sln From vbp6ynr02 at sneakemail.com Sun Aug 24 10:28:53 2008 From: vbp6ynr02 at sneakemail.com (twyk) Date: Sun, 24 Aug 2008 07:28:53 -0700 (PDT) Subject: PEP 8: Byte Order Mark (BOM) vs coding cookie Message-ID: <186d34d3-c3a9-4d95-984f-89ce36d7b64f@59g2000hsb.googlegroups.com> PEP 8 says ... Files using ASCII (or UTF-8, for Python 3.0) should not have a coding cookie. What about a BOM (Byte Order Mark)? Per Wikipedia ... http://en.wikipedia.org/wiki/Byte-order_mark#endnote_UTF-8) 'In UTF-8, this is not really a "byte order" mark. It identifies the text as UTF-8 but doesn't say anything about the byte order, because UTF-8 does not have byte order issues.' So is it good style to omit the BOM in UTF-8 for Python 3.0? From jldunn2000 at googlemail.com Thu Aug 21 10:53:39 2008 From: jldunn2000 at googlemail.com (loial) Date: Thu, 21 Aug 2008 07:53:39 -0700 (PDT) Subject: Question re ConfigParser References: <63c0f1df-404c-4e09-8605-0f8bdc6a333a@k13g2000hse.googlegroups.com> <0d5c1706-ca81-4e76-bce4-7e63ab915605@x16g2000prn.googlegroups.com> Message-ID: <75ddf31b-b2d6-4e75-b69a-6b093a32ad46@y38g2000hsy.googlegroups.com> On 20 Aug, 13:49, alex23 wrote: > On Aug 20, 5:34?pm, loial wrote: > > > Given a section like > > > [Data] > > value1 > > value2 > > value3 > > > Can ConfigParser be easily used to put the values in a dictionary? If > > so, how? > > Dictionaries are key/value pairs. Do you expect 'value1' to be a key > or a value? > > If the data is literally as you describe, and not key/value entries > (such as 'key1: value1' or 'key1=value1'), you would probably be > better off just stepping through the file, testing for the [data] > section and then reading the following lines into a list. Thanks. Thats what I did in the end From gagsl-py2 at yahoo.com.ar Tue Aug 12 01:23:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Aug 2008 02:23:46 -0300 Subject: Starting seperate programs References: Message-ID: En Thu, 07 Aug 2008 10:03:59 -0300, David Dean escribi?: > Is there a way for a python program start another python program, and > then continue, without waiting for the second program to finish? > os.startfile() seems to be what I want on windows, but I need it to work > on linux and mac as well. > Is there a function that does essentially the same as startfile, but > without needing an associtated program (i.e. asking for one)? os.system("python other_program.py") You may want to replace that "python" with sys.executable. -- Gabriel Genellina From shahmed at sfwmd.gov Thu Aug 14 11:50:57 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Thu, 14 Aug 2008 11:50:57 -0400 Subject: help with parsing email Message-ID: Hi all, I do appreciate if any one can help me for my following problem: I need to grab/parse numeric numbers such as app number from incoming emails stored in Microsoft Outlook (Microsoft Exchange server) with specified subject line. Any help with the python script is highly appreciated. The email body is like this myregion ; tst ; 11-Aug-2008 http://my.xyz.com/dddd/content/ifs/apps/myDocFolder/NoticeOfapplication/ 080612-21_test_337683.pdf I need to extract 080612-21_ number from above line from incoming emails. Thanks sk -------------- next part -------------- An HTML attachment was scrubbed... URL: From half.italian at gmail.com Thu Aug 7 11:51:00 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 7 Aug 2008 08:51:00 -0700 (PDT) Subject: Testing for the first few letters of a string References: Message-ID: try string1 = "My name is alex" string2 = "My name is alex, and I like pie" if string2.startswith(string1): process() or if you want to match a set number of characters you can use a slice: if string2[:15] == string1[:15]: process() or if you dont care where the characters appear in the string, beginning, middle, end, etc: if string2 in string1: process() Theres lots of other ways as well. http://docs.python.org/lib/string-methods.html ~Sean On Aug 7, 8:40?am, Alexnb wrote: > Okay, I have a fix for this problem, but it is messy and I think there might > be a better way. Heres an example: > > Lets say I have a string: "My name is alex" > > and I have another string "My name is alex, and I like pie". > > I want to test to see if just the "My name is alex" part is there. I don't > care about the pie part. > My first instinct was to just create a for loop and test for the string like > this: > > n = 0 > > for x in string1: > ? ? ? if string1[n] == string2[n] > ? ? ? ? ? ? n = n +0 > ? ? ? else: > ? ? ? ? ? ? break > and then later testing to see what n was = to and figuring out if it got > through the whole loop. I feel like there should be an easier way to do > this, and probably is. So Does anyone have a suggestion? > -- > View this message in context:http://www.nabble.com/Testing-for-the-first-few-letters-of-a-string-t... > Sent from the Python - python-list mailing list archive at Nabble.com. From castironpi at gmail.com Sun Aug 24 22:42:35 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 24 Aug 2008 19:42:35 -0700 (PDT) Subject: property() usage - is this as good as it gets? References: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> <9dc512a3-a0ba-461a-a242-c2681b7db42e@a8g2000prf.googlegroups.com> Message-ID: On Aug 24, 7:43?pm, alex23 wrote: > castironpi wrote: > > Python isn't as clever as you think. ?It's a language. ? > > Yet another non-sequitur response from you. At which point in my post > did I make any such claims about Python's 'cleverness'? > > > Do you want a > > link to clever code? ? > > Not if you wrote it or find it clever, no. > > To quote Kernighan: "Debugging is twice as hard as writing the code in > the first place. Therefore, if you write the code as cleverly as > possible, you are, by definition, not smart enough to debug it." > > When the code in question is one of the abstract monstrosities you > regularly post here - often in response to _new python users_ asking > _basic_ questions that _don't require metaclass solutions_ - I've > repeatedly found the cost in interpreting it is just never worth the > time and effort required. > > > I like to encourage creativity. > > Then why do you seem to stymie it? Care to go back through the > responses to your posts and tally up the "thanks, that makes sense!" > replies to the "I don't get what you mean here" ones? > > If you're seriously attempting to educate, you're failing. If you're > trying to show how blazingly clever you are, you're failing at that, > too. > > When people seem to generally consider you a markov chainer, that - > should- be a sign to work on the clarity of your communication. I'm baffled. I don't understand what you write. I think someone in my shoes would be justified in dismissing it as either malicious or a miscommunication. My typical response is, take something I've said in context, and show how it fulfills the criteria you describe. For instance, "I won't like it if you do" and "I won't think it's clever if you do" aren't consistent belief structures, they're fight structures. You have made such claims. In the post above, I make two claims, ask two questions, and encourage a brainstorm. I don't see how what you say applies to it. I am willing to change the way I communicate. I want to communicate effectively. But, until someone takes something I want to say, and says it the right way, I can't learn how. So I wait and write Python, and share my frustration with my peers. Lastly, in the syllogism you propose, "not smart enough to debug it", you equate maximally clever writing with maximally clever debugging, which is clearly wrong. They are distinct; someone could be better at either one than the other. And besides, your quoted premise "twice as hard" is assumed, not proven. From sjmachin at lexicon.net Mon Aug 18 19:35:14 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 18 Aug 2008 16:35:14 -0700 (PDT) Subject: Programming Languages Decisions References: Message-ID: <79db7bbe-a3dc-41d1-9b38-7b220116dd3c@a8g2000prf.googlegroups.com> On Aug 18, 10:59 pm, "E.D.G." wrote: > > If all goes according to plan, within a few weeks I will begin > circulating .exe copies of a Perl language disaster mitigation related > computer program that I have been developing during the past decade or so. A computer program that's related to "Perl language disaster mitigation"? I would have thought that it would take the average sentient being less than 10 *days* to nut out that the best strategy to mitigate Perl language disaster was to avoid using that language altogether. From wuwei23 at gmail.com Fri Aug 1 00:52:32 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 31 Jul 2008 21:52:32 -0700 (PDT) Subject: HELP - Attribute Error, no matter what I do on PAMIE... References: <38ed1b14-fb96-4891-9188-c62337aeef89@f36g2000hsa.googlegroups.com> Message-ID: On Aug 1, 1:00?am, frankrentef wrote: > Greetings all. I'm new to PAMIE and I've watched / followed to PAMIE > videos on Show me Do. I've tried to duplicate the "scriptWrite" > function in an attempt to automate the forms process... without > success. I haven't seen the video, bt by "duplicate the 'scriptWrite' function" do you mean you've implemented that yourself? I couldn't any such function in the PAMIE code. If so, could you throw that code into http://pastebin.com/ and link back to it here? That might help us with finding the problem. From dbickett at gmail.com Thu Aug 21 15:06:11 2008 From: dbickett at gmail.com (Daniel Bickett) Date: Thu, 21 Aug 2008 12:06:11 -0700 (PDT) Subject: Prevalent Python/Django academic software References: <3299bba4-b4fa-4c81-a5e2-b99ee4c5f8c2@w7g2000hsa.googlegroups.com> Message-ID: <4a6faa5c-663e-4ac5-bd84-c39eb3555861@l42g2000hsc.googlegroups.com> On Aug 21, 7:39 am, cla... at lairds.us (Cameron Laird) wrote: > I don't understand the question. YES, there are MANY > Python-based applications doing service in a variety > of academic contexts. No, there is no central index > of all such programs. Sorry if I was unclear. If there are many such applications, very good! I hope to use them. Certainly there seems not to be any sort of central index, which was why I hoped to hear the opinion of various c.l.py users. Tobias: No, money is not one of my objectives. Neither is paying for software, however, which is why I wondered if anyone was currently developing any relevant, open-source applications. I had not heard the name Moodle, thank you. dbickett From ramen at lackingtalent.com Thu Aug 21 01:17:35 2008 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 20 Aug 2008 22:17:35 -0700 Subject: Factory for Struct-like classes In-Reply-To: <3dec7f3e-0cd2-40ee-a4d4-74935eabae5a@k13g2000hse.googlegroups.com> References: <1N4rk.167$_s1.91@newsfe07.iad> <3dec7f3e-0cd2-40ee-a4d4-74935eabae5a@k13g2000hse.googlegroups.com> Message-ID: eliben wrote: >> Whaaa? Named tuples are being added to Python? Neat! Is there any >> documentation on this? I can't seem to find anything on the web... > > It's not easy to find unless you recall where you've seen it: > http://docs.python.org/dev/3.0/library/collections.html#collections.namedtuple Thanks! From deets at nospam.web.de Tue Aug 19 04:46:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 19 Aug 2008 10:46:26 +0200 Subject: Python Substitute for PHP GD, Resizing an image on the client side References: <02f733bb-e734-46a9-b42f-5b664cdddd3f@v26g2000prm.googlegroups.com> <6gv91bFhm5u5U1@mid.uni-berlin.de> <86256d88-2bf9-4818-9df9-d798ae9ff025@a2g2000prm.googlegroups.com> Message-ID: <6gvfkuFhki87U1@mid.uni-berlin.de> > Does anyone have any code that does the javascript "selecting the > rectangle bit" and uploading to the server. I've based my work in this field on some freely available JS, but don't know what it was called. Google is your friend here. > Also incidentally is ftp > or put the recommended way to go for uploading the reduced image to > the server? In the same way any other uploading is done in browsers when a website is involved: using HTTP POST. Use the -tag, and make sure the server-side will store a transmitted file properly. Frameworks such as TurboGears (1 or 2) and Django will do that for you. Diez From fredrik at pythonware.com Sat Aug 23 06:15:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 23 Aug 2008 12:15:06 +0200 Subject: Is my thinking Pythonic? In-Reply-To: <48ae84de$0$13858$426a34cc@news.free.fr> References: <638bf217-3eaf-43af-8604-4145aa156afe@m73g2000hsh.googlegroups.com> <39fcb558-2869-438b-9309-e55ccfed7ec6@i24g2000prf.googlegroups.com> <48add182$0$12232$426a74cc@news.free.fr> <48ae84de$0$13858$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Given the lack of proper support for the descriptor protocol in > old-style classes and a couple other diverging behaviors, I wouldn't say > that advising newcomers to use new-style classes is so pointless. Yeah, but if you don't need descriptors, new-style classes don't buy you anything (except a slight slowdown in certain situations). Dogmatic use of new-style classes (or any other "new" feature) isn't "pythonic". From anishchapagain at gmail.com Wed Aug 13 06:52:56 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Wed, 13 Aug 2008 03:52:56 -0700 (PDT) Subject: Parse error befor % token Message-ID: <7f97ab7f-4deb-491d-a729-bc7b560ff685@59g2000hsb.googlegroups.com> Hi, i tried to compile the swig .i file but am having probel with the error: parse error before % token example.i 1. %module example 2. %{ 3. #include 4. %} 5. 6. %include "header.h" i have setup.py file and am running through, >>python setup.py build_ext but is showing parse error before % token in example.i in line 1 and also in 4. Thank's for any help on this matter in advance also, is there any live example having multiple .i files in single interface SWIG file. cheer's From sjmachin at lexicon.net Sat Aug 9 17:43:36 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 9 Aug 2008 14:43:36 -0700 (PDT) Subject: Fastest way to store ints and floats on disk References: <489B41CE.8080909@shopzeus.com> <1ad14df7-09ea-4b1d-8fac-3025bdd2d522@f63g2000hsf.googlegroups.com> Message-ID: <380b121c-4595-4618-95f3-b8c50c8b39c8@k36g2000pri.googlegroups.com> On Aug 10, 4:58 am, castironpi wrote: > On Aug 7, 2:27 pm, "M.-A. Lemburg" wrote: > > > > > On 2008-08-07 20:41, Laszlo Nagy wrote: > > > > Hi, > > > > I'm working on a pivot table. I would like to write it in Python. I > > > know, I should be doing that in C, but I would like to create a cross > > > platform version which can deal with smaller databases (not more than a > > > million facts). > > > > The data is first imported from a csv file: the user selects which > > > columns contain dimension and measure data (and which columns to > > > ignore). In the next step I would like to build up a database that is > > > efficient enough to be used for making pivot tables. Here is my idea for > > > the database: > > > > Original CSV file with column header and values: > > > > "Color","Year","Make","Price","VMax" > > > Yellow,2000,Ferrari,100000,254 > > > Blue,2003,Volvo,50000,210 > > > > Using the GUI, it is converted to this: > > > > dimensions = [ > > > { 'name':'Color', 'colindex:0, 'values':[ 'Red', 'Blue', 'Green', > > > 'Yellow' ], }, > > > { 'name':'Year', colindex:1, 'values':[ > > > 1995,1999,2000,2001,2002,2003,2007 ], }, > > > { 'name':'Make', colindex:2, 'value':[ 'Ferrari', 'Volvo', 'Ford', > > > 'Lamborgini' ], }, > > > ] > > > measures = [ > > > { 'name', 'Price', 'colindex':3 }, > > > { 'name', 'Vmax', 'colindex':4 }, > > > ] > > > facts = [ > > > ( (3,2,0),(100000.0,254.0) ), # ( dimension_value_indexes, > > > measure_values ) > > > ( (1,5,1),(50000.0,210.0) ), > > > .... # Some million rows or less > > > ] > > > > The core of the idea is that, when using a relatively small number of > > > possible values for each dimension, the facts table becomes > > > significantly smaller and easier to process. (Processing the facts would > > > be: iterate over facts, filter out some of them, create statistical > > > values of the measures, grouped by dimensions.) > > > > The facts table cannot be kept in memory because it is too big. I need > > > to store it on disk, be able to read incrementally, and make statistics. > > > In most cases, the "statistic" will be simple sum of the measures, and > > > counting the number of facts affected. To be effective, reading the > > > facts from disk should not involve complex conversions. For this reason, > > > storing in CSV or XML or any textual format would be bad. I'm thinking > > > about a binary format, but how can I interface that with Python? > > > > I already looked at: > > > > - xdrlib, which throws me DeprecationWarning when I store some integers > > > - struct which uses format string for each read operation, I'm concerned > > > about its speed > > > > What else can I use? > > > >>> import marshal > > >>> marshal.dump(1, open('test.db', 'wb')) > > >>> marshal.load(open('test.db', 'rb')) > > 1 > > > It also very fast at dumping/loading lists, tuples, dictionaries, > > floats, etc. > > Depending on how hard-core you want to be, store the int, float, > string, and long C structures directly to disk, at a given offset. > Either use fixed-length strings, or implement (or find) a memory > manager. Anyone have a good alloc-realloc-free library, C or Python? A long time ago, when I last needed to bother about such things (to override the memory allocator in the DJGPP RTL), Doug Lea's malloc did the trick. A memory allocator written in Python? That's a novel concept. From bj_666 at gmx.net Mon Aug 25 17:30:13 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Aug 2008 21:30:13 GMT Subject: Private attribute References: <076a50cb-99ad-44c5-b4eb-17a45ee1abe9@c65g2000hsa.googlegroups.com> Message-ID: <6hgmj5Flo1i6U4@mid.uni-berlin.de> On Mon, 25 Aug 2008 21:44:49 +0100, Ken Starks wrote: >>> #################### >>> >>> def __getattr__(self,attrname): >>> if attrname == 'gridsize': >>> return 0.8 >>> >>> def __setattr__(self,attrname,value): >>> if attrname == 'gridsize': >>> pass >>> else: >>> self.__dict__[attrname]=value >> [?] > > I admit I haven't used properties, and had to look them up. Pretty cool > indeed ! But an extra unnecessary level of complexity for my needs > here, I feel. Compare this with your approach above and point out the extra complexity please: @property def gridsize(self): return 0.8 Ciao, Marc 'BlackJack' Rintsch From hanlray at gmail.com Tue Aug 12 04:42:26 2008 From: hanlray at gmail.com (ray) Date: Tue, 12 Aug 2008 01:42:26 -0700 (PDT) Subject: How to iterate a sequence, with skipping the first item? References: Message-ID: Thanks you guys. Now I understand the -for- loop mechanism. From cypriankumwaka at yahoo.com Wed Aug 13 01:58:38 2008 From: cypriankumwaka at yahoo.com (Cyprian Kumwaka) Date: Wed, 13 Aug 2008 05:58:38 -0000 Subject: Downloading and Installing gasp Message-ID: I am a beginner in Python. Please tell me how to go about in downloading and installing the module gasp.I am using Python 2.5.2. From bockman at virgilio.it Thu Aug 28 08:06:16 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Thu, 28 Aug 2008 05:06:16 -0700 (PDT) Subject: Python sockets UDP broadcast multicast question?? References: <57a408ba-2cfd-4b79-9832-f741a55ac18f@d1g2000hsg.googlegroups.com> Message-ID: On 28 Ago, 08:09, inorlando wrote: > Hi all, > > I have a question about python and sockets , UDP datagram in > particular. I'm new to socket programming so please bare with me. > > I am trying to write a simple application that broadcast files to > another computer on the same network/subnet but I do not want the > receiver computer to have to respond, I only want it to receive the > packet. > > So this was simple enough, but my problem is this when I send a file > that is say larger then 100K the receiver is not able to keep up with > the packets as they arrive. I get say 60 or so then the rest are > ignored. > > I have tried a couple of different approaches like threading and > queuing, ?but all ultimately have the same problem. > > So my question is how can I receive a continuous stream of UDP packets > to some kind of buffer for processing with out losing packets? > > Thank you for any help or guidance that you provide. > > - InOrlando The UDP protocol is defined 'unreliable' because it cannot guarantee in all conditions the delivery of all packets in the correct sequence. This means than in specific conditions, e.g. when the network or one of the communicating computers is overloaded, you can loose packets or receive them in the wrong order. So, first of all, if you cannon tolerate packet loss, consider switching the protocol to TCP. If you cannot change protocol (maybe because TCP has no multicast), then try to reduce the load on the computer and the network, e.g. by inserting a delay between two packet transmissions. But remember that this only reduce, does not cancel, the possibility of packet loss or packet mis-ordering. Of course, it could be a bug in your program, in which case none of the above matters ;) Ciao ----- FB From george.sakkis at gmail.com Fri Aug 29 13:42:11 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 29 Aug 2008 10:42:11 -0700 (PDT) Subject: When to use try and except? References: <8a2dd955-6641-493d-b7eb-3e29c14686a5@26g2000hsk.googlegroups.com> Message-ID: On Aug 29, 1:23 pm, cnb wrote: > If I get zero division error it is obv a poor solution to do try and > except since it can be solved with an if-clause. > > However if a program runs out of memory I should just let it crash > right? Because if not then I'd have to write exceptions everywhere to > prevent that right? > > So when would I actually use try-except? Whenever you can do something *meaningful* in the except block to handle the exception (e.g. recover). Is there any meaningful action you can take when you run out of memory ? If yes (e.g. write current data to the disk and open a popup window that informs ths user), then use try/except, otherwise don't. IOW code like the following try: ... except MemoryError: print "You ran out of memory!" is typically useless; better let the exception propagate to the top level with a full traceback. HTH, George From castironpi at gmail.com Sun Aug 24 10:12:22 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 24 Aug 2008 07:12:22 -0700 (PDT) Subject: Best way to set/get an object property References: Message-ID: On Aug 24, 5:07?am, Hussein B wrote: > Hey, > I noted that Python encourage the usage of: > -- > obj.prop = data > x = obj.prop > -- > to set/get an object's property value. > What if I want to run some logic upon setting/getting a property? > What is Python preferred method to do so (using the new feature > 'property')? > I don't think __getattr__ and __setattr__ are practical (I have to > code the property name into them). > Thanks. The answer Hussein is you have both options in Python. If neither one is clearly better-suited to your new application, pick one and go. From alan.franzoni.blahblah at example.com.invalid Fri Aug 1 11:57:10 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Fri, 01 Aug 2008 15:57:10 GMT Subject: Strong/weak typing References: <6727fa22-aee9-4a9b-b9c0-08534aab6b34@m45g2000hsb.googlegroups.com> Message-ID: <1gzggry4ihm6l.g9by2ktuome2$.dlg@40tude.net> MartinRinehart at gmail.com was kind enough to say: > I'm writing Python as if it were strongly typed, never recycling a > name to hold a type other than the original type. > > Is this good software engineering practice, or am I missing something > Pythonic? Python *is* strongly typed. You're talking about dynamic typing, but that's not about "name reuse". -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From norseman at hughes.net Wed Aug 27 17:51:17 2008 From: norseman at hughes.net (norseman) Date: Wed, 27 Aug 2008 14:51:17 -0700 Subject: finding out the number of rows in a CSV file [Resolved] In-Reply-To: References: <3aaa109e-9a7e-4d02-8af5-0161251d7678@t54g2000hsg.googlegroups.com> <0bc6097f-af52-4951-a413-e9a983df93c7@79g2000hsk.googlegroups.com> Message-ID: <48B5CC55.90308@hughes.net> Peter Otten wrote: > John S wrote: > >> [OP] Jon Clements wrote: >>> On Aug 27, 12:54 pm, SimonPalmer wrote: >>>> after reading the file throughthe csv.reader for the length I cannot >>>> iterate over the rows. How do I reset the row iterator? >> A CSV file is just a text file. Don't use csv.reader for counting rows >> -- it's overkill. You can just read the file normally, counting lines >> (lines == rows). > > Wrong. A field may have embedded newlines: > >>>> import csv >>>> csv.writer(open("tmp.csv", "w")).writerow(["a" + "\n"*10 + "b"]) >>>> sum(1 for row in csv.reader(open("tmp.csv"))) > 1 >>>> sum(1 for line in open("tmp.csv")) > 11 > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > ============================= Well..... a semantics's problem here. A blank line is just an EOL by its self. Yes. I may want to count these. Could be indicative of a problem. Besides sum(1 for len(line)>0 in ...) handles problem if I'm not counting blanks and still avoids tossing, re-opening etc... Again - it's how you look at it, but I don't want EOLs in my dbase fields. csv was designed to 'dump' data base fields into text for those not affording a data base program and/or to convert between data base programs. By the way - has anyone seen a good spread sheet dumper? One that dumps the underlying formulas and such along with the display value? That would greatly facilitate portability, wouldn't it? (Yeah - the receiving would have to be able to read it. But it would be a start - yes?) Everyone got the point? Just because it gets abused doesn't mean .... Are we back on track? Number of lines equals number of reads - which is what was requested. No bytes magically disappearing. No slight of hand, no one dictating how to or what with .... The good part is everyone who reads this now knows two ways to approach the problem and the pros/cons of each. No loosers. Steve norseman at hughes.net From fredrik at pythonware.com Tue Aug 19 05:51:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Aug 2008 11:51:37 +0200 Subject: Handling Property and internal ('__') attribute inheritance and creation In-Reply-To: References: Message-ID: Eric Brunel wrote: > To add to what others have already said, it is not only 'just extra > work', it is also quite dangerous. See: > > class A(object): > children = [] the OP is aware of that, of course: > I set anything that is constant but anything variable is set again in > __init__() as long as if you're aware of the issues involved (which you should be if you're using Python professionally), using class-level attributes is a perfectly valid Python style. From stef.mientki at gmail.com Wed Aug 20 14:37:15 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 20 Aug 2008 20:37:15 +0200 Subject: evaluating code lines above breakpoints ? Message-ID: <48AC645B.6050705@gmail.com> hello, I'm trying to create a high level debugger, based on rpd2. So when the debugger enters a breakpoint, I want to display the values of all variables in the, let's say, 5 lines above the breakpoint (if possible). Any hints on how I get a list of all vars in those lines ? My rough idea is to scan the lines, skip keywords, test type of each term ( by eval), if the term is var eval the value of it. Are there better ways ? Another idea, when hoovering over a variable during a breakpoint, a hint appears with the type and value of that var. thanks, Stef Mientki From eglyph at gmail.com Sat Aug 23 05:47:29 2008 From: eglyph at gmail.com (eglyph at gmail.com) Date: Sat, 23 Aug 2008 02:47:29 -0700 (PDT) Subject: problems debugging python script on server References: <5011f266-8c65-4507-8682-1e10d05584a7@b30g2000prf.googlegroups.com> Message-ID: > cgitb.enable() to try to find the error, but with no success. I'm > really at a loss as to why it's generating this error. Apache's error_log and access_log are your friends. In this particular case your script breaks something http-server related: premature end of headers, incorrect permissions on script, wrong interpreter script, etc. Anyway the right reason is in the http server's logs. From hanlray at gmail.com Tue Aug 12 02:51:17 2008 From: hanlray at gmail.com (ray) Date: Mon, 11 Aug 2008 23:51:17 -0700 (PDT) Subject: How to iterate a sequence, with skipping the first item? Message-ID: A container object provides a method that returns an iterator object. I need to iterate the sequence with that iterator, but need to skip the first item. I can only iterate the whole sequence with: for x in container.iterChildren(): How to skip the first item? It seems that it's a simple question. Could somebody help me? Thanks. From bdesth.quelquechose at free.quelquepart.fr Tue Aug 26 15:42:03 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 26 Aug 2008 21:42:03 +0200 Subject: dynamically adding some of one module's functions to another In-Reply-To: References: Message-ID: <48b45c9d$0$10780$426a74cc@news.free.fr> Gabriel Rossetti a ?crit : > Hello everyone, > > I'm trying to import some modules into another's namespace (network_utils) > > network_utils.py: > > import utils > import constants as main_const > from services import constants as srv_const > from plugins import constants as plg_const > > # > # Import all the message creation functions > # > f = dict([ (f, eval("utils." + f)) for f in dir(utils) if > f.startswith("create") ]) As usual, you don't need eval here. Use getattr instead: create_functions = dict( (name, getattr(utils, name) for name in dir(utils) if name.startswith('create') ) > __builtins__.update(f) Python 2.5.1 (r251:54863, Apr 6 2008, 17:20:35) [GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> __builtins__ >>> type(__builtins__) >>> __builtins__.update Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'update' >>> Anyway, adding to builtins is certainly not the best thing to do. I don't know what you're trying to do here, but looks like a very ugly mess to me. > del utils > > # > # Create a virgin namespace > # > class constants: > """ > An aggragation of L{constants}, > L{services.constants}, & > L{plugins.constants} > """ > pass > # > # Import all the constants into the new namespace > # > f = dict([ (f, eval("main_const." + f)) for f in dir(main_const) if > f.isupper() ]) > constants.__dict__.update(f) > del main_const > f = dict([ (f, eval("srv_const." + f)) for f in dir(srv_const) if > f.isupper() ]) > constants.__dict__.update(f) > del srv_const > f = dict([ (f, eval("plg_const." + f)) for f in dir(plg_const) if > f.isupper() ]) > constants.__dict__.update(f) > del plg_const Yuck. In your constants.py file, just add the relevant imports: from services.constants import * from plugins.constants import * And then in your network_utils file: import constants But this is still a mess to me. The nice point with explicit import and modules namespaces is that you at least have a chance to know where a given symbol comes from. > > now, if I import network_utils somewhere, and try to call > network_utils.myFunction() I get : > > >>> import network_utils > >>> network_utils.myFunction > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'myFunction' And ? Where is the name myFunction bound in the above code ? > but if I try to access the constants class: > > >>> from network_utils import constants > >>> constants.NO_DATA_TYPE > 'none' > > it works, how come? I suppose NO_DATA_TYPE is defined somewhere in one of your constants.py files. Instead of messing with eval and builtins and wonder why something "works" and why something else doesn't, I strongly suggest you (re)read the part about imports, packages, modules etc in the FineManual. From pythonnutter at gmail.com Wed Aug 13 23:53:06 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Thu, 14 Aug 2008 13:53:06 +1000 Subject: An FTP Client...My first real program! In-Reply-To: References: <228e4214-01cf-4152-acdb-3743594f0581@e53g2000hsa.googlegroups.com> Message-ID: sorry cut off due to original email being sent not to the list due to gmail: A second for that suggestion--the ftp module in the python standard library is very low level and not very useful for beginners as a lot of the heavy lifting and management is still left up to you, the programmer. 2008/8/14 Python Nutter : > ery low level and not very useful for beginners as a lot of the heavy > lifting and management is still left up to you, the programmer. > > The module ftputil is a high-level interface to the ftplib module. The > FTPHost objects generated from it allow many operations similar to > those of os and os.path. An example: > > # download some files from the login directory > host = ftputil.FTPHost('ftp.domain.com', 'user', 'secret') > names = host.listdir(host.curdir) > for name in names: > if host.path.isfile(name): > host.download(name, name, 'b') # remote, local, binary mode > # make a new directory and copy a remote file into it > host.mkdir('newdir') > source = host.file('index.html', 'r') # file-like object > target = host.file('newdir/index.html', 'w') # file-like object > host.copyfileobj(source, target) # similar to shutil.copyfileobj > source.close() > target.close() > > > Now if you are again purely in it for a challenge or for and > educational roller coaster ride, ignore the suggestion to look at > higher level ftp modules =) > > Cheers, > PN > From michele.simionato at gmail.com Thu Aug 7 09:59:05 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 7 Aug 2008 06:59:05 -0700 (PDT) Subject: python-mode is missing the class browser Message-ID: <6361fac8-3bfb-4d7e-b13b-84261ebeea10@b1g2000hsg.googlegroups.com> I have noticed that the python-mode for Emacs that comes with the latest Ubuntu is missing the class browser. Moreover if works differently from the python-mode I was used to (for instance CTRL-c-c works as CTRL-c-! whereas CTRL-c-! is missing, etc). How can I go back to the old python-mode or at least how do I get back the class browser? Michele Simionato From maric at aristote.info Thu Aug 28 10:31:50 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 28 Aug 2008 16:31:50 +0200 Subject: Multiple values for one key In-Reply-To: <48B602B4.5080800@hughes.net> References: <26c69b160808271326w2f53b6b8s6e4aa7f91071ac71@mail.gmail.com> <48B602B4.5080800@hughes.net> Message-ID: <200808281631.51234.maric@aristote.info> Le Thursday 28 August 2008 03:43:16 norseman, vous avez ?crit?: > Terry Reedy wrote: > > Ron Brennan wrote: > >> Hello, > >> > >> > >> How would I create a dictionary that contains multiple values for one > >> key. > > > > Make the value a collection object (set or list if you plan to add and > > delete). > > > >> I'd also like the key to be able to have duplicate entries. > > > > Dict keys must be hashable and unique. > > > > tjr > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > ================ > First part I understand, second is still giving me a problem. > > For some reason I still want keys to be dbf column headers. > like: > > name:address:zip so forth > ---- ------- --- ------------------ > guy: unknown:00000 > girl: 123 tiny street:12345 > boy:321 here:33333 > gal:999 over there: 55555 > so forth > > Thus one key has many values. And you can then index on whatever key(s) > you wish - name,zip... > > With billions plus records, trying to put a unique key on each entry > seems to preclude the need for a dictionary, just use the entries. > (Format to SDF and index on substr(line,1,24)+substr(line,48,+5) etc..) > name + zip > OK - I know I missed the whole concept of a Python Dictionary. I haven't > read anything as yet that gives a clear picture of what it is and what > it is for. Please, classroom concepts usually consist of a handful of > objects. I have files here that takes up multiple DVDs each, AFTER a 15 > to 1 compression. 3 bytes per pixel. I need to work with them. Things > like changing geobase projections and cookie cutting based on real world > coordinates and modifying the lumens and so forth. Based on what I've > read, the Python Dictionary concept flat will not work for such as this. > Yes - the example is overkill. But in my world it is reality. I deal > with sizeable things. Not all are raster. Most all are binary! Things > that work on massive text files - like banking and mortgage - simply > don't work here. There are seldom 'lines'. There are always bytes. Lots > of bytes. Things that form a group are not necessarily stored sequentially. > > Back to What Is A Python Dictionary: Somebody please enlighten me. > Disctionaries are hash tables with a unique key and constant time lookup. What you want could be implemented as a complex data structures with as many dict as needed keys, but it seems you really want a relational table and a rdbms. This is exactly what they are for. A short example with the new python2.5 sqlite package : >>>[107]: import sqlite3 >>>[108]: from string import letters >>>[109]: db = sqlite3.connect(':memory:') >>>[110]: db.execute("create table 'table1' ('name' text(20), 'address' text(100), primary key ('name', 'address'))") ...[110]: >>>[111]: db.executemany("insert into 'table1' values (?, ?)", ((letters[i%len(letters)]*i, "%d street" % i) for i in range(1000))).rowcount ...[111]: 1000 >>>[112]: for i in db.execute("select * from 'table1' where address like '99 %'") : print i .....: (u'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV', u'99 street') >>>[113]: for i in db.execute("select * from 'table1' where name like '___'") : print i .....: (u'ddd', u'3 street') >>>[114]: db.execute("insert into 'table1' values (?, ?)", ('ddd', '4 street')).rowcount ...[114]: 1 >>>[115]: for i in db.execute("select * from 'table1' where name like '___'") : print i .....: (u'ddd', u'3 street') (u'ddd', u'4 street') >>>[116]: db.execute("insert into 'table1' values (?, ?)", ('ddd', '4 street')).rowcount --------------------------------------------------------------------------- IntegrityError Traceback (most recent call last) /home/maric/ in () IntegrityError: columns name, address are not unique > > Steve > norseman at hughes.net > -- > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud From kmathew at envivio.fr Sat Aug 16 17:20:52 2008 From: kmathew at envivio.fr (Kurien Mathew) Date: Sat, 16 Aug 2008 23:20:52 +0200 Subject: Good python equivalent to C goto Message-ID: <48a744b6$0$299$7a628cd7@news.club-internet.fr> Hello, Any suggestions on a good python equivalent for the following C code: while (loopCondition) { if (condition1) goto next; if (condition2) goto next; if (condition3) goto next; stmt1; stmt2; next: stmt3; stmt4; } Thanks Kurien From sjmachin at lexicon.net Tue Aug 5 05:00:31 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 5 Aug 2008 02:00:31 -0700 (PDT) Subject: UnicodeDecodeError, how to elegantly deal with this? References: Message-ID: <85c55895-eea2-487c-baa6-6b72f0a4afc6@l33g2000pri.googlegroups.com> On Aug 5, 4:23 am, "Jorgen Bodde" wrote: > Hi All, > > I am relatively new to python unicode pains and I would like to have > some advice. I have this snippet of code: > thefile = args["file"] > filemask = u"%file%" > therep = arg.replace(filemask, thefile) ##### error here > It crashes on this: > > 20:03:49: File > "D:\backup\important\src\airs\webserver\webdispatch.py", line 117, in > playFile therep = arg.replace(filemask, thefile) > > 20:03:49: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in > position 93: ordinal not in range(128) > > 20:03:49: Unhandled Error: : > 'ascii' codec can't decode byte 0xc2 in position 93: ordinal not in > range(128) > > It chokes on a ` character in a file name. I read this file from disk, > and I would like to play it. However in the replace action it cannot > translate this character. How can I transparently deal with this issue > because in my eyes it is simply replacing a string with a string, and > I do not want to be bothered with unicode problems. I am not sure in > which encoding it is in, but I am not experienced enough to see how I > can solve this If you don't want to be bothered with "unicode problems": (1) Don't create a "unicode problem" when one doesn't exist. (2) Don't bother other people with *your* "unicode problems". > > Can anybody guide me to an elegant solution? > Short path: In this case, less is more; remove the u prefix in the line filemask = u"%file%" Long Path: Ignorance is not bliss. Lose the attitude. Unicode is your friend, not an instrument of Satan. Read this: http://www.amk.ca/python/howto/unicode By the way, how one's filesystem encodes file names can be a good thing to know; in your case it appears to be UTF-8. HTH, John From elessar at nienna.org Tue Aug 26 16:47:45 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Tue, 26 Aug 2008 14:47:45 -0600 Subject: Programmatically exit the REPL In-Reply-To: <48B35768.80304@nienna.org> References: <288810.50426.qm@web7904.mail.in.yahoo.com> <48B35768.80304@nienna.org> Message-ID: <48B46BF1.20408@nienna.org> Matthew Fitzgibbons wrote: > I've got a pretty complex interactive command line program. Instead of > writing my own REPL, I'm using the Python interpreter (an infinitely > better solution). This program has two threads, a background thread and > the REPL thread. When you call quit() or sys.exit() in the REPL thread, > everything is perfectly happy. However, the background thread does some > long-running jobs, and I want it to have the ability to exit the program > when the job is complete. When I call quit() or sys.exit() from the > background thread, the REPL merrily continues on its way. > > This is a very frustrating problem, so I'm hoping someone can shed some > light on it. Am I missing something simple? Or is this just impossible? > I don't see anything about breaking out of interact() in the code module > docs. > > > Here's a minimal example: > > #!/usr/bin/env python -i > # You get the same behavior using code.interact() > > import sys > import time > import threading > > def end_the_program(): > # works if you call it from the REPL thread, > # but not the background thread > print "called end_the_program()" > sys.exit() > # quit() # using quit() rather than sys.exit() > # results in identical behavior > > keep_going = True > def runner(): > while keep_going: > time.sleep(0.1) > end_the_program() > threading.Thread(target=runner).start() > > # end example > > > Here's the console session (edited for clarity): > > Desktop$ ./exit_repl.py > >>> keep_going = False > called end_the_program() > # notice we didn't exit here > >>> end_the_program() > called end_the_program() > # but we did exit here > Desktop$ > > > -Matt > Here's a modified example that _almost_ works: #!/usr/bin/env python import code import time import threading keep_going = True def runner(): while keep_going: time.sleep(0.1) ic.push("quit()") # this will exit the InteractiveConsole loop! threading.Thread(target=runner).start() ic = code.InteractiveConsole(locals()) ic.interact("InteractiveConsole") # end example It uses code.InteractiveConsole instead of python -i. When you push "quit()" to the InteractiveConsole, the loop exits, but the raw_input call is still blocking. Argh! Console session: Desktop$ ./exit_repl.py && echo done InteractiveConsole >>> keep_going = False >>> done Desktop$ Does anyone know how to make raw_input think it has gotten input? -Matt From abesto0 at gmail.com Sat Aug 2 08:45:42 2008 From: abesto0 at gmail.com (=?ISO-8859-1?Q?Zolt=E1n_Nagy?=) Date: Sat, 02 Aug 2008 14:45:42 +0200 Subject: Multiline text in XML file In-Reply-To: References: Message-ID: King wrote: > Is there any other way to define multiline text in a XML file: > > multiline > multiline > multiline > multiline > ... > ]]> > Unless someone has to edit the XML manually (which is bad anyway): first line\nsecond line From gagsl-py2 at yahoo.com.ar Wed Aug 20 02:46:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 20 Aug 2008 03:46:14 -0300 Subject: Newbie question about sending and receiving data to the command prompt. References: <73045cca0808191248o47d315d5wb9780b92e17dc684@mail.gmail.com> Message-ID: En Tue, 19 Aug 2008 16:48:26 -0300, aditya shukla escribi?: > I am using windows vista and i am trying to send data to the command > prompt > ,this is what is done. > > import subprocess > proc =subprocess.Popen('cmd.exe',stdin=subprocess.PIPE) > proc.communicate('abc') > when i run this the command prompt just blinks and disappears , can > anyone > explain what's going on? I don't have a Vista machine to test right now, but I'd expect the above sequence to hang indefinitely. If you want to execute something, don't forget the final \n On XP this works fine: import subprocess proc =subprocess.Popen('cmd.exe',stdin=subprocess.PIPE,stdout=subprocess.PIPE) output = proc.communicate('dir\n')[0] print repr(output) -- Gabriel Genellina From exarkun at divmod.com Fri Aug 22 14:32:27 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 22 Aug 2008 14:32:27 -0400 Subject: How to read and write the same socket in different threads? In-Reply-To: <4e307e0f0808221125j3083500bu2def39b8bf609a9d@mail.gmail.com> Message-ID: <20080822183227.29191.1770886464.divmod.quotient.17478@ohm> On Sat, 23 Aug 2008 02:25:17 +0800, Leo Jay wrote: >On Sat, Aug 23, 2008 at 1:58 AM, Jean-Paul Calderone wrote: >> On Sat, 23 Aug 2008 01:47:23 +0800, Leo Jay wrote: >>> >>> I'd like to read and write the same socket in different threads. >>> one thread is only used to read from the socket, and the other is only >>> used to write to the socket. >>> But I always get a 10022 'Invalid argument' exception. Anyone knows why? >>> >>> I'm using windows xp. >>> >>> my source code is here: >>> http://pastebin.com/m23e633a2 >>> >> >> You're connecting and accepting with the same socket. That's not a very >> good thing to do. You're not even reading and writing on the same socket, >> since you're writing to the socket which you get from accept (if the code >> could get that far). >> > >not exactly. the socket connecting to port 1 is listening to port 2. >port 1 and port 2 are not the same. No - it's just what I said. create_socket creates one socket and passes it to read_socket and write_socket. read_socket calls connect on the socket it is passed. write_socket calls accept on the socket it is passed. So a single socket has connect and accept called on it. Now, main does call create_socket twice, so this does happen to two sockets, but it's broken in each case. > >> What are you trying to do? Why are you connecting and accepting? Why do >> you need two threads? >> > >I'm migrating a java module to python. In the java code, after >creating a socket, >the code gets an InputStream and an OutputStream from that socket, >sends and receives data in different threads. >So I just want to do the same thing. (at least do the same thing >currently, I don't want to change all related projects at the same >time.) Two threads per socket is a bad design. :( > >> Have you seen Twisted? http://twistedmatrix.com/ >> > >not yet, but it seems that it's quite a complicated module, isn't it? >is it possible to get the work done without adopting such a monster? :) > It's complicated so that applications using it don't have to be. It's easier to write network code with Twisted than with the socket and threading modules. Jean-Paul From tom1189 at removethis.verizon.net Sun Aug 24 12:47:34 2008 From: tom1189 at removethis.verizon.net (tom) Date: Sun, 24 Aug 2008 16:47:34 GMT Subject: Filling in Degrees in a Circle (Astronomy) In-Reply-To: References: Message-ID: >> http://matplotlib.sourceforge.net/ >> > I'm using Python 2.4. The install looks pretty complicated for Windows. > It doesn't seem like matplotlib is a module. > Maybe going with the enthought edition would be easiest for you as it is a very complete set of tools all in one package. It's at http://www.enthought.com/products/epd.php These are really nice tools for scientific (and other) data analysis, and are very competitive with most professional packages. There are other bundles as well, like Sage. I've always used enthought. On the other hand, I think making tools that use these in a bundled exe might be more difficult, and if possible, might not be consistent with their license agreements, and might make for large packages. I never really looked into this. Also, with matplotlib, you might just try installing it without anything else and see how it goes. Just download the exe and double-click, or the egg file and do whatever one does with those. I bet it will work... I think it will just default to using Tk for the GUI, which you already have installed with Python, and it won't use agg (an anti-aliasing library), so your plots won't be quite as pretty. But they'll still be nice, and it will likely work. From adrian_p_smith at yahoo.com Tue Aug 26 18:30:28 2008 From: adrian_p_smith at yahoo.com (Adrian Smith) Date: Tue, 26 Aug 2008 15:30:28 -0700 (PDT) Subject: smart quotes References: <4188c027-3c64-429b-a1e6-a1f3a79060e8@a3g2000prm.googlegroups.com> Message-ID: <672a2ddc-a2ce-499a-b506-8eeb5ba4d578@a2g2000prm.googlegroups.com> On Aug 26, 4:13?pm, Peter Otten <__pete... at web.de> wrote: > Adrian Smith wrote: > > Can anyone tell me how to get rid of smart quotes in html using > > Python? I've tried variations on > > stuff = string.replace(stuff, "\?", "\""), but to no avail, presumably > > because they're not standard ASCII. > > Convert the string to unicode. For that you have to know its encoding. I > assume UTF-8: > > >>> s = "a ?smart quote? example" > >>> u = s.decode("utf-8") > > Now you can replace the quotes (I looked up the codes in wikipedia): > > >>> u.replace(u"\u201c", "").replace(u"\u201d", "") > > u'a smart quote example' > > Alternatively, if you have many characters to remove translate() is more > efficient: > > >>> u.translate(dict.fromkeys([0x201c, 0x201d, 0x2018, 0x2019])) > > u'a smart quote example' > > If necessary convert the result back to the original encoding: > > >>> clean = u.translate(dict.fromkeys([0x201c, 0x201d, 0x2018, 0x2019])) > >>> clean.encode("utf-8") > > 'a smart quote example' > > Peter Brilliant, thanks! From larry.bates at vitalEsafe.com Thu Aug 21 19:29:34 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Thu, 21 Aug 2008 18:29:34 -0500 Subject: 'While' question In-Reply-To: References: Message-ID: Ben Keshet wrote: > Thanks for the reference. I tried it with a general example and got it > to work - I used an index that counts up to a threshold that is set to > break. It does not work though with my real code. I suspect this is > because I cannot really read any lines from an empty file, so the code > gets stuck even before I get to j=j+1: > > line = f.readline()[:-1] > j=0 > while 'PRIMARY' not in line: > line = f.readline()[:-1] > j=j+1 if j==30: > break > Any suggestions? > > BK > > > Wojtek Walczak wrote: >> On Thu, 21 Aug 2008 18:01:25 -0400, Ben Keshet wrote: >> >>> somehow. I use 'while 'word' not in line' to recognize words in the >>> texts. Sometimes, the files are empty, so while doesn't find 'word' >>> and runs forever. I have two questions: >>> 1) how do I overcome this, and make the script skip the empty files? >>> (should I use another command?) >>> 2) how do I interrupt the code without closing Python? (I have >>> ActivePython) >>> >> >> Try the docs first. You need to read about 'continue' and >> 'break' statements: http://docs.python.org/tut/node6.html >> >> HTH. >> >> > You might consider turning this around into something like: for j, line in enumerate(f): if 'PRIMARY' in line: continue if j == 30: break IMHO this is MUCH easier to understand. -Larry From pavlovevidence at gmail.com Fri Aug 22 23:13:02 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 22 Aug 2008 20:13:02 -0700 (PDT) Subject: Filling in Degrees in a Circle (Astronomy) References: Message-ID: On Aug 22, 7:12?pm, "W. eWatson" wrote: > Is there some simple operational device in Python that would allow me to > create an array (vector) of 360 points from my data by interpolating between > azimuth points when necessary? All my data I rounded to the nearest integer. > Maybe there's an interpolation operator? There's nothing built in, but see the bisect module. It is a good way to determine which interval you are in, and you can interpolate the points yourself. Carl Banks From joefazee at gmail.com Fri Aug 8 14:47:36 2008 From: joefazee at gmail.com (A. Joseph) Date: Fri, 8 Aug 2008 11:47:36 -0700 Subject: I need a Python mentor Message-ID: *Please the first message i sent out contain error, i`m very very sorry.* Hello everybody, i`m new to this list. I was programming in PHP before, so just of recent I started learning python. I need someone who I can be giving me some assignment based on the chapter I read in the book, and tell person will sometime review my code and tell me if it well structured. Can you be my mentor? Abah Josep -------------- next part -------------- An HTML attachment was scrubbed... URL: From Shawn at Milochik.com Wed Aug 6 14:17:45 2008 From: Shawn at Milochik.com (Shawn Milochik) Date: Wed, 6 Aug 2008 14:17:45 -0400 Subject: Monitor and compare two log files in real time In-Reply-To: <6f11115b-6f19-4ca4-97e6-0a0781ed617c@b30g2000prf.googlegroups.com> References: <6f11115b-6f19-4ca4-97e6-0a0781ed617c@b30g2000prf.googlegroups.com> Message-ID: <2dc0c81b0808061117h2c24fc6emd112893f957b91fb@mail.gmail.com> Can you be more specific? That will also help you write your requirements, which will lead to your pseudo code and then your code. Do you want to search for a a pre-defined string (or set of strings), or just look for anything matching a pattern to appear in the first file? Related question: Can that string appear anywhere in the second file, or does it have to appear in a certain pattern (at the beginning of a line, followed by a colon or the word "error" or something? Do the log entries have timestamps, or will you be capturing the time your script found the string in file 1? What will you do if the script must be restarted and "forgets" what it found in the past eight minutes? If you're feeling ambitious, write some code. Figure out how to: 1. Read a file. 2. Locate the value(s) you are looking for and retain them somehow. Once you can do those two things, you can easily read the second file and seek the values you already found. A few lines to handle the eight-minute rule, and you're almost done. Post back when you have some code written. ShawnMilo From benjamin.kaplan at case.edu Tue Aug 5 19:38:00 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 5 Aug 2008 19:38:00 -0400 Subject: pyprocessing/multiprocessing for x64? In-Reply-To: <5cqdnSE547L0QgXVnZ2dnUVZ_sLinZ2d@comcast.com> References: <5cqdnSE547L0QgXVnZ2dnUVZ_sLinZ2d@comcast.com> Message-ID: On Tue, Aug 5, 2008 at 7:16 PM, pigmartian wrote: > I recently learned (from I response on this newsgroup to an earlier query) > of the processing module for working with subprocesses in a similar manner > to threading. For what I needed to do, it worked great --- until I tried to > run my code on an x64 box, for which that module isn't available*. So, I'm > just wondering if when processing is renamed to multiprocessing and included > in the standard lib for 2.6, will x64 be supported? > > > ~Scott > > *yes, yes, I know. download the source and compile it myself. > I'm not an expert on this, but I think that anything written for x86 (32 bit) machines can run on x64 machines. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 7 11:30:22 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 07 Aug 2008 17:30:22 +0200 Subject: python-mode is missing the class browser In-Reply-To: <6361fac8-3bfb-4d7e-b13b-84261ebeea10@b1g2000hsg.googlegroups.com> References: <6361fac8-3bfb-4d7e-b13b-84261ebeea10@b1g2000hsg.googlegroups.com> Message-ID: <489b1509$0$3481$426a74cc@news.free.fr> Michele Simionato a ?crit : > I have noticed that the python-mode for Emacs that comes with the > latest Ubuntu is missing the class browser. Moreover if works > differently from the python-mode I was used to (for instance CTRL-c-c > works as CTRL-c-! whereas CTRL-c-! is missing, etc). How can I go back > to the old python-mode > or at least how do I get back the class browser? I'm not really up2date wrt/ my ubuntu station here, but I remember having seen this somewhat different (emacs-provided IIRC) python-mode which I didn't like. I don't quite remember what I did, but I can at least tell you what I have actually have: - in /usr/share/emacs/site-lisp/python-mode/python-mode.el : the 'true' python-mode which header goes like this: """ ;;; python-mode.el --- Major mode for editing Python programs ;; Copyright (C) 1992,1993,1994 Tim Peters ;; Author: 2003-2006 http://sf.net/projects/python-mode ;; 1995-2002 Barry A. Warsaw ;; 1992-1994 Tim Peters ;; Maintainer: python-mode at python.org ;; Created: Feb 1992 ;; Keywords: python languages oop (defconst py-version "$Revision: 4.78 $" "`python-mode' version number.") """ - in /usr/share/emacs/22.0.91/site-lisp/python-mode/ : the corresponding byte-compiled python-mode.elc - in /etc/emacs/site-start.d/ : a 50python-mode.el file that reads: """ ;-*-emacs-lisp-*- (autoload 'python-mode "python-mode" "Python editing mode." t) (autoload 'py-shell "python-mode" "Interactive Python interpreter." t) (autoload 'doctest-mode "doctest-mode" "Python doctest editing mode." t) (setq load-path (append (list (concat "/usr/share/" (symbol-name debian-emacs-flavor) "/site-lisp/python-mode") (concat "/usr/share/" (symbol-name debian-emacs-flavor) "/site-lisp/pymacs") ) load-path)) (setq auto-mode-alist (append (list '("\\.py$" . python-mode) '("SConstruct$" . python-mode) '("SConscript$" . python-mode) ) auto-mode-alist)) (setq interpreter-mode-alist (append (list '("python" . python-mode) '("python2.1" . python-mode) '("python2.2" . python-mode) '("python2.3" . python-mode) '("python2.4" . python-mode) '("python2.5" . python-mode) ) interpreter-mode-alist)) """ emacs-version : GNU Emacs 22.0.91.1 (i486-pc-linux-gnu, GTK+ Version 2.10.6) of 2006-12-20 on rothera, modified by Debian ubuntu Feisty Fawn (7.04) FWIW and talking about class-browser, there's the IMHO very excellent emacs-code-browser too. HTH From Edwin.Madari at VerizonWireless.com Thu Aug 14 11:06:42 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Thu, 14 Aug 2008 11:06:42 -0400 Subject: Fixed-length text file to database script In-Reply-To: Message-ID: <20080814150654.32B5D1E4019@bag.python.org> here is a working code snippet to read from MySQL db. python tutorial has examples of reading from files. put them together to do your task. =================================================== import MySQLdb con = MySQLdb.connect(host='127.0.0.1', port=4321, user='joe', passwd='shmoe', db='tst') cursor = con.cursor() sql = 'select * from YOUR_TABLE' cursor.execute(sql) results = cursor.fetch() con.close() ===================================================== hope that helps. good luck Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com at python.org [mailto:python-list-bounces+edwin.madari=verizonwireless.com at python.org] On Behalf Of Diez B. Roggisch Sent: Thursday, August 14, 2008 7:11 AM To: python-list at python.org Subject: Re: Fixed-length text file to database script Stacey wrote: > Hi Guys, > > I'm new to Python (mostly) and I'm wanting to use it for a new project > I'm faced with. > > I have a machine (PLC) that is dumping its test results into a > fixed-length text file. I need to pull this data into a database > (MySQL most likely) so that I can access it with Crystal Reports to > create daily reports for my engineers. > > I've been reading the Python manual for about a week now and I'm > learning a lot. Unfortunately, I was given a deadline today that I > cannot meet without a little help. > > I need to know how to write a script that will DAILY pull this text > file into a MySQL database. > > Can anyone show me how to do this? Show us code & data, and we show you how to improve the code. Or would you be able to write the script with the above information? Diez -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From rschroev_nospam_ml at fastmail.fm Sun Aug 17 15:19:37 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 17 Aug 2008 21:19:37 +0200 Subject: how many nested for can we utilize? In-Reply-To: References: <27cbc0fa0808152200l4be2ca5gc24d8b01458b6e62@mail.gmail.com> Message-ID: Nick Dumas schreef: > A good quote I read (I can't remember who it was from, though) is "If > you need more than three levels of indentation, then something is > seriously wrong with your code." Possibly Guido himself? Linus Torvalds in the Linux kernel coding style document: "[...] The answer to that is that if you need more than 3 levels of indentation, you're screwed anyway, and should fix your program." (http://lxr.linux.no/linux/Documentation/CodingStyle) -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From clp at rebertia.com Sun Aug 31 21:50:24 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 31 Aug 2008 18:50:24 -0700 Subject: Some problems with classes In-Reply-To: References: Message-ID: <47c890dc0808311850i577a7e3drd09b43dc2481bc68@mail.gmail.com> On Sun, Aug 31, 2008 at 6:39 PM, ssecorp wrote: > Why/how is it possible to add variables like this? I don't understand > this mechanism: > http://docs.python.org/tut/node11.html#SECTION0011330000000000000000 Under the covers, Python objects are implemented using dictionaries, so adding an attribute just adds a new key-value pair to the object's internal dictionary (which, incidentally, you can access as someobj.__dict__). > > class Employee: > pass > > john = Employee() # Create an empty employee record > > # Fill the fields of the record > john.name = 'John Doe' > john.dept = 'computer lab' > john.salary = 1000 > > --------------------------------------------------------------------------- > > Also, I can't get multiple inheritance to work. > > Don't mind that the a vegan obviously don't inherit from an animal and > a vegetable. I didn't come up with anything better, it is just to > learn about inheritance. > > > class Animal(object): > def __init__(self, name, weight): > self.name = name > self.weight = weight > > def speak(self): > print "speak" > > class Vegetable(object): > def __init__(self, name, volume): > self.name = name > self.volume = volume > > def split(self): > print "tjoff" > > class Vegan(Animal, Vegetable): > #pass > def __init__(self, name, attacks): > self.name = name > self.attacks = attacks > >>>> > > Traceback (most recent call last): > File "C:/Python25/Progs/XXXX/Movie.py", line 42, in > class ActionComedy(Movie, ActionMovie): > TypeError: Error when calling the metaclass bases > Cannot create a consistent method resolution > order (MRO) for bases Movie, ActionMovie The class names in error message here don't match the classes you declared above. Give us the actual code you're using or at least a stub version. >>>> > > > also, when inheriting, can I inherit __init__() somehow? If I want the > same attributes but perhaps some additional methods for example. Use super() to call your superclasses' __init__() methods. See super()'s entry in http://docs.python.org/lib/built-in-funcs.html for more info. - Chris > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From victoryforever83 at gmail.com Wed Aug 6 00:43:38 2008 From: victoryforever83 at gmail.com (victory_forever_83) Date: Tue, 5 Aug 2008 21:43:38 -0700 (PDT) Subject: i Covert my car from gas fuel to water fuel Message-ID: <39f467c8-ba83-49b9-b4bf-f5ef55c03bcb@e39g2000hsf.googlegroups.com> HI Do you have a car ? Does gas and fuel price driving you crazy ? Do you want to SAVE 60% of your car fuel ? Do you want to help solve the Global Warming problem ? if yes so you Want to Covert you car from gas fuel to water fuel **not a necessary to have a technical knowledge** We will lead you to Convert Your Car/Truck to BURN WATER as well as Gasoline and BOOST YOUR GAS MILEAGE!!! SEE on YOUTUBE 1- http://www.youtube.com/v/GmhQ31Pu-78&hl=en&fs=1 2- http://www.youtube.com/v/wqlLuifrHQs&hl=en&fs=1 Our Offer 1-How to Save Tons of Fuel With Your Water-Hybrid (E-Book) 2-Modify Your Car to Save Gas USING WATER (E-Book) the two e-books now for only $97, one-time charge. Also give you the FREE updates at no extra charge. Click to See http://goofiy2k.water4gas.hop.clickbank.net/ Dont Forget That You Have ** 60 Day 100% Full Money Back ** From drkjam at gmail.com Fri Aug 22 12:18:31 2008 From: drkjam at gmail.com (David Moss) Date: Fri, 22 Aug 2008 09:18:31 -0700 (PDT) Subject: property() usage - is this as good as it gets? Message-ID: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> Hi, I want to manage and control access to several important attributes in a class and override the behaviour of some of them in various subclasses. Below is a stripped version of how I've implemented this in my current bit of work. It works well enough, but I can't help feeling there a cleaner more readable way of doing this (with less duplication, etc). Is this as good as it gets or can this be refined and improved especially if I was to add in a couple more attributes some fairly complex over-ride logic? #!/usr/bin/env python class A(object): def __init__(self): self._x = None self._y = None def _set_x(self, value): self._x = value def _get_x(self): return self._x x = property(_get_x, _set_x) def _set_y(self, value): self._y = value def _get_y(self): return self._y y = property(_get_y, _set_y) class B(A): def __init__(self): self._z = None super(B, self).__init__() def _set_x(self, x): # An example subclass 'set' override. if x == 10: raise Exception('%r is invalid!' % x) self._x = x x = property(A._get_x, _set_x) def _set_z(self, value): self._z = value def _get_z(self): return self._z z = property(_get_z, _set_z) del A._get_x, A._set_x, A._get_y, A._set_y del B._set_x, B._get_z, B._set_z From norseman at hughes.net Tue Aug 12 13:48:15 2008 From: norseman at hughes.net (norseman) Date: Tue, 12 Aug 2008 10:48:15 -0700 Subject: Broken examples In-Reply-To: <48A0E04B.1040006@probo.com> References: <48A0DAF6.4040207@hughes.net> <48A0E04B.1040006@probo.com> Message-ID: <48A1CCDF.50302@hughes.net> Tim Roberts wrote: > norseman wrote: >> Tim; >> Finally got a chance to test your snippet. Thank you for it! >> >> I took the liberty of flushing it out a bit. >> ================ >> #!/--- >> # >> import os >> import win32com.client >> >> excel = win32com.client.Dispatch( 'Excel.Application' ) >> excel.Visible=1 # shows the spreadsheet (can be handy) >> xlCSV = 6 >> # substitute for list generation >> list = ["c:\\temp\\test.xls", "c:\\temp\\test1.xls"] >> >> for nm in list: >> csv = os.path.splitext( nm )[0] + '.csv' >> print "Procesing file:", csv >> if os.path.exists(csv): # window$ won't auto overwrite >> os.unlink(csv) >> wb = excel.Workbooks.Open( nm ) >> wb.SaveAs( csv, xlCSV ) >> print wb.Close() # requires manual verification >> # eliminating unattended runs >> >> #wb.Exit() & wb.Quit() # generate ERROR(s) - no such thing(s) >> # leaving Excel open >> >> excel.Visible=0 # actually closes Excel if no sheet open >> # verified via task manager >> >> print "Check to see if this worked." >> >> # end of file >> ================= >> The above does in fact work. >> Using the above I have a few questions. >> Documentation on xlCSV came from where? >> " on .Workbooks.Open(file.xls) came from ??? >> " on .SaveAs( filename, xlCSV ) came from ??? >> " on .Close() came from ??? > > MSDN has rather extensive documentation on the Excel object model, > although it is somewhat spread out. Search for "Excel object model". > > I cheated on xlCSV. That's the name of the symbol, and I believe it > will even be available as win32com.client.constants.xlCSV after you > instantiate the application, but I just searched the web for "xlCSV" and > hard-coded the 6. > > >> Tell me about the lack of the .Exit() and/or .Quit(), please. > > Workbooks don't exit or quit. Workbooks can be closed, but exit is > something that applies to the application (excel, in your case). You > should also be able to say > excel = None > to get rid of the app. > > >> I ran out of time today. Is it possible to send something like an >> keystroke to a Window () box if it accepts same from >> actual keyboard? May not work anyway since .Close() hangs (in >> interactive) awaiting it's answer. > > The Workbook.Close method accepts parameters; you should be able to get > it to skip the dialog. I believe that wb.Close( False ) should do this. > ============== The wb.Close( False) works as predicted. The excel = None leaves Excel open. excel.Visible=0 does close it so I'm OK. excel.Quit() is probably the better choice. (learned via a comment above + Trial & Error) For the next person that might have need of this: >>>>>>>>>> tested/working final snippet #!/--- # import os import win32com.client excel = win32com.client.Dispatch( 'Excel.Application' ) excel.Visible=0 #=1 shows the spreadsheet (can be handy) xlCSV = 6 # substituted for list generation list = ["c:\\temp\\test.xls", "c:\\temp\\test1.xls"] # for nm in list: csv = os.path.splitext( nm )[0] + '.csv' print "Procesing file:", csv if os.path.exists(csv): # window$/Win-DOS won't auto overwrite os.unlink(csv) wb = excel.Workbooks.Open( nm ) wb.SaveAs( csv, xlCSV ) wb.Close( False ) # excel.Quit() # doing it right # print "Do a dir *.csv check to see if this worked." # end of file >>>>>>>>>>>>> Using the Python supplied CSV module now makes handling a variety of .xls files a real snap. "Variety" of real spread sheet types, yes. The butchered type that should have been done in Word - probably never. Thanks again! Steve norseman at hughes.net From bsder at allcaps.org Sat Aug 2 02:35:20 2008 From: bsder at allcaps.org (Andrew Lentvorski) Date: Fri, 01 Aug 2008 23:35:20 -0700 Subject: Interconvert a ctypes.Structure to/from a binary string? Message-ID: <48940028.8080201@allcaps.org> Basically, I'd like to use the ctypes module as a much more descriptive "struct" module. Is there a way to take a ctypes.Structure-based class and convert it to/from a binary string? Thanks, -a From bedouglas at earthlink.net Sun Aug 31 16:36:48 2008 From: bedouglas at earthlink.net (bruce) Date: Sun, 31 Aug 2008 13:36:48 -0700 Subject: parsing "&A" in a string.. In-Reply-To: Message-ID: <0d7e01c90ba9$4b8e10f0$0301a8c0@tmesa.com> Hi Fredrick Thanks for the reply. But since I don't have control of the initial text, is there something with python that will strip/replace this... or are you saying I should do a search/replace on the "&" char with the "amp&;" prior to parsing?? -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Fredrik Lundh Sent: Sunday, August 31, 2008 1:10 PM To: python-list at python.org Subject: Re: parsing "&A" in a string.. bruce wrote: > a pretty simple question, i'm guessing. > > i have a text/html string that looks like: > ....(A&E) > > the issue i have is that when i parse it using xpath/node/toString, > i get the following > > ...(A&E;). that's because your parser is interpreting the &E part as an entity reference, and the serializer is then adding the missing semicolon. bare ampersands must be written as "&" in the file. -- http://mail.python.org/mailman/listinfo/python-list From tjreedy at udel.edu Wed Aug 27 19:56:54 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 27 Aug 2008 19:56:54 -0400 Subject: Multiple values for one key In-Reply-To: <26c69b160808271326w2f53b6b8s6e4aa7f91071ac71@mail.gmail.com> References: <26c69b160808271326w2f53b6b8s6e4aa7f91071ac71@mail.gmail.com> Message-ID: Ron Brennan wrote: > Hello, > > > How would I create a dictionary that contains multiple values for one > key. Make the value a collection object (set or list if you plan to add and delete). > I'd also like the key to be able to have duplicate entries. Dict keys must be hashable and unique. tjr From bhood2 at comcast.net Tue Aug 26 00:11:10 2008 From: bhood2 at comcast.net (bhood2 at comcast.net) Date: Mon, 25 Aug 2008 22:11:10 -0600 Subject: Need help with extension modules built in debug mode Message-ID: I've come to the conclusion that posting about Embedded Python on the Python forums is a complete waste of time. I hope I can get some useful insights here. I'm looking for some help with extension modules built using Visual Studio. I'm using the simple extension module example "hello" (taken from the "Programming Python" book). I'm building it successfully in both release and debug mode using a Visual Studio project. I can successfully import the release build of the module into the release build of Python. For example: [E:\]python Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import hello >>> hello.message("Bob") 'Hello, Bob' >>> quit() I cannot, however, load the debug build of the exact same code (stored in the exact same location) into the debug build of Python: [E:\]python_d Python 2.5.1 (r251:54863, Jun 5 2007, 10:17:28) [MSC v.1400 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import hello Traceback (most recent call last): File "", line 1, in ImportError: No module named hello [26848 refs] >>> quit() [7826 refs] Does anybody know what tricks or coding magic might be required to get debug extension modules to load into debug Python? From sierra_mtnview at sbcglobal.net Sat Aug 23 09:27:38 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 23 Aug 2008 06:27:38 -0700 Subject: Python open of c:\ path Problem Message-ID: <48B0104A.4010303@sbcglobal.net> An HTML attachment was scrubbed... URL: From gminick at nie.ma.takiego.adresu.w.sieci.pl Thu Aug 14 06:10:56 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Thu, 14 Aug 2008 10:10:56 +0000 (UTC) Subject: Suggestion for improved ImportError message References: Message-ID: On Thu, 14 Aug 2008 01:35:44 +0000 (UTC), Kent Tenney wrote: >> > Then go for it You can prepare a patch and ask on python-dev >> > if the developers are interested. > > hehe, I'll get a C level patch accepted right after I > out-swim Mike Phelps. It's really not that hard. The only hard thing (harder than writing the code) might be to win the acceptance of the core developers that this change is really needed ;-) >> > I was never hacking the import things on C level before, >> > but a hint: you have to modify import_from function from >> > Python/ceval.c > > Am I correct in thinking that PyPy would mean low level > stuff like this will be Python instead of C? > That would be nice. I don't know PyPy, but I guess you're right here. -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From circularfunc at yahoo.se Mon Aug 25 21:58:56 2008 From: circularfunc at yahoo.se (cnb) Date: Mon, 25 Aug 2008 18:58:56 -0700 (PDT) Subject: Return a string result with out breaking loop References: <116e4423-44c5-4f13-ab2d-d8040b550a8e@2g2000hsn.googlegroups.com> Message-ID: ok post exactly what you do when this hapens: ault: :cannot marshal objects"> it complains you are trying to marshal a generator object rather than the file you are yielding. also, something I am not sure about: >>> def f(x): try: open("C:/ruby/progs/blandat/infixtoprefix.rb") or open(str(x)) except:print "hello" >>> f(12) >>> def f(x): try: (open(str(x)) or open("C:/ruby/progs/blandat/infixtoprefix.rb")) except:print "hello" >>> f(12) hello >>> the or doesnt seem to work as expected. but thats not the problem youa re experienceing From duncan.booth at invalid.invalid Sun Aug 10 07:31:58 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Aug 2008 11:31:58 GMT Subject: Missing exceptions in PEP 3107 References: <11655cb0-c30b-4cd3-9c13-f806681f28cc@w1g2000prk.googlegroups.com> Message-ID: Christoph Zwerschke wrote: > That would be possible. But I still think it makes sense to separate > them, like so: > > def foo(a: "a info", b: "b info") -> "ret info" raise "exc info": > return "hello world" > > And then the annotation dictionary would contain another key "raise" > containing the exc info. This cannot conflict with the name of any other > parameter either. > If you really want this then you can use a decorator to insert a 'raise' key into the annotations: @raises("exc info") def foo(a: "a info", b: "b info") -> "ret info": return "hello world" > I don't know how determined the "->" syntax is already. Consider the syntax set in concrete. The meaning of the annotations on the other hand is completely up for grabs. From gminick at nie.ma.takiego.adresu.w.sieci.pl Wed Aug 6 07:55:13 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Wed, 6 Aug 2008 11:55:13 +0000 (UTC) Subject: Help with mechanize References: Message-ID: Dnia Wed, 06 Aug 2008 07:16:37 -0400, Neal Becker napisa?(a): > I'm trying to use mechanize to read for a M$ mail server. I can get past the login page OK using: ... > Now it seems if I read b.links() I can see links to my mail. My question is, how do I now actually get the contents of this page? Have you tried follow_link() method? In your case it should be something like: response = b.follow_link(b.links()[0]) # I suppose links() # returns a list or tuple print response.info() # headers print response.read() # body IIRC, it's described in the documentation. -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From ggpolo at gmail.com Mon Aug 25 23:10:15 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 26 Aug 2008 00:10:15 -0300 Subject: SocketServer max connections In-Reply-To: <48B28784.2050209@seehart.com> References: <48B28784.2050209@seehart.com> Message-ID: On Mon, Aug 25, 2008 at 7:20 AM, Ken Seehart wrote: > I'm using SocketServer to implement a local server that serves comet > long-polling connections. > > How do I increase the maximum number of open connections? Currently it is > limited to about 8 I think. More than that and it seems to block on opening > more connections until one of the other connections releases. You need to change request_queue_size in your subclass, supposing you are directly or indirectly using a tcp server. The default is 5, rather low. The first attempt you can do is using the socket.SOMAXCONN value, but depending on your system you can set a number much higher than that one given by socket.SOMAXCONN. > > - Ken > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From tkpmep at hotmail.com Tue Aug 26 17:49:35 2008 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: Tue, 26 Aug 2008 14:49:35 -0700 (PDT) Subject: Identifying the start of good data in a list Message-ID: <94524253-b946-4ffa-ae2e-ae6a555d4e7c@a1g2000hsb.googlegroups.com> I have a list that starts with zeros, has sporadic data, and then has good data. I define the point at which the data turns good to be the first index with a non-zero entry that is followed by at least 4 consecutive non-zero data items (i.e. a week's worth of non-zero data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], I would define the point at which data turns good to be 4 (1 followed by 2, 3, 4, 5). I have a simple algorithm to identify this changepoint, but it looks crude: is there a cleaner, more elegant way to do this? flag = True i=-1 j=0 while flag and i < len(retHist)-1: i += 1 if retHist[i] == 0: j = 0 else: j += 1 if j == 5: flag = False del retHist[:i-4] Thanks in advance for your help Thomas Philips From gagsl-py2 at yahoo.com.ar Fri Aug 29 20:04:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 29 Aug 2008 21:04:47 -0300 Subject: no string.downer() ? References: <53a51084-8ec9-4069-99b6-7d494002a308@56g2000hsm.googlegroups.com> <9364d88d-6792-4398-8703-cad69b5be3f5@b38g2000prf.googlegroups.com> Message-ID: En Thu, 28 Aug 2008 02:52:42 -0300, Fredrik Lundh escribi?: > Asun Friere wrote: > >> Never ascribe to humour that which can be adequately explained by >> increadible stupidity! On the other hand given up/down vs. high/low, >> upper/downer might appear logical to someone who doesn't know that >> "downcase" is called 'lowercase.' > > prior exposure to Ruby might explain this, right? (iirc, they use > "upcase" and "downcase"). Yes. And Common Lisp has used the same very names for a longer time than Python itself existed, so I don't agree with many comments on this thread. -- Gabriel Genellina From jonathansamuel at yahoo.com Sun Aug 3 19:20:37 2008 From: jonathansamuel at yahoo.com (Jonathan Mark) Date: Sun, 3 Aug 2008 16:20:37 -0700 (PDT) Subject: How do I find out from inside pdb which namespace contains an object? References: Message-ID: Never mind. I had to run "import collective.dancing" first. From ryntech at gmail.com Wed Aug 27 09:52:59 2008 From: ryntech at gmail.com (rynt) Date: Wed, 27 Aug 2008 06:52:59 -0700 (PDT) Subject: GUI programming with python References: <1ff5e508-0fd8-44cf-9c82-3c85ded0ed2d@x16g2000prn.googlegroups.com> <1bs69ogq6nspt.136i7kvcux142$.dlg@40tude.net> Message-ID: <880f46a3-8c26-4ad1-891d-a593ff3de886@w1g2000prk.googlegroups.com> On Aug 26, 10:49?am, John Fabiani wrote: > Alan Franzoni wrote: > > zamil was kind enough to say: > > > [cut] > > > See the following link on the Python website. http://wiki.python.org/moin/GuiProgramming Google this list for GUI RC From paul at boddie.org.uk Fri Aug 15 09:42:26 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 15 Aug 2008 06:42:26 -0700 (PDT) Subject: getattr nested attributes References: Message-ID: <7229d7ab-c3df-4a6a-b050-65ca0b43ad9a@56g2000hsm.googlegroups.com> On 15 Aug, 10:35, Gregor Horvath wrote: > > : type object 'B' has no attribute > 'a.test' You have to realise that attributes can have names beyond those supported by the usual attribute access syntax. For example: class C: pass setattr(C, "x.y", 123) getattr(C, "x.y") # gives 123 setattr(C, "class $$$", 456) getattr(C, "class $$$") # gives 456 Note that there's no way of using the object.name syntax to access these attributes, although some proposals have been made to allow it in some fashion. What you should conclude from this is that the name argument to setattr and getattr is just a name, not an expression, even if you can construct names which look like expressions or other syntactically meaningful fragments of code. > Documentation says B.a.test and getattr(B, "a.test") should be equivalent. > > http://docs.python.org/lib/built-in-funcs.html No, the documentation says that the name must be "the name of one of the object's attributes", not an expression fragment that if combined with the name of the object and evaluated would yield an attribute from some object or other reachable via the original object. Paul From phillip.oldham at gmail.com Thu Aug 14 08:22:35 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Thu, 14 Aug 2008 05:22:35 -0700 (PDT) Subject: Trying ZODB, background in Relational: mimic auto_increment? Message-ID: Hi all. I'm playing with standalone ZODB at the moment trying to get a better understanding of its use in applications. I come from a PHP/MySQL background, and I'm taking my first steps with Python at the same time. One of the things I'm not understanding about ZODB is assigning incremental IDs to objects. For instance, if I were to be writing a support-ticket system I'd want to give each ticket a unique number, but one that's "human-useable" (otherwise you could just use a UUID - try giving one of those over the phone!). Also, how would one add a new item to the db in this way? For instance: class Ticket(Persistence): def __init__(self): self.id = '' # How do I add a new incremental ID here? # and later on in the app tkt = Ticket() dbroot[?????] = tkt How would one assign a unique ID to the root at that point? From teh.saber at gmail.com Sat Aug 9 22:20:02 2008 From: teh.saber at gmail.com (teh_sAbEr) Date: Sat, 9 Aug 2008 19:20:02 -0700 (PDT) Subject: The wrong approach to things Message-ID: <0c435465-b769-45b9-8c6e-57d57abc5c31@j33g2000pri.googlegroups.com> Ok, so this isn't necessarily a programming issue, but anyways. I've managed to write that random wallpaper changer i've been wanting to make, but i've run into a little problem. According to the MS Knowledge Base, SystemParametersInfo() can't take a .jpg file as an argument when changing the wallpaper (it doesn't work, i've tried it), only .bmps so i'm stuck converting one of my many wallpapers from .jpg to .bmp, passing that to SystemParametersInfo(), and deleting the previous .bmp so that i don't have any duplicates. The problem with this is that other members of my family use this computer too, and they sometimes set the desktop wallpaper to some other, usually funny picture they've got stored on the HD, and when I run this little script it'll delete whatever the current wallpaper is, regardless of whether its one of mine or not. Any suggestions on how to work around this problem? #random wallpaper changer! import win32gui #use this to change the wallpaper. import os import os.path import random import Image SPI_SETDESKWALLPAPER = 20 #It took me WAY too long to find them. SPI_GETDESKWALLPAPER = 115 #I should keep these handy. def RandomlySelectWallpaper(filePaths): CurrentWallpaper = win32gui.SystemParametersInfo(SPI_GETDESKWALLPAPER) while True: index = random.randint(0,len(filePaths)-1) RandomlySelectedWallpaper = filePaths[index] if RandomlySelectedWallpaper <> CurrentWallpaper: break print RandomlySelectedWallpaper return RandomlySelectedWallpaper #it should be a string... def ChangeDesktopWallpaper(RandomlySelectedWallpaper): #so the RIGHT way to do this would be to use #win32gui.SystemParametersInfo() to change the wallpaper. #1) we convert the image to .bmp. #Delete the old wallpaper, actual delete occurs after new wallpaper has been set. pathToCurrentWall = win32gui.SystemParametersInfo(SPI_GETDESKWALLPAPER) root,extension = os.path.splitext(RandomlySelectedWallpaper) newFileName = root + '.bmp' print "Wallpaper to delete: ", pathToCurrentWall try: #every so often something goes wrong at this stage in the script #and I can't figure out what. Something raises an IOError. Image.open(RandomlySelectedWallpaper).save(newFileName) print "File saved!" except IOError: print "Error while converting, please check filepath and permissions." print "Program will restart in an attempt to generate a correct wallpaper." Main() win32gui.SystemParametersInfo(SPI_SETDESKWALLPAPER,newFileName, 1+2) print "Removing: ", pathToCurrentWall os.remove(pathToCurrentWall) def Main(): #woot. listOfWallpaperPaths = GenerateListOfWallpapers() RandomlySelectedWall = RandomlySelectWallpaper(listOfWallpaperPaths) ChangeDesktopWallpaper(RandomlySelectedWall) Main() From claird at lairds.us Sun Aug 31 12:24:06 2008 From: claird at lairds.us (Cameron Laird) Date: Sun, 31 Aug 2008 16:24:06 +0000 Subject: python subprocess know how References: <997f0a34-6f38-4276-9107-2d5b725d1247@q26g2000prq.googlegroups.com> Message-ID: <66tqo5-cht.ln1@lairds.us> In article <997f0a34-6f38-4276-9107-2d5b725d1247 at q26g2000prq.googlegroups.com>, King wrote: >Hi, > >I am using subprocess module to execute a command and print results >back. > >startupinfo = subprocess.STARTUPINFO() >startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW >my_process = subprocess.Popen(cmnd, startupinfo=startupinfo) >print repr(my_process.communicate()[0]) > >This code executes on pressing a button (wxPython). The problem is >until command is not done >and it's results are not printed, program halts and button keep the >state of pushed. > >Is there any way to avoid this? . . . From bignose+hates-spam at benfinney.id.au Thu Aug 7 19:50:04 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 08 Aug 2008 09:50:04 +1000 Subject: how to find out if an object is a class? References: Message-ID: <871w105qs3.fsf@benfinney.id.au> szczepiq writes: > Pardon me for most likely a dummy question but how do I find out if > an object is a class? You can test using 'isinstance'. However, using that is a bad code smell, which requires investigation as to the reason. Presumably you want to know whether it's a class in order to use it for instantiating it. It is usually more Pythonic to use the object as intended, and allow the object itself to tell you (via exceptions) when it's not behaving as you expect. >>> def foo(spam_class): ... spam_arg = 10 ... spam_instance = spam_class(spam_arg) ... # ? do stuff with spam_instance ? ... >>> foo(int) >>> foo("not a class") Traceback (most recent call last): File "", line 1, in File "", line 3, in foo TypeError: 'str' object is not callable > I need something like that: > > def foo(self, obj): > if (obj is a class): > some stuff Why do you think you need to test whether an object is a class? What problem are you trying to solve? -- \ ?I got fired from my job the other day. They said my | `\ personality was weird. ? That's okay, I have four more.? | _o__) ?Bug-Eyed Earl, _Red Meat_ | Ben Finney From maric at aristote.info Sat Aug 16 10:02:26 2008 From: maric at aristote.info (Maric Michaud) Date: Sat, 16 Aug 2008 16:02:26 +0200 Subject: Dynamically defined functions via exec in imported module In-Reply-To: <979a8a16-0930-4838-9625-0a03784e590b@w7g2000hsa.googlegroups.com> References: <036d8731-5984-4c23-a15d-efe7e01b5d07@x35g2000hsb.googlegroups.com> <979a8a16-0930-4838-9625-0a03784e590b@w7g2000hsa.googlegroups.com> Message-ID: <200808161602.27642.maric@aristote.info> Le Saturday 16 August 2008 06:50:02 Michele Simionato, vous avez ?crit?: > On Aug 16, 4:48?am, Nadeem wrote: > > I understand the 99% rule... the example I gave was to simplify the > > issue. The full thing I'm working on is a library for an introductory > > CS class I'm teaching. I'm trying, essentially, to build a library of > > macros for students to use allowing them to define records (like > > structs in C) with selector functions. > > The namedtuple recipe by Raymond Hetting does > exactly that and, guess what, it uses exec! It uses exec, but could not, and IMO, should not, all of the cooking could be done in the closure. I join version of it without exec. Of course the only drawback is that you need to do the job of argument checking in __new__ and can't rely on a dynamically compiled arglist. But it is a common idiom I think. > Also the doctest module in the standard library > uses exec at good effect. So, I would say it is > not a 99% rule, let's say it is a 98% rule ;) Yes, but in doctest, exec is used for what it is intended to be use, execute arbitrary code provided by the user, this is legal and perfect use of exec because here the user is a trusted one (the programer himself). I'd say that everywhere exec/eval are used in a application/function/lib that doesn't mean to interpret arbitrary and user provided python code, it is a bad usage. -- _____________ Maric Michaud -------------- next part -------------- A non-text attachment was scrubbed... Name: namedtuple.py Type: application/x-python Size: 5644 bytes Desc: not available URL: From Slaunger at gmail.com Thu Aug 7 02:29:01 2008 From: Slaunger at gmail.com (Slaunger) Date: Wed, 6 Aug 2008 23:29:01 -0700 (PDT) Subject: Best practise implementation for equal by value objects References: <135eb396-6daa-4ff4-a722-253ba149889c@27g2000hsf.googlegroups.com> <00aa5a64$0$20317$c3e8da3@news.astraweb.com> Message-ID: <473d7c86-22f4-4992-989b-e2b9402fd10d@l64g2000hse.googlegroups.com> On 7 Aug., 04:34, Steven D'Aprano wrote: > On Wed, 06 Aug 2008 05:50:35 -0700, Slaunger wrote: > > Hi, > > > I am new here and relatively new to Python, so be gentle: > > > Is there a recommended generic implementation of __repr__ for objects > > equal by value to assure that eval(repr(x)) == x independet of which > > module the call is made from? > > In general, no. > > ... > OK. > > My question is: Is there a robust generic type of implementation of > > __repr__ which I can use instead? > > > This is something I plan to reuse for many different Value classes, so I > > would like to get it robust. > > I doubt you could get it that robust, nor is it intended to be. > > eval(repr(obj)) giving obj is meant as a guideline, not an invariant -- > there are many things that can break it. For example, here's a module > with a simple class: OK, I had not fully understood the implications of 'not' implementing __repr__ such that eval(repr(x)) == x, so I just tried to make it work to make sure life would be easy for me and my object as I went further into the Python jungle As mentioned above, i also find the eval(repr(x))==x condition convenient from a unit test point of view. > > # Parrot module > class Parrot(object): > ? ? def __repr__(self): > ? ? ? ? return "parrot.Parrot()" > ? ? def __eq__(self, other): > ? ? ? ? # all parrots are equal > ? ? ? ? return isinstance(other, Parrot) > > Now let's use it: > > >>> import parrot > >>> p = parrot.Parrot() > >>> s = repr(p) > >>> assert eval(s) == p > >>> del parrot > >>> assert eval(s) == p > > Traceback (most recent call last): > ? File "", line 1, in > ? File "", line 1, in > NameError: name 'parrot' is not defined > OK, I see, but this isn't exactly eval(repr(x))==x but s = repr(x) eval(s) == x so, of course, is s is deleted in between it won't work. In my implementation I only expect this should work as a one-liner. > If you look at classes in the standard library, they often have reprs > like this: > > >>> repr(timeit.Timer()) > > '' > Yes, I noticed that. But the example here is also an object, which is equal by reference, not value. And for these it does not make so much sense to evaluate the representation. > Certainly you can't expect to successfully eval that! > > I believe the recommendation for eval(repr(obj)) to give obj again is > meant as a convenience for the interactive interpreter, and even there > only for simple types like int or list. If you can do it, great, but if > it doesn't work, so be it. You're not supposed to rely on it, and it's > not meant as a general way to serialize classes. > > -- > Steven OK, I will put less emphasis on it in the future. Thank you for taking your time to answer. Slaunger From vijayakumar.subburaj at gmail.com Thu Aug 7 08:48:27 2008 From: vijayakumar.subburaj at gmail.com (v4vijayakumar) Date: Thu, 7 Aug 2008 05:48:27 -0700 (PDT) Subject: More Datastore Examples Please References: Message-ID: <9eed4339-587a-4405-8d38-7b2a80cefc29@j7g2000prm.googlegroups.com> On Aug 7, 11:38 am, Tim Roberts wrote: > v4vijayakumar wrote: > > >Google appengine datastore is not very clear, and I couldn't get much > >from API documents. It would be very helpful if there are some more > >detailed documents with examples. > > I would gently suggest that you are not trying hard enough. I had never > encountered the Google appengine datastore, but the first hit in Googling > that phrase took me to the Google documentation, which seems to be quite > thorough. Google documentation is not clear for me. Documentation provided there is not helping much with modeling entities. This requires some practice, so I thought that If there were some ways to access this APIs through Idle. This is not as simple as adding some directories to PYTHONPATH. There are some more things to be done before working directly on datastore through Idle. This is not documented, but luckily got some help from the group, google-appengine. > If you have never worked with a database before, then you might want to go > find a good book on databases first. No. That won't help, because this datastore is not a relational database, but Google's proprietary format called BigTable. > What are you trying to DO with the datastore? I am just experimenting with google-appengine, and building an application on it. From simon at mullis.co.uk Wed Aug 13 09:15:21 2008 From: simon at mullis.co.uk (Simon Mullis) Date: Wed, 13 Aug 2008 15:15:21 +0200 Subject: Regarding Telnet library in python In-Reply-To: <7412fd2f-b6b0-4b91-b05e-53b434d6fd2e@w24g2000prd.googlegroups.com> References: <7412fd2f-b6b0-4b91-b05e-53b434d6fd2e@w24g2000prd.googlegroups.com> Message-ID: <23d7e1bb0808130615s571a091fsa84124ad84e67a64@mail.gmail.com> Hi there, This works (but bear in mind I'm about only 30 minutes into my Python adventure...): ------ def connect(host): tn = telnetlib.Telnet(host) return tn def login(session,user,password): session.write("\n") session.read_until("Login: ") session.write(user + "\n") session.read_until("Password: ") session.write(password + "\n") session.read_until("#") def apply_command(session,command): session.write(command + "\n") response = str(session.read_until("#")) return response def cleanup(session): session.write("exit\n") session.close() tn = connect(1.1.1.1) login(tn,user,password) directory = apply_command(tn,"ls -l") kernel_release = apply_command(tn,"uname -r\n") cleanup(tn) ------ You'd probably need to apply a regex to the output of the apply_command method for it to make sense, and I am confident there is a much, much better way to do this! Cheers SM -------------- next part -------------- An HTML attachment was scrubbed... URL: From saswat at gmail.com Fri Aug 29 04:16:26 2008 From: saswat at gmail.com (saswat at gmail.com) Date: Fri, 29 Aug 2008 01:16:26 -0700 (PDT) Subject: Checking if the file is a symlink fails References: <803e077e-c0c9-43d3-b40a-99511c2e55f3@25g2000prz.googlegroups.com> Message-ID: On Aug 28, 10:20?pm, Fredrik Lundh wrote: > sas... at gmail.com wrote: > > Do you mean the following is deprecated ? > >http://docs.python.org/lib/module-stat.html > > >>From the documentation - > > > S_ISLNK( mode) > > ? ? Return non-zero if the mode is from a symbolic link. > > As that page states, that's a function used to interpret a mode flag > returned by os.stat, os.fstat, or os.lstat. ?It obviously won't give you > the result you're looking for if you use a stat function that *follows* > symbolic links. > > Thank you Fredrick and Miles, stat() is on the actual file and not on the symlink. That explains. -Saswat From modelnine at modelnine.org Sat Aug 2 12:14:33 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Sat, 02 Aug 2008 17:14:33 +0100 Subject: Help me In-Reply-To: <20080802200242.cn33gib7288s4sko@mail.svuonline.org> References: <20080802200242.cn33gib7288s4sko@mail.svuonline.org> Message-ID: Am 02.08.2008, 18:02 Uhr, schrieb : > I'll help you by giving some good advice: homework is meant to be homework, so you should get started reading and processing the assignment. If you have any specific questions besides text comprehension, come back to ask. --- Heiko. From george.sakkis at gmail.com Mon Aug 18 11:57:57 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 18 Aug 2008 08:57:57 -0700 (PDT) Subject: Weird expression result Message-ID: <83803185-725e-45bb-b2fe-1add2868bd34@c58g2000hsc.googlegroups.com> I'm probably missing something obvious but I can't put my finger on it: >>> (3 in [3]) == True True >>> 3 in ([3] == True) Traceback (most recent call last): File "", line 1, in TypeError: argument of type 'bool' is not iterable >>> 3 in [3] == True False How/why does the last one evaluate to False ? George From scottpig1 at comcast.net Wed Aug 6 18:34:07 2008 From: scottpig1 at comcast.net (pigmartian) Date: Wed, 06 Aug 2008 18:34:07 -0400 Subject: pyprocessing/multiprocessing for x64? In-Reply-To: <5cqdnSE547L0QgXVnZ2dnUVZ_sLinZ2d@comcast.com> References: <5cqdnSE547L0QgXVnZ2dnUVZ_sLinZ2d@comcast.com> Message-ID: Interesting, I see Christian's responses to Benjamin, but not Benjamin's posts themselves. Anyways, the question remains: will multiprocessing be supported for the x64 platform when it's released in 2.6? pigmartian wrote: > I recently learned (from I response on this newsgroup to an earlier > query) of the processing module for working with subprocesses in a > similar manner to threading. For what I needed to do, it worked great > --- until I tried to run my code on an x64 box, for which that module > isn't available*. So, I'm just wondering if when processing is renamed > to multiprocessing and included in the standard lib for 2.6, will x64 be > supported? > > > ~Scott > > *yes, yes, I know. download the source and compile it myself. From kmathew at envivio.fr Sat Aug 2 07:53:03 2008 From: kmathew at envivio.fr (Kurien Mathew) Date: Sat, 02 Aug 2008 13:53:03 +0200 Subject: Concise way to format list/array to custom(hex) string Message-ID: <48944aa1$0$289$7a628cd7@news.club-internet.fr> Hello, What will be a concise & efficient way to convert a list/array.array of n elements into a hex string? For e.g. given the bytes [116, 111, 110, 103, 107, 97] I would like the formatted string 0x74 0x6f 0x6e 0x67 0x6b 0x61 Is there an approach better than below: hex = '' for b in bytes: hex += ('0x%x '%b) Thanks Kurien Test program: import array import sys bytes = array.array('B') bytes.fromstring("tongka") print bytes hex = '' for b in bytes: hex += ('0x%x '%b) print hex From nandhini.ram8 at gmail.com Fri Aug 1 02:58:41 2008 From: nandhini.ram8 at gmail.com (nandhini.ram8 at gmail.com) Date: Thu, 31 Jul 2008 23:58:41 -0700 (PDT) Subject: http://makmoneyy.googlepages.com Message-ID: http://makmoneyy.googlepages.com ........................\.\.~.~././........................... ...........................(@.@)............................. ....======oOOo=(_)=oOOo=========. ...|........Se voc? ? como eu, que................| ...|.........fica super feliz ao perceber..........| ...|......e ver o quanto sua m?e trata.........| ...|.....bem o seu namorado e o quanto.....| ...|........ela gosta dele, participe, aqui.......| ...|.....? o seu lugar, sejam bem vindos.....| ...=================Oooo=======| http://makmoneyy.googlepages.com/.................ooo0...............(........)................ .................(.......)..............)...../................... ..................\.....(..............(__./..................... ...................\.__)....................................... http://makmoneyy.googlepages.com/ From norseman at hughes.net Tue Aug 12 19:25:26 2008 From: norseman at hughes.net (norseman) Date: Tue, 12 Aug 2008 16:25:26 -0700 Subject: Broken examples In-Reply-To: <362180a2-c3da-4a71-b41d-6b02e2d800ee@v26g2000prm.googlegroups.com> References: <362180a2-c3da-4a71-b41d-6b02e2d800ee@v26g2000prm.googlegroups.com> Message-ID: <48A21BE6.6070908@hughes.net> John Machin wrote: > On Aug 12, 10:36 am, norseman wrote: >> Tim; >> Finally got a chance to test your snippet. Thank you for it! >> >> I took the liberty of flushing it out a bit. >> ================ ...(snip) >> > > Why do you want to save as CSV? Would you be happier with a simple > reliable method to extract information from Excel files without all > that bother? If so, consider the xlrd package (http://www.lexicon.net/ > sjmachin/xlrd.htm). If you really do need CSV files, still consider > xlrd in combination with the Python csv module -- remove all that user > involvement, allow the user to use Excel for other purposes while the > job is running (instead of filing), programatically handle exception > conditions (like more than one worksheet in the workbook), run it on > Linus or a Mac if you want to, ... > > -- > http://mail.python.org/mailman/listinfo/python-list > ====================== Why do you want to save as CSV? There is a ton of text processing programs that suit various people and thus text lends itself to a greater audience and massive amounts of processing tools. Tools people already know how to use. Would you be happier with a simple reliable method to extract information from Excel files without all that bother? In truth - perhaps on occasion. But take a look at the following*. I can process 1,000's of files while I am asleep and I don't even need to know the internal layout. Secretaries, Clerks and even Student help can use their favorite text program to search and replace whatever. Massive amounts of data can be reviewed and corrected by non-special computer users. Not to mention my use of things like sed for the bulk work. If so, consider the xlrd package (http://www.lexicon.net/sjmachin/xlrd.htm). I did download it. I'll give it a "test drive" as soon as I can. Then I can comment on it. There are times when it could be handy. If you really do need CSV files, still consider xlrd in combination with the Python csv module -- remove all that user involvement... Point here is I need human review. What I don't need is typos. The intent in the original Clerk statement was to poke fun at Window$. Microsoft "point'n'click" is very non-production oriented. "The following*" ==================== #!/--- # import os import win32com.client excel = win32com.client.Dispatch( 'Excel.Application' ) excel.Visible=0 #=1 shows the spreadsheet (can be handy) xlCSV = 6 # a substitute for the list generator list = ["c:\\temp\\test.xls", "c:\\temp\\test1.xls"] for nm in list: csv = os.path.splitext( nm )[0] + '.csv' print "Procesing file:", csv if os.path.exists(csv): os.unlink(csv) wb = excel.Workbooks.Open( nm ) wb.SaveAs( csv, xlCSV ) wb.Close( False ) excel.Quit() print "Check to see if this worked for you." # end of file ==================== The case at hand is that The State of California has been keeping weather records for awhile. The more reliable stations date from the 1920's. Others go back into the latter 1800's. Satellite reporting is rather new. Before that one took a horse or a buckboard and went off to check things. Daily data is missing (even now) for various reasons. The human can do what computers cannot - think (we hope) :). Some forms of omissions can be bulk checked. Some cannot. It is counter productive to try to create 'the all encompassing program'. The 'do all' does, as yet, not exist. If someone reading this got lost, try this; would you consider taking your brand new Ferrari 4-wheeling in the Grand Canyon? Or would you prefer that beat-up old jeep over there? Sometimes just getting out and walking around accomplishes more. Maybe not as fast, but usually better. The trick is knowing which to program and which to give to the kid. It is also counter productive to force people well trained on Tool A to only use Tool B. Better to find a common zone and let each use their respective favorite. "If you are not converting data, you are not producing anything useful." -- Me John - Thanks for the link. I will test the library. Steve norseman at hughes.net From rw at smsnet.pl Wed Aug 27 05:30:09 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 27 Aug 2008 02:30:09 -0700 (PDT) Subject: logging exceptions References: <3c8c0b98-54ea-4112-8db9-e0040929e558@w1g2000prk.googlegroups.com> <200e9b4d-c062-4984-bcec-581666458071@79g2000hsk.googlegroups.com> Message-ID: <1868e033-8313-414c-a82a-35a8852ffb77@v57g2000hse.googlegroups.com> Vinay Sajip napisa?(a): > On Aug 26, 10:36 am, Alexandru Mosoi wrote: > > why doesn'tloggingthrow any exception when it should? how do I > > configureloggingto throw exceptions? > > > > >>> try: > > > > ... logging.fatal('asdf %d', '123') > > ... except: > > ... print 'this line is never printed' > > ... > > Traceback (most recent call last): > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > python2.5/logging/__init__.py", line 744, in emit > > msg = self.format(record) > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > python2.5/logging/__init__.py", line 630, in format > > return fmt.format(record) > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > python2.5/logging/__init__.py", line 418, in format > > record.message = record.getMessage() > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > python2.5/logging/__init__.py", line 288, in getMessage > > msg = msg % self.args > > TypeError: int argument required > > Was your traceback from the snippet you posted? If it was, then the > exception (a TypeError) *is* being raised from logging. So I don't > understand your question "why doesn't logging throw any exception when > it should?", because logging is raising an exception here. No, it isn't. This traceback is *printed* in `Handler.handleError` method: __version__ = "0.5.0.2" [...] def handleError(self, record): """ Handle errors which occur during an emit() call. This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method. """ if raiseExceptions: ei = sys.exc_info() traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr) del ei > > To cause logging to *not* raise exceptions, set > logging.raiseExceptions to 0 (default is 1). The raiseExceptions > variable would normally be set to 0 in a production environment, where > you don't want logging-related exceptions to bring an application > down. Well, I think that it will not help. The exception will be printed not raised. The only solution is to redefine `handleError` method or maybe I've missed something? Br, Rob From nytrokiss at gmail.com Thu Aug 28 19:21:23 2008 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 28 Aug 2008 16:21:23 -0700 Subject: eval() == evil? --- How to use it safely? In-Reply-To: References: Message-ID: <8a6b8e350808281621u80b0222w3117acb75706535b@mail.gmail.com> I had an issue once that i was getting true and false statements in text and needed to convert them into Python boolean objects. So i wrote a function to parse the text. and return True or False based on the text. On Thu, Aug 28, 2008 at 3:09 PM, Guilherme Polo wrote: > On Thu, Aug 28, 2008 at 6:51 PM, Fett wrote: > > I am creating a program that requires some data that must be kept up > > to date. What I plan is to put this data up on a web-site then have > > the program periodically pull the data off the web-site. > > > > My problem is that when I pull the data (currently stored as a > > dictionary on the site) off the site, it is a string, I can use eval() > > to make that string into a dictionary, and everything is great. > > However, this means that I am using eval() on some string on a web- > > site, which seems pretty un-safe. > > > > I read that by using eval(code,{"__builtins__":None},{}) I can prevent > > them from using pretty much anything, and my nested dictionary of > > strings is still allowable. What I want to know is: > > > > What are the dangers of eval? > > - I originally was using exec() but switched to eval() because I > > didn't want some hacker to be able to delete/steal files off my > > clients computers. I assume this is not an issue with eval(), since > > eval wont execute commands. > > - What exactly can someone do by modifying my code string in a command > > like: thing = eval(code{"__builtins__":None},{}), anything other than > > assign their own values to the object thing? > > By "disabling" __builtins__ you indeed cut some obvious tricks, but > someone still could send you a string like "10 ** 10 ** 10". > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > -- Guilherme H. Polo Goncalves > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Tue Aug 12 08:32:59 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 12 Aug 2008 14:32:59 +0200 Subject: Help counting the total number of dictionaries inside a list that contain a specified key value In-Reply-To: <8d37bc060808120519n7f7cefban136469c49265391a@mail.gmail.com> References: <8d37bc060808120409r70fb5469kb56186b812dcc434@mail.gmail.com> <8d37bc060808120506n5e94819cp42b99c048bffc903@mail.gmail.com> <8d37bc060808120519n7f7cefban136469c49265391a@mail.gmail.com> Message-ID: Jon Bowlas wrote: > I'm afraid I can't use Peters suggestion as I'm using python 2.3 and > it doesn't have the collection module. Thanks anyway. Python 2.3 is the reason. It doesn't support the generator expression syntax. Try sum([u'Level 2 Courses' in dct for dct in yourlist]) or len([1 for dct in yourlist if u'Level 2 Courses' in dct]) Christian From BjornSteinarFjeldPettersen at gmail.com Sat Aug 9 18:14:06 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sat, 9 Aug 2008 15:14:06 -0700 (PDT) Subject: Class definition attribute order References: <5fb776ae-e3d7-49ec-9ebf-350b9bf9cac1@l42g2000hsc.googlegroups.com> <64ce3665-c76a-4ee1-b7cf-be5eef7e793f@z72g2000hsb.googlegroups.com> Message-ID: On Aug 9, 7:55?am, Michele Simionato wrote: > On Aug 5, 5:05?am, Michele Simionato > > > Yep. Seehttp://stacktrace.it/articoli/2008/01/metaclassi-python-3000 > > (I am working on an English translation these days, > > but for the moment you can use Google Translator). > > > ?M. Simionato > > FWIW, I have just finished translating the first > part of the article and I have posted it on my > blog on Artima: > > http://www.artima.com/weblogs/viewpost.jsp?thread=236234 Great feature and great article! I haven't used ABCs yet, so my initial instinct would be to derive odict from dict (it would obviate the conversions in the metaclass). Are you using ABCs just to play with all the new toys at the same time? ;-) -- bjorn From uclamathguy at gmail.com Wed Aug 6 01:20:06 2008 From: uclamathguy at gmail.com (Ryan Rosario) Date: Tue, 5 Aug 2008 22:20:06 -0700 (PDT) Subject: Trying to fix Invalid CSV File References: <0427191c-d493-442d-ba26-94802bc6062b@v13g2000pro.googlegroups.com> <078f7aad-3bba-49b4-8978-18ac5bfaa6f7@r15g2000prd.googlegroups.com> <6bade254-5001-4ae2-a000-003b84437a76@w1g2000prk.googlegroups.com> <42134ad4-ae35-4d25-94fc-2504d29003e6@r15g2000prh.googlegroups.com> Message-ID: <6bfd79e6-3b7c-4176-a3a9-941f8fa78e02@w1g2000prk.googlegroups.com> On Aug 4, 1:56?pm, Larry Bates wrote: > Ryan Rosario wrote: > > On Aug 4, 8:30 am, Emile van Sebille wrote: > >> John Machin wrote: > >>> On Aug 4, 6:15 pm, Ryan Rosario wrote: > >>>> On Aug 4, 1:01 am, John Machin wrote: > >>>>> On Aug 4, 5:49 pm, Ryan Rosario wrote: > >>>>>> Thanks Emile! Works almost perfectly, but is there some way I can > >>>>>> adapt this to quote fields that contain a comma in them? > >> > > >>> Emile's snippet is pushing it through thecsvreading process, to > >>> demonstrate that his series of replaces works (on your *sole* example, > >>> at least). > >> Exactly -- just print out the results of the passed argument: > > >> rec.replace(',"',",'''").replace('",',"''',").replace('"','""').replace("'''",'"') > > >> '123,"Here is some, text ""and some quoted text"" where the quotes > >> should have been doubled",321' > > >> Where it won't work is if any of the field embedded quotes are next to > >> commas. > > >> I'd run it against the file. ?Presumably, you've got a consistent field > >> count expectation per record. ?Any resulting record not matching is > >> suspect and will identify records this approach won't address. > > >> There's probably better ways, but sometimes it's fun to create > >> executable line noise. ?:) > > >> Emile > > > Thanks for your responses. I think John may be right that I am reading > > it a second time. I will take a look at theCSVreader documentation > > and see if that helps. Then once I run it I can see if I need to worry > > about the comma-next-to-quote issue. > > This is a perfect demonstration of why tab delimited files are so much better > than comma and quote delimited. ?Virtually all software can handle table > delimited as well as comma and quote delimited, but you would have none of these > problems if you had used tab delimited. ?The chances of tabs being embedded in > most data is virtually nil. > > -Larry Thank you for all the help. I wasn't using Emile's code correctly. It fixed 99% of the problem, reducing 30,000 bad lines to about 300. The remaining cases were too difficult to pin a pattern on, so I just spent an hour fixing those lines. It was typically just adding one more " to one that was already there. Next time I am going to be much more careful. Tab delimited is probably better for my purpose, but I can definitely see there being issues with invisible tab characters and other weirdness. Ryan From fredrik at pythonware.com Thu Aug 28 14:38:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 28 Aug 2008 20:38:42 +0200 Subject: no string.downer() ? In-Reply-To: References: <53a51084-8ec9-4069-99b6-7d494002a308@56g2000hsm.googlegroups.com> <9364d88d-6792-4398-8703-cad69b5be3f5@b38g2000prf.googlegroups.com> Message-ID: Tobiah wrote: >> Never ascribe to humour that which can be adequately explained by >> increadible stupidity! > > I love the irony. Muphry's law. From abesto0 at gmail.com Sat Aug 2 08:50:38 2008 From: abesto0 at gmail.com (=?ISO-8859-1?Q?Zolt=E1n_Nagy?=) Date: Sat, 02 Aug 2008 14:50:38 +0200 Subject: Concise way to format list/array to custom(hex) string In-Reply-To: <48944aa1$0$289$7a628cd7@news.club-internet.fr> References: <48944aa1$0$289$7a628cd7@news.club-internet.fr> Message-ID: Kurien Mathew ?rta: > Hello, > > What will be a concise & efficient way to convert a list/array.array of > n elements into a hex string? For e.g. given the bytes > [116, 111, 110, 103, 107, 97] > I would like the formatted string > 0x74 0x6f 0x6e 0x67 0x6b 0x61 > > Is there an approach better than below: > hex = '' > for b in bytes: > hex += ('0x%x '%b) > You should avoid multiple string additions, as each one creates a new string object (str objects are immutable). Try this: bytes = [116, 111, 110, 103, 107, 97] string = ''.join( ['0x%x '%b for b in bytes] ) From mattheww at chiark.greenend.org.uk Tue Aug 5 13:06:58 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 05 Aug 2008 18:06:58 +0100 (BST) Subject: URLs and ampersands References: <00a78f7e$0$20302$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I'm using urllib.urlretrieve() to download HTML pages, and I've hit a > snag with URLs containing ampersands: > > http://www.example.com/parrot.php?x=1&y=2 > > Somewhere in the process, urls like the above are escaped to: > > http://www.example.com/parrot.php?x=1&y=2 > > which naturally fails to exist. > > I could just do a string replace, but is there a "right" way to escape > and unescape URLs? I've looked through the standard lib, but I can't find > anything helpful. I don't believe there is a concept of 'escaping a URL' as such. How you escape or unescape a URL depends on what context you're embedding it in or extracting it from. In this case, it looks like you have URLs which have been escaped to go into an html CDATA attribute value (such as ). I believe there is no documented function in the Python standard library which reverses this escaping (short of putting your string into a larger document and parsing that with a full html or xml parser). -M- From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 20 05:31:59 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 20 Aug 2008 11:31:59 +0200 Subject: getattr() on nested functions? In-Reply-To: References: Message-ID: <48abe483$0$31875$426a74cc@news.free.fr> Gabriel Rossetti a ?crit : > Hello, > > I can't get getattr() to return nested functions, Of course. Nested functions are not attributes of their container function. > I tried this : > > >>> def toto(): > ... def titi(): > ... pass > ... f = getattr(toto, "titi") > ... print str(f) > ... > >>> toto() > Traceback (most recent call last): > File "", line 1, in > File "", line 4, in toto > AttributeError: 'function' object has no attribute 'titi' > >>> > > I thought that since functions are objects, that I could obtain it's > nested functions. Well, there's probably a very hackish way, but it's not worth the pain. The fact that functions are objects doesn't make nested functions methods of that object. If what you really want are methods, then you can write your own callable: class _Test(object): def request(self, params): pass def submit(self, params, values): pass def update(self, params, values): pass def delete(self, params): pass def __call__(self, action, *args): return resultToXml(getattr(self, action)(*args)) _test = _Test() But read the remaining before... > How come it doesn't work and what can I do to > fix/replace it? I'm using it in code that is like this : > > def __test(self, action, *args): > def request(params): > pass > def submit(params, values): > pass > def update(params, values): > pass > def delete(params): > pass > result = getattr(__test, action)(*args) > return resultToXml(result) > > where "action" is a string containing either "request", "submit", > "update", or "delete". I was using an evel() with this form : > > result = eval(action + "(params, values)") Wrong use case for eval, as usual. > but I didn't find that very clean. indeed !-) locals() is your friend. def _test(self, action, *args): def request(params): pass def submit(params, values): pass def update(params, values): pass def delete(params): pass result = locals()[action](*args) return resultToXml(result) HTH From pavlovevidence at gmail.com Fri Aug 1 17:13:04 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 1 Aug 2008 14:13:04 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> <5a0b303a-8324-4eeb-a975-397371bf2875@b1g2000hsg.googlegroups.com> Message-ID: <8956f8ca-1f5a-465a-9b02-5ad9b1c97876@l64g2000hse.googlegroups.com> On Aug 1, 4:45 pm, Carl Banks wrote: > On Aug 1, 3:36 pm, Terry Reedy wrote: > > In general, asking code to apply across numeric, container, and other > > classes is asking too much. Python code can be generic only within > > protocol/interface categories such as number-like, sortable, and > > iterable. But making tests too specific can unnecessarily prevent even > > that. > > At some point we have to throw our hands up and realize that if we're > working with custom classes with varying degrees of nonconformance, > there is nothing we can do that's safe. And I want to make clear I'm not trying to downplay your example here. The example you gave me definitely fits the criteria of being a useful "if x" that can't be replaced by a simple explicit test, at least after my alteration to a vector example. It's a concern when you write code that breaks realistic custom classes, but really concerning when it breaks built-in classes. Carl Banks From adityashukla1983 at gmail.com Sun Aug 17 18:14:56 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Sun, 17 Aug 2008 17:14:56 -0500 Subject: command line tool for process communication Message-ID: <73045cca0808171514j6ab1195ag7d0909a048bb51ea@mail.gmail.com> Hello guys, I have a program which is run through command line .I am trying to create another command line tools which controls this program. So for example in my new program when i give newprog -a then it should invoke the existing tool and perform one of its operation.eg existtprog -s How could this be done in python? Optparse can be used to make the new tool but what should be done to control the existing tool from the new tool? Thanks in advance. Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From jimgardener at gmail.com Wed Aug 27 12:57:15 2008 From: jimgardener at gmail.com (jimgardener) Date: Wed, 27 Aug 2008 09:57:15 -0700 (PDT) Subject: import error between 2 modules References: <98825d39-e457-4957-bfdc-846b7eca6ca9@w1g2000prk.googlegroups.com> Message-ID: <25c9bda7-7715-4fcf-bf74-34fdd91d55cc@n33g2000pri.googlegroups.com> On Aug 27, 5:37 pm, Laszlo Nagy wrote: > These constructors will be calling each other forever. This will be an infinite recursion. sorry,that was a quite stupid mistake on my part..thanks for pointing out.. jim From brennan.ron at gmail.com Wed Aug 27 16:26:45 2008 From: brennan.ron at gmail.com (Ron Brennan) Date: Wed, 27 Aug 2008 16:26:45 -0400 Subject: Multiple values for one key Message-ID: <26c69b160808271326w2f53b6b8s6e4aa7f91071ac71@mail.gmail.com> Hello, How would I create a dictionary that contains multiple values for one key. I'd also like the key to be able to have duplicate entries. Thanks, Ron -- FYI, my email address is changing. My rogers account will be deactivated shortly. From now on please use: brennan.ron at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sat Aug 30 03:11:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 30 Aug 2008 04:11:33 -0300 Subject: Which is faster? References: <00c8e015$0$20302$c3e8da3@news.astraweb.com> Message-ID: En Sat, 30 Aug 2008 03:15:30 -0300, Steven D'Aprano escribi?: > On Fri, 29 Aug 2008 21:26:35 -0700, cnb wrote: > >> def averageGrade(self): >> tot = 0 >> for review in self.reviews: >> tot += review.grade >> return tot / len(self.reviews) >> >> def av_grade(self): >> return sum(review.grade for review in self.reviews) / \ >> len(self.reviews) > > Re-writing the functions so they can be tested alone: > > def averageGrade(alist): > tot = 0.0 > for x in alist: > tot += x > return tot/len(alist) > > > def av_grade(alist): > return sum(alist)/len(alist) > > >>>> from timeit import Timer >>>> # small amount of items > ... alist = range(100) >>>> Timer('averageGrade(alist)', > ... 'from __main__ import alist, averageGrade').repeat(number=100000) > [3.9559240341186523, 3.4910569190979004, 3.4856188297271729] >>>> >>>> Timer('av_grade(alist)', > ... 'from __main__ import alist, av_grade').repeat(number=100000) > [2.0255107879638672, 1.0968310832977295, 1.0733180046081543] > > > The version with sum() is much faster. How about with lots of data? > >>>> alist = xrange(1000000) >>>> Timer('averageGrade(alist)', > ... 'from __main__ import alist, averageGrade').repeat(number=50) > [17.699107885360718, 18.182793140411377, 18.651514053344727] >>>> >>>> Timer('av_grade(alist)', > ... 'from __main__ import alist, av_grade').repeat(number=50) > [17.125216007232666, 15.72636890411377, 16.309713840484619] > > sum() is still a little faster. Mmm, in this last test you're measuring the long integer operations performance (because the sum exceeds largely what can be represented in a plain integer). Long integers are so slow that the difference between both loops becomes negligible. I've tried again using float values: alist = [float(x) for x in xrange(1000000)] and got consistent results for any input size (the version using sum() is about twice as fast as the for loop) -- Gabriel Genellina From code at pizzashack.org Wed Aug 20 18:46:42 2008 From: code at pizzashack.org (Derek Martin) Date: Wed, 20 Aug 2008 18:46:42 -0400 Subject: python custom command interpreter? In-Reply-To: References: Message-ID: <20080820224642.GD28038@dragontoe.org> On Wed, Aug 20, 2008 at 03:19:19PM -0400, joey boggs wrote: > In the end I'd like to be able to run a custom interpreter and just feed it > one command and a directory. The end result in the kickstart something like > this: > > %post --interpreter #!/usr/bin/myinterpreter > DROP /tmp/directory > DROP /tmp/directory2 What is the problem you are trying to solve? Are you asking how to write a shell in Python? > How would I setup the interpreter to take the DROP command? You wouldn't... "setup" is a noun. You might "set up" an interpreter though. > I've been reading and searching all day but I haven't found anything > close to what I'm doing. I realize that using custom commands in > this case is overkill but in the end is used to make the users life > easier. How so? What could be easier than "rm -rf directory"? > If anyone can point me to some documentation I would be more than > grateful. I'd be happy to, but I can't imagine what sort of documentation would help you. It sounds like what you want to do, basically, is write a program to read commands from stdin, parse them to make sure the syntax is right, and then execute the equivalent code in Python. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jianbing.chen at gmail.com Fri Aug 15 10:02:03 2008 From: jianbing.chen at gmail.com (jianbing.chen at gmail.com) Date: Fri, 15 Aug 2008 07:02:03 -0700 (PDT) Subject: help on import libxml2 References: <092ae320-f21b-473f-9c41-80da00568a12@f63g2000hsf.googlegroups.com> <1a760b5a-bec1-4221-a746-d10324b05ca8@t54g2000hsg.googlegroups.com> Message-ID: <38adeea7-2e04-408f-9f18-5121b3d86794@k7g2000hsd.googlegroups.com> Paul, Thanks. This helped. Jianbing On Aug 14, 4:10?pm, Paul Boddie wrote: > On 14 Aug, 22:43, jianbing.c... at gmail.com wrote: > > > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? File "/sea/local/lib/python2.5/site-packages/libxml2.py", line 1, in > > > > ? ? import libxml2mod > > ImportError: ld.so.1: python: fatal: relocation error: file /usr/local/ > > lib/python2.5/site-packages/libxml2mod.so: symbol > > xmlXIncludeProcessFlags: referenced symbol not found > > The symbol mentioned should be found in the libxml2.so library file > (which I discovered by running nm on the static libxml2.a file). On my > Ubuntu system, if I run the ldd program on the libxml2mod.so file (in > a different place to where yours lives), I get the following results: > > ? ldd /var/lib/python-support/python2.5/libxml2mod.so > ? ? ? ? linux-gate.so.1 => ?(0xffffe000) > ? ? ? ? libxml2.so.2 => /usr/lib/libxml2.so.2 (0xb7e0b000) > ? ? ? ? libc.so.6 => /lib/tls/i686/cmov/libc.so.6 (0xb7cca000) > ? ? ? ? libdl.so.2 => /lib/tls/i686/cmov/libdl.so.2 (0xb7cc5000) > ? ? ? ? libz.so.1 => /usr/lib/libz.so.1 (0xb7cb1000) > ? ? ? ? libm.so.6 => /lib/tls/i686/cmov/libm.so.6 (0xb7c8a000) > ? ? ? ? /lib/ld-linux.so.2 (0x80000000) > > I suggest you run ldd on /usr/local/lib/python2.5/site-packages/ > libxml2mod.so for each user and see what it tells you. Perhaps there > are permissions issues on the libxml2.so files, wherever they are > installed, or there's a LD_LIBRARY_PATH (or equivalent) setting that > one user has that the other doesn't. > > Paul From timothy.grant at gmail.com Thu Aug 7 18:15:33 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Thu, 7 Aug 2008 15:15:33 -0700 Subject: A question about string and float number In-Reply-To: References: <489A8A01.1050908@linkline.com> Message-ID: That's because s IS a string. It's not been converted to a float. In [1]: s = '3.1415' In [2]: n = float(s) In [3]: type(s) Out[3]: In [4]: type(n) Out[4]: Why are you avoiding the very simple try:/except: solution to this problem? On Thu, Aug 7, 2008 at 1:28 PM, Wei Guo wrote: > Hi I tried the first type method but it seens that it doesn't work. Could > anyone help me about it? > >>>> s = '3.145' >>>> type(s) == type(float()) > False >>>> type(s) > >>>> type(float()) > >>>> > > Best regards, > > Wei > > > On 8/7/08, Wei Guo wrote: >> >> Hi Thanks for Tyler and Edwin's help. >> >> For my questions, I need to import some xml file and there are floating >> number and strings in it. I need to process string and number differently. >> This is reason that I am asking question here. Is this background >> information we need for this quesions. >> >> Btw, which way is better? type or with exception ValueError? >> >> Thanks, >> >> Wei >> >> >> On 8/6/08, Tyler Breisacher wrote: >>> >>> It's generally a bad idea to use "except" without naming a specific >>> exception. The exception you might expect in this case is ValueError. Any >>> other exception *should* be uncaught if it happens. By the way, this method >>> will return true for integers as well as floats. For example, isFloat('3') >>> will return 3.0. So make sure this is what you want, since it wasn't 100% >>> clear from the original message. >>> >>> >>> Wei Guo wrote: >>>> >>>> #this is a better way of testing a string for float >>>> def isFloat(s): >>>> try: >>>> s = float(s) >>>> except: >>>> return False >>>> return True >>> >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Stand Fast, tjg. [Timothy Grant] From fredrik at pythonware.com Fri Aug 29 01:30:04 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 29 Aug 2008 07:30:04 +0200 Subject: Python in a Nutshell -- Book vs Web In-Reply-To: References: Message-ID: Cameron Laird wrote: > No. No, to an almost libelous extent. No matter what you write about, there's always a certain subcategory of potential readers who insist that collection, editing, filtering, structuring, clarification, and the author's real-life experience of the topic he's writing about has no value at all. My guess is that they don't value their own time very highly. From harrrrpo at gmail.com Sat Aug 30 08:49:01 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Sat, 30 Aug 2008 05:49:01 -0700 Subject: Fastest way to write huge files In-Reply-To: References: <538050a90808281735u51ce90d0o3db3945a6ed2b591@mail.gmail.com> <48B7A8DA.7050203@timgolden.me.uk> Message-ID: <538050a90808300549v62860522h51028513afbdf7ad@mail.gmail.com> > > If connection is over Internet via HTTP the connection speed is so slow in > relation to the speed of your CPU that it doesn't really matter. this is not always true , espicially when using a localhost or a local netwtork server the problem is the increase in cpu and memory usage make it a painful bug such that downloading a big file (say 1 GB ) would introduce a big cpu usage (already tested) Thanks , Regards, Mohamed Yousef From pavlovevidence at gmail.com Fri Aug 1 17:00:01 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 1 Aug 2008 14:00:01 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> <5a0b303a-8324-4eeb-a975-397371bf2875@b1g2000hsg.googlegroups.com> Message-ID: <391e0166-7a94-4302-97f1-dbf02cc6c756@8g2000hse.googlegroups.com> On Aug 1, 4:45 pm, Carl Banks wrote: > On Aug 1, 3:36 pm, Terry Reedy wrote: > > > > > > Nevertheless, I think this is probably the best example of the > > > enhanced polymorphism of "if x" yet. I'm kind of surprised no one > > > came up with it.) > > > I think of Python code as 'generic' rather than 'polymorphic'. I am not > > sure if that is a real difference or not, since I am a bit fuzzy on the > > meaning of 'polymorphic' in this context. > > > The generality of 'if x:' depends on the context. If x is defined as a > > number by doc or previous code (or possibly even by subsequent code), > > then 'if x:' is equivalent to 'if x != 0:'. At this point, it is a > > stylistic argument which to use. > > > But here is an example where 'if x:' is more generic. > > > def solve(a,b): > > 'a and b such that b/a exists' > > if a: > > return a/b > > else: > > raise ValueError('a not invertible, cannot solve' > > > Now suppose we have a matrix class (2x2 for simplicity and realism). > > Its __bool__ (3.0) method implements 'is non-singular'. As written > > above, solve(mat,vec) works (with compatible mat and vec sizes), but it > > would not with 'if a != 0:'. > > I see what you're saying, even though this example turns out to be > pretty bad in practice. > > (Practically speaking, you hardly ever write code for both matrices > and scalars, because the optimal way for matrices would be convoluted > and opaque for scalars, though scalars can sometimes be fed into > matrix code as a degenerate case. Also, checking the condition of the > matrix by calculating and comparing the determinant to zero is like > comparing float equality without a tolerance, only much, much worse.) > > But instead of a matrix, take a vector (which has a better chance of > being used in code designed for scalars) and define a zero-length > vector as false, and that could be a good example. > > > In general, asking code to apply across numeric, container, and other > > classes is asking too much. Python code can be generic only within > > protocol/interface categories such as number-like, sortable, and > > iterable. But making tests too specific can unnecessarily prevent even > > that. > > At some point we have to throw our hands up and realize that if we're > working with custom classes with varying degrees of nonconformance, > there is nothing we can do that's safe. > > > > Something versus nothing is a useless concept most of the time, but > > > occasionally finds use in human interaction cases such as printing. > > > It is sometimes useful within categories of classes, as in my solve example. > > I'm going to say no. > > Let's take your matrix example: you defined singularity to be false, > but singularity can't reasonably be mapped to the concept of nothing. > For "nothing" I would think you'd want a 0x0 matrix. Something vs > nothing also implies that all objects should have a boolean value. > So, assuming boolean is connected to a matrices singularity, what > should be the boolean value of non-square matrices? > > No, I'm going to have to disagree very strongly with this. > Nonzeroness is useful. Emptiness is useful. Singularity a kind of > useful. Nothing and something are vague, ill-defined, ad hoc concepts > that mean nothing to a computer. Have you ever seen an algorithm that > says "if x is something"? > > Something and nothing do seem to come into play occasionally in that, > when interacting with humans (be it the user or programmer), it > sometimes--not nearly always--makes sense to treat nonzero and empty > in the same way. But there's no particular reason to apply the > concepts of something and nothing beyond this pragmatic use. > > Carl Banks From elessar at nienna.org Fri Aug 1 16:20:18 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 01 Aug 2008 14:20:18 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <2a56bffc-6c11-474d-b2b1-ca344ff94f09@x41g2000hsb.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> <5a0b303a-8324-4eeb-a975-397371bf2875@b1g2000hsg.googlegroups.com> <9f920209-3080-470a-817b-9afadbecc453@j22g2000hsf.googlegroups.com> <2a56bffc-6c11-474d-b2b1-ca344ff94f09@x41g2000hsb.googlegroups.com> Message-ID: <48937002.2010600@nienna.org> Carl Banks wrote: > On Aug 1, 8:49 am, Matthew Fitzgibbons wrote: >> Carl Banks wrote: >>> On Jul 31, 11:44 pm, Carl Banks wrote: >>> [snip excellent explanation of why it's hard to for "if x" to be >>> extensively polymorphic] >>> By the way, one thing I forgot to mention is Matt Fitzgibbons' filter >>> example. >>> As I said, it's hard to write code that works for both numeric and >>> container types because they share so few methods. However, sometimes >>> you don't know ahead of time what methods are used! When you're doing >>> functional programming you might pass in a method that calls the >>> appropriate method, like so: >>> def apply_if_true(func,x): >>> if x: >>> func(x) >> I find myself doing things like this surprisingly often. All you've done >> is move the decision as to what function is applied to x elsewhere. Like >> a factory, for example. I could see using something like this where func >> prepares object x to be inserted into a database, and you want to make >> sure x is meaningful first. >> >> def add_to_db(prep_func, x): >> if x: >> entry = prep_func(x) >> add_to_db(entry) >> >> 'if x' strikes me as better for this case because you might want to >> accept a non-empty list (or some other objects) but reject non-empty >> lists. 'if x is None' would not work. It still may be susceptible to the >> empty iterator problem, depending on what prep_func does. > > What if what you consider to be "meaningful" doesn't happen to > coincide with what Python considers to be "something". For instance, > what if being non-negative is what makes an integer meaningful? You > can't use "if x" for that. What if any list, including an empty one, > is meaningful, but you want to indicate the possibility of an > unmeaningful value by passing None? You can't use "if x" for that. > > So, you might address this issue by doing something like this: > > def add_to_db(prep_func, is_meaningful, x): > if is_meaningful(x): > entry = prep_func(x) > add_to_db(entry > > But if you do that, what has the polymorphism of "if x" gained you? > > The thing it gained for you before is not having to pass in a > condition: whether x was a sequence, number, or whatever, the same > condition could be used, and thus you avoided considerable > complexity. But if you have to perform tests for which the implicit > boolean doesn't work, that complexity has to be added to the code > anyway. Of course. If a chunk of code already does what you want it to, then you can use it. Otherwise you have to do something different. I was just pointing out that 'if x' often does what I want it to. Sometimes it doesn't, so I do something different. > > That matters in the context of this discussion because it limits the > usefulness of the polymorphism of "if x" for this functional idiom: > "if x" only helps you if you have no need for tests that it can't > handle. > > [snip] > > Carl Banks > -- > http://mail.python.org/mailman/listinfo/python-list > By this argument, all code is limiting. Obviously, no code can do what it can't. We're not getting anywhere; it's past time to kill this one off. -Matt From wiggly at wiggly.org Wed Aug 13 11:51:53 2008 From: wiggly at wiggly.org (Nigel Rantor) Date: Wed, 13 Aug 2008 16:51:53 +0100 Subject: You advice please In-Reply-To: <76fd5acf0808130838r44590107t3297fb3f38d38f10@mail.gmail.com> References: <20080813110444.7b48ddbc.darcy@druid.net> <76fd5acf0808130811y7d7d6584m721096295a72af98@mail.gmail.com> <48A2FBAC.3000103@wiggly.org> <76fd5acf0808130838r44590107t3297fb3f38d38f10@mail.gmail.com> Message-ID: <48A30319.9030105@wiggly.org> Calvin Spealman wrote: > God forbid I try to make a joke. Ah, sorry, sense of humour failure for me today obviously. n From bdesth.quelquechose at free.quelquepart.fr Tue Aug 19 14:45:06 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 19 Aug 2008 20:45:06 +0200 Subject: who to call a list of method inside the class itself In-Reply-To: References: Message-ID: <48ab30a4$0$12032$426a34cc@news.free.fr> Edwin.Madari at VerizonWireless.com a ?crit : > maduma at pt.lu wrote: >> Hi, >> >> Is the following code is ok. who to call all method. >> It is working but the call to m() without a reference to self seems >> strange >> >> Thanks for your help >> >> class CustomMethod: >> def method1(self): >> .... >> def method2(self): >> .... >> def method3(self): >> .... >> >> def getAllMethod(self): >> return [self.method1, self.method2, self.method3] >> >> def applyAll(self): >> for m in self.getAllMethod(): >> # how to call all methods ? >> # is it correct >> m() > > 1. return string names of required methods in getAllMethod > return ['method1', 'method2', 'method3'] > 2. use gettattr on self and then exetute methods in applyAll > def applyAll(self): > for method_name in self.getAllMethod(): > method = gettattr(self,method_name) > method() #execute method now > > Except for extra lookup time, what would this buy you ??? From tshopshire at gmail.com Thu Aug 28 18:45:28 2008 From: tshopshire at gmail.com (Tyler Shopshire) Date: Thu, 28 Aug 2008 22:45:28 GMT Subject: PyDoc in Windows Vista Message-ID: I can't seem to access the pydoc sever from my web browser. I start the server from the command prompt and everything seems to be working fine, then I got to http://localhost:8888/ and it doesn't work. I also tried starting the graphical mode with the -g parameter but I still cannot use PyDoc. It works on my Ubuntu Partition so I do know how to use it. Any help is appreciated. From NO_Kroeger at gmx.de Tue Aug 19 14:58:11 2008 From: NO_Kroeger at gmx.de (=?UTF-8?B?TmlscyBPbGl2ZXIgS3LDtmdlcg==?=) Date: Tue, 19 Aug 2008 20:58:11 +0200 Subject: Python Query: Related to locking a resource in a multithreaded environment In-Reply-To: References: Message-ID: <48AB17C3.80408@gmx.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, I don't think the global interpreter lock is what you need ... read here for reference: http://docs.python.org/api/threads.html My approach what be to write one class for reading and writing to the configuration and make that class thread-safe using the RLock. Then you create one and only one instance of this class and let all your threads use (not import) that one instance. You could achieve that "one and only one" either by having a main program which creates the instance and pass the reference to each thread via its __init__ or you implement the Configuration class as a singleton like this: class Singleton(object): """ A simple example implementing the singleton design pattern in python """ #we need two class attributes (which translate to static attributes in java) __lock = Lock() #a lock for thread safety __instance = None #and to remember the one instance #first of all: make pythons usual way of creating objects # unusable because we cannot just hide them as one would in java # or C++ def __new__(cls, *args, **kwargs): pass def __init__(self): pass @classmethod def getInstance(cls, *args, **kwargs): """ The famous gatInstance method which resturns the one instance of our class. params: cls - reference to the class *args - the tuple of arguments paassed by position **kwargs - the dictionary of arguments passed by keyword """ #enter critical section cls.__lock.acquire() try: if cls.__instance is None: #use the superclasses __new__ for creation cls.__instance = object.__new__(cls, *args, **kwargs) #place initialisation code (everything which #would usually happen in __init__) here cls.__instance.SomeInt = 1 finally: #leave critical section cls.__lock.release() return cls.__instance Add your methods for accessing as instance methods to this class and get the same instance of this class in each thread by calling Singleton.getInstance(). Hope that helps Regards Nils tarun schrieb: > I think I need something called global interpreter lock which is > accessible to all the threads. But I am not sure how to implement this. > > > On Tue, Aug 19, 2008 at 11:28 AM, tarun > wrote: > > Hello All, > > I've a configuration.ini file. This particular can be accessed by > several threads of my application. Each thread can read/write > configuration parameters from/to the configuration.ini file. I am > using threading (Rlock) to lock the resource (configuration.ini > file) while accessing it from any thread. I use the file available > at http://www.voidspace.org.uk/python/configobj.html for read/write. > > I did the following in one of my files: > > import threading > class Synchronization: > def __init__(self): > self.mutex = threading.RLock() > > Now this I can create instances of the class Synchronization and use > acquire/release to work on the shared resource. But every thread > would need to import this class and hence each thread would create a > separate instance of the class. This means several lock variables. > But I think we need a global lock flag that is accessible across all > the threads. > > How do i do this? > > Please let me know ASAP. > > Thanks In Advance, > Tarun > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list -----BEGIN PGP SIGNATURE----- iD8DBQFIqxfCzvGJy8WEGTcRApe+AJ9MNqWI9FOsJIKuTKxy8ZNSGYTy2gCdHtGc clDPMMAPRoIxsBvVm4ygi6U= =vIPW -----END PGP SIGNATURE----- -------------- next part -------------- A non-text attachment was scrubbed... Name: NO_Kroeger.vcf Type: text/x-vcard Size: 162 bytes Desc: not available URL: From deets at nospam.web.de Mon Aug 4 14:08:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 04 Aug 2008 20:08:29 +0200 Subject: Garbage collection of recursive inner function In-Reply-To: <784c3984-b32e-466a-8542-f93f2dc453d1@27g2000hsf.googlegroups.com> References: <784c3984-b32e-466a-8542-f93f2dc453d1@27g2000hsf.googlegroups.com> Message-ID: <6foustFcj6oaU1@mid.uni-berlin.de> from.future.import at gmail.com schrieb: > Hi, > > I encountered garbage collection behaviour that I didn't expect when > using a recursive function inside another function: the definition of > the inner function seems to contain a circular reference, which means > it is only collected by the mark-and-sweep collector, not by reference > counting. Here is some code that demonstrates it: > > === > def outer(): > > def inner(n): > if n == 0: > return 1 > else: > return n * inner(n - 1) > > return 42 > > import gc > gc.set_debug(gc.DEBUG_SAVEALL) > print outer() > gc.collect() > print gc.garbage > === > > Output when executed: > $ python internal_func_gc.py > 42 > [, ( 0xb7dec3ec: function object at 0xb7dbd3ac>,), 0xb7dbd3ac>] > > Note that the inner function is not called at all, it is only defined. > If the inner function is moved outside the scope of the outer > function, gc.garbage will be empty. If the inner function is inside > but not recursive, gc.garbage will also be empty. If the outer > function is called twice, there will be twice as many objects in > gc.garbage. > > Is this expected behaviour? Collecting an object when its refcount > reaches zero is preferable to collecting it with mark-and-sweep, but > maybe there is a reason that a circular reference must exist in this > situation. I want to check that first so I don't report a bug for > something that is not a bug. The reference comes from the closure of inner. And inner is part of the closure, so there is a circular reference. I don't see a way to overcome this - consider the following code: def outer(): def inner(): inner() if random.random() > .5: return inner How is the GC/refcounting to know if it can create a reference or not? Diez From castironpi at gmail.com Sat Aug 9 00:47:42 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 8 Aug 2008 21:47:42 -0700 (PDT) Subject: interpreter vs. compiled References: <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <4rl294duo83eujnq6tjbk215mavpl87o9r@4ax.com> <43f519dd-6763-4cc0-a6d2-1e671da54c2c@d45g2000hsc.googlegroups.com> <1fdd10ae-581c-428d-9268-8fca8b99aff4@2g2000hsn.googlegroups.com> <5f742714-1d29-467e-82fe-d88253542657@79g2000hsk.googlegroups.com> <33d58bd6-ba49-4517-9d79-884988025e50@r66g2000hsg.googlegroups.com> <8df89e54-b106-4bfb-9937-974c8d2d4776@j22g2000hsf.googlegroups.com> Message-ID: <6486eee8-fcc8-4b6b-8cf9-b6dae3dd9b41@m3g2000hsc.googlegroups.com> On Aug 5, 2:09?pm, "paulo.jpi... at gmail.com" wrote: > Regarding exploring processor instructions. > > Lets say you compile a C program targeting x86 architecture, with > optimizations > turned on for speed, and let the compiler automatic select MMX and SSE > instructions > for numeric code. > > I have now a program that executes very fast, and does what I want > very well. Now > when I execute it on a x86 processor with the new SSE 4 instructions, > it will not > matter, because it cannot take advantage of them. > > With a JIT is different. Assuming that the JIT is also aware of the > SSE 4 instructions, > it might take advantage of this new set, if for a given instruction > sequence it is better > to do so. > > For the usage of the profile guided optimizations, here go a few > examples. > > The JIT might find out that on a given section, the vector indexes are > always correct, so > no need for bounds verification is needed. Or if the language is a OOP > one, it might come > to the conclusion that the same virtual method is always called, so > there is no need for > a VMT lookup before calling the method, thus it replaces the already > generated code by > a direct call. > > Or that a small method is called enough times, so it would be better > to inline it instead. > > Here are a few papers about profile guided optimizations: > > http://rogue.colorado.edu/EPIC6/EPIC6-ember.pdfhttp://www.cs.princeton.edu/picasso/mats/HotspotOverview.pdf > > Of course most of these optimizations are only visible in applications > that you use for longer > that 5m. > > -- > Paulo There are two things I can emphasize after reading the papers and your post. One is the benefit of distributing an incompletely compiled module, which is that it makes machine-targeted specializations possible right then and there, and does not require recompiling from the source on the original author's/distributor's budget. Even if there's no YOURSUITE.EXE built, the code is still in a state where you can make one, by only needing JIT.LIB on your machine. The second is the massive use of lightweight profiling in choosing optimizations in JIT. One of the advantages is inlining common function sequences, that you would either have to detect yourself, or inline everything, to achieve. What are some others? From ndbecker2 at gmail.com Wed Aug 6 08:44:21 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 06 Aug 2008 08:44:21 -0400 Subject: Find class of an instance? Message-ID: Sounds simple, but how, given an instance, do I find the class? From lists at cheimes.de Sat Aug 16 17:42:19 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 16 Aug 2008 23:42:19 +0200 Subject: Good python equivalent to C goto In-Reply-To: <48a744b6$0$299$7a628cd7@news.club-internet.fr> References: <48a744b6$0$299$7a628cd7@news.club-internet.fr> Message-ID: Kurien Mathew wrote: > Hello, > > Any suggestions on a good python equivalent for the following C code: > There are various ways to write your example in Python. For example while loopCondition: condition = 1 while condition: if condition1: break if condition2: break if condition3: break stmt1 stmt2 condition = 0 else: stmt3 stmt4 The else block of while isn't execute if you break out of while. You can emulate multiple gotos with exceptions. In general you shouldn't try to mimic C in Python code. C like Python code is often hard to read and slower than well designed Python code. From deets at nospam.web.de Wed Aug 27 03:42:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 27 Aug 2008 09:42:00 +0200 Subject: unexpected from/import statement behaviour In-Reply-To: <1a66cf9d-88e3-437f-aa4d-ec13a153cab1@25g2000prz.googlegroups.com> References: <42780654-8a54-470e-a494-ca53fd0504f5@p25g2000hsf.googlegroups.com> <1a66cf9d-88e3-437f-aa4d-ec13a153cab1@25g2000prz.googlegroups.com> Message-ID: <6hkeq8Flqcu4U2@mid.uni-berlin.de> alex23 schrieb: > nisp wrote: >> I've always been convinced of the equivalence of the two ways of using >> the import statement but it's clear I'm wrong :-( > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> from sys import stderr >>>> import sys >>>> sys.stderr is stderr > True > > Behaviourly, I'm finding no difference between the two either. > > Could you cut & paste a minimal example that isn't producing the > correct behaviour, and perhaps mention what type of OS you're using? You did not read this part of the post: """ I'm not able to capture its stderr and of course I would like not to do this kind of change. """ He tries to set sys.stderr to a new stream and capture the print statements, but fails to do so because he created a local alias. Diez From matthew at woodcraft.me.uk Thu Aug 28 15:58:10 2008 From: matthew at woodcraft.me.uk (Matthew Woodcraft) Date: Thu, 28 Aug 2008 19:58:10 GMT Subject: Python svn bindings for Subversion? References: <9bfdb452scm8ks5ci27a6so2f3rc3nsvv2@4ax.com> Message-ID: <873ako6hf1.fsf@golux.woodcraft.me.uk> Mike B writes: > I'm trying to get Subversion 'hook scripts' working on an Ubuntu box and the > following fails. > > from svn import fs, repos, core, delta [...] > 'svn' appears to be a SWIG wrapper and could be what I'm looking for, but I > cannot find it anywhere. > > Can anyone point me in the right direction. It's maintained as part of the main Subversion distribution. http://svn.collab.net/viewvc/svn/trunk/subversion/bindings/swig/ In Ubuntu, it should be in the python-subversion package. -M- From castironpi at gmail.com Sat Aug 16 18:20:52 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 16 Aug 2008 15:20:52 -0700 (PDT) Subject: mmap and ctypes References: <48a74b26$0$23839$426a34cc@news.free.fr> Message-ID: On Aug 16, 4:42?pm, "Michel Claveau - NoSpam SVP ; merci" wrote: > Hi! > > I use mmap for interchange data between Python & Autoit. ?For that, I > use (Autoit's side) a little DLL. > This DLL can, perhaps, be used with ctypes. > > @-salutations > -- > Michel Claveau Say more-- what DLL? @-greetings From fabiofz at gmail.com Fri Aug 1 13:36:20 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Fri, 1 Aug 2008 14:36:20 -0300 Subject: Pydev 1.3.19 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.19 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Code Analysis: Not all unused imports are shown in the message anymore (could give problems saving workspace). * Code Analysis: Fixed problem on double cycle in list comprehension. * Interpreter config: The initial parse of the modules is much faster. Release Highlights in Pydev: ---------------------------------------------- Pydev 1.3.19 Release highlights ---------------------- * Eclipse 3.2: Interactive console working * Eclipse 3.4: Hyperlinks working * Eclipse 3.4: Move / rename working * raw_input() and input(): functions are now changed when a program is launched from eclipse to consider a trailing '\r' * Ctr+/: Changed to toggle comment (instead of only comment) -- patch from Christoph Pickl * Pydev package explorer: Link working with compare editor * Auto-indent: Fixed problem when smart indent was turned off * Debugger: Better inspection of internal variables for dict, list, tuple, set and frozenset * Console: When a parenthesis is entered, the text to the end of the line is no longer deleted * Code Formatter: can deal with operators (+, -, *, etc) * Code Formatter: can handle '=' differently inside function calls / keyword args * Problem while navigating pydev package explorer fixed * Race condition fixed in PythonNatureStore/PythonNature (thanks to Radim Kubacki) * Halt fixed while having multiple editors with the same file (with the spell service on) * Pythonpath is no longer lost on closed/imported projects * Applying a template uses the correct line delimiter * NPE fixed when creating editor with no interpreter configured * Hyperlink works in the same way that F3 (saves file before search) What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From med.swl at gmail.com Fri Aug 22 18:43:22 2008 From: med.swl at gmail.com (Medardo Rodriguez (Merchise Group)) Date: Fri, 22 Aug 2008 18:43:22 -0400 Subject: >> and << operators? In-Reply-To: References: Message-ID: <4891add70808221543w195fb88am2d4f84a52c6eb195@mail.gmail.com> On Fri, Aug 22, 2008 at 6:30 PM, defn noob wrote: > What does >> and << do? Normally they are bitwise operators: >> Shifts bits right << Shifts bits left print 1 << 3 8 because 8 = 00001000 in binary Regards From wtanksleyjr at gmail.com Mon Aug 4 12:39:28 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Mon, 4 Aug 2008 09:39:28 -0700 (PDT) Subject: Bidirectional Generators References: <8e2cf6b7-4b5f-4701-8a4c-bc779ed7305c@m45g2000hsb.googlegroups.com> <976df308-3855-4f2b-a82a-dacba480e7d7@i76g2000hsf.googlegroups.com> Message-ID: <4f1ac687-2401-4ee7-acd9-b0eb3ef8e910@v39g2000pro.googlegroups.com> Paddy wrote: > What's one of them then? I'm sorry, I don't know what you mean. Meanwhile, more pertinently: I did get my generator working, and then I replaced it with a class that did the same thing in less than a quarter of the number of lines. So... I'm not going to worry about that anymore. My use case obviously wasn't the right one for them. I'm still curious, though, whether anyone's written any code that actually uses yield _and_ send() to do anything that isn't in the original PEP. > - Paddy. -Wm From google at mrabarnett.plus.com Wed Aug 20 05:56:07 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 20 Aug 2008 02:56:07 -0700 (PDT) Subject: How to stop iteration with __iter__() ? References: <836a8d0a-ce00-40da-bc7c-f390ead0acfe@w7g2000hsa.googlegroups.com> <92953733-f834-4e84-a83c-eb0edc9a8a05@1g2000pre.googlegroups.com> Message-ID: <7cf65c80-8667-45fb-88b3-795c9c6c4ecc@m36g2000hse.googlegroups.com> On Aug 20, 12:11?am, John Machin wrote: > On Aug 20, 5:06 am, Terry Reedy wrote: > > > In your case, the standard Python idiom, as Jon said, is > > > it = iter(iterable) > > next(it) # 2.6, 3.0 > > for for item in iterable: > > ? ?f(item) > > or, perhaps, for completeness/paranoia/whatever: > > it = iter(iterable) > try: > ? ?headings = it.next() # < 2.5 > except StopIteration: > ? ?# code to handle empty > for item etc etc > I think it needs to be: it = iter(iterable) try: headings = it.next() # < 2.5 except StopIteration: # code to handle empty else: for item etc etc because you don't want to iterate over the remainder if it has already stopped yielding! :-) > > The alternative is a flag variable and test > > > first = True > > for for item in iterable: > > ? ?if first: > > ? ? ?first = False > > ? ?else: > > ? ? ?f(item) > > > This takes two more lines and does an unnecessary test for every line > > after the first. ?But this approach might be useful if, for instance, > > you needed to skip every other line (put 'first = True' after f(item)). > > and change its name from 'first' to something more meaningful ;-) > > Cheers, > John From vinay_sajip at yahoo.co.uk Mon Aug 25 19:57:57 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Mon, 25 Aug 2008 16:57:57 -0700 (PDT) Subject: Why do all my loggers start auto-disabled? References: <13922a38-da45-4608-9bab-2bc153a07eae@k7g2000hsd.googlegroups.com> Message-ID: Calling fileConfig() disables any loggers existing at the time of the call. Make sure you call fileConfig() before instantiating any loggers; after that you can instantiate as many as you like, and they will all be enabled. Make sure you don't call fileConfig() again, as in that call all loggers which are not named in the configuration will be disabled. The reason why fileConfig() disables existing loggers is that it was designed as a one-off configuration (which completely replaces any existing configuration with that specified in the config file) - not as an incremental configurator. Best regards, Vinay Sajip From bearophileHUGS at lycos.com Fri Aug 8 15:31:03 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 8 Aug 2008 12:31:03 -0700 (PDT) Subject: Psycho question References: Message-ID: <476017db-4872-4cf5-a1cc-b3fc81ecaaf0@f36g2000hsa.googlegroups.com> John Krukoff: > One possibility for the performance difference, is that as I understand > it the psyco developer has moved on to working on pypy, and probably > isn't interested in keeping psyco updated and optimized for new python > syntax. > Somebody correct me if I'm wrong, but last I heard there's no > expectation of a python 3.0 compatible version of psyco, either. But for me on the short term Python 3 is probably more important than pypy, and I'd like to keep using Psyco... Bye, bearophile From cjw at ncf.ca Sat Aug 9 08:47:35 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 09 Aug 2008 08:47:35 -0400 Subject: Why is ::= used as assignment operator in doc statements? In-Reply-To: <8763qa4n03.fsf@benfinney.id.au> References: <8763qa4n03.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > schaffe at gmail.com writes: > >> Why is statments expressed with ::= as the assigning operator? >> like: http://docs.python.org/ref/grammar.txt > > That page is part of the language reference. It shows, not Python > code, but a description of part of the Python grammar. See ??1.2 > . > Of historic interest is Extended Bachus-Naur Normal Form (EBNF): http://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form Colin W. From deets at nospam.web.de Mon Aug 18 04:52:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 18 Aug 2008 10:52:02 +0200 Subject: Bizarre method keyword-arg bug. In-Reply-To: References: Message-ID: <6gsrhiFh98kpU1@mid.uni-berlin.de> Jasper schrieb: > I'm stumped. I'm calling a method that has keyword args, but not > setting them, and yet one of them starts off with data?! > > The class definition begins like so: > > class BattleIntentionAction( BattleAction ): > def __init__( self, factionName, location, tactic='hold', > targetFacName='', terrainArgs=[], garrisonIds=[] ): > self.terrainArgs = terrainArgs > print terrainArgs > > The constructor is called somewhere else, like so: > act = BattleIntentionAction( facName, self.location ) > > > During this object's construction, terrainArgs is set to a list with > values corresponding to a previously created BattleIntentionAction! > Even more bizarre, the terrainArgs param is a testing formality, and > doesn't actually get used anywhere in my code -- the corresponding > attribute is always modified after object creation. Furthermore, this > doesn't happen with the other keyword args... > > Obviously, I'm glossing over a ton of code here, but I'm having a > tough time isolating this problem, as it seems to be very dependent on > events leading up to it. It feels like the sort of memory stomping > bug I remember seeing from days of yore when I hacked C++. :-( > > > I frankly don't understand how "terrainArgs" can have a value if > nothing is passed for it on the calling invocation, short of some > obscure compiler bug (this is Python 2.4.3). Am I being naive? Is > there some way I could be bringing this about myself? > > I can easily work around this weirdness by having the caller set > terrainArgs explicitly, but I can't shake the sensation that this > "fix" just masks some deeper flaw in my code. > This is a FAQ: http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm Diez From castironpi at gmail.com Wed Aug 6 13:04:51 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 6 Aug 2008 10:04:51 -0700 (PDT) Subject: Limits of Metaprogramming References: <0c56829a-7ad2-4ff2-b225-7981538e7c7a@j22g2000hsf.googlegroups.com> <07c3d5f8-563c-43bc-8772-5eb60de52c82@8g2000hse.googlegroups.com> <95cebacd-6221-478f-81ae-1040b1711b40@k13g2000hse.googlegroups.com> Message-ID: <5306b80e-81ff-43a5-a472-4f9f05764e4a@e39g2000hsf.googlegroups.com> On Aug 6, 7:24?am, Wilson wrote: > On Aug 4, 9:23?pm, castironpi wrote: > > > > > On Aug 4, 1:57?pm, Wilson wrote: > > > > On Aug 4, 6:49?pm, castironpi wrote: > > > > > Two, if all your methods will have uniform signatures and closures, > > > > you can store class methods as only their co_code objects: > > > > > >>> C.g.im_func.func_code.co_code > > > > > 'd\x00\x00S' > > > > > And fabricate them dynamically into full live types as needed. > > > > Thanks for your comments and advice. This second option intrigues me; > > > could you elaborate further, I don't follow you... > > > > Thanks Paul > > > Depending on the complexity of the functions, a code string could be > > all you need to store to determine (redetermine) a function's > > behavior. ?For something moderately simple, > > > def trans1( self, prev, trans ): > > ? ? ? ? if prev== 0 and trans== 'a': > > ? ? ? ? ? ? ? ? return 1 > > ? ? ? ? if prev== 1 and trans== 'b': > > ? ? ? ? ? ? ? ? return 0 > > ? ? ? ? return prev > > > I found you need to store code.co_nlocals, code.co_code, and > > code.co_consts, to distinguish from a blank stub. ?With extra > > variables, I needed code.co_names and code.co_varnames too. ?To > > recreate a code object completely, you need 12 variables (14 to > > include closures), some of which are composite objects and would need > > to be pickled to be stored. > > Still don't really understand this so I'm going to admit defeat. > Thanks all for your advice... Very much appreciated! I was describing an alternative to storing functions in a way that wasn't in serial in plain text. It was off-topic from state-machine transitions. Can you start with this? # state, input, next state transitions= [ ( 0, 'a', 1 ), ( 1, 'a', 2 ), ( 2, 'a', 0 ), ( 0, 'b', 0 ), ( 1, 'b', 0 ), ( 2, 'b', 2 ) ] What further? From anartz at anartz.cjb.net Mon Aug 11 11:30:06 2008 From: anartz at anartz.cjb.net (anartz at anartz.cjb.net) Date: Mon, 11 Aug 2008 09:30:06 -0600 Subject: =?UTF-8?B?UmU6IGR5bmFtaWNhbGx5IGNyZWF0aW5nIGh0bWwgY29kZSB3aXRoIHB5dGhvbi4uLg==?= In-Reply-To: <200808111315.m7BDFjqs045647@cjb.net> References: <200808111315.m7BDFjqs045647@cjb.net> Message-ID: <200808111530.m7BFUBbS047579@cjb.net> Sorry, my fault... I am trying to build a web application for data analysis. Basically some data will be read from a database and passed to a python script (myLibs.py) to build an image as follows. [CODE] f=urllib.urlopen("http://localhost/path2Libs/myLibs.py",urllib.urlencode(TheData)) print "Content-type: image/png\n" print f.read() f.close() [/CODE] This section behaves as expected, and I can see the chart on the web-page. Now, I would like to add some text and possibly more charts (generated in the same way) to my web-page. This is what I need help with. I tried to add some html code to the f variable (file-type variable) before and after the plot generated (see first post). When I load the page in a browser, I get a blank page, not even the chart (that I used to get) appears any more. There is no error messages in the server's error log, and when I run it as a python script I get the following output: Content-type: image/png\n My question: How can I use python to dynamically add descriptive comments (text), and possibly more charts to the web-page? Hope this is more explanatory. Thanks Anartz at anartz.cjb.net wrote : > Hi, > > how can I combine some dynamically generated html code (using python) with the output of a urllib.openurl() call? > > I have tried to use the StringIO() class with .write functions, but it did not work. Below is the code that does not work. > > [CODE] > f=StringIO.StringIO() > f.write('data analysis') > f.write(urllib.urlopen("http://localhost/path2Libs/myLibs.py", urllib.urlencode(TheData))) > f.write("") > > print "Content-type: text/html\n" > print f.read() > f.close() > [/CODE] > > What is wrong with this approach/code? Is there an easier way of doing it? > > Thanks. > > > > -- > http://mail.python.org/mailman/listinfo/python-list From dudeja.rajat at gmail.com Thu Aug 21 04:07:45 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Thu, 21 Aug 2008 09:07:45 +0100 Subject: Tkinter/WindowsXP - how to use checkbutton to toggle a label in GUI? Message-ID: Hi, I've a checkbutton in my GUI application which I want to work as: 1. it should be un-ticked by default, 2. should display a label in Gui, by default, 3. when user ticks the check button this should the above label goes off the screen and not longer is displayed. Please suggest how could I do this: my code for the check button and label is : #Check button varTestAll = IntVar() self.cbTestAll = Checkbutton(master, text="Test All", variable=varTestAll ) self.cbTestAll.grid(row = 12, column = 1, sticky = W, pady = 30, padx = 30) #Label - Version under Test self.lblVersionUnderTest = Label(master, \ text = "v2.1.5.0") self.lblVersionUnderTest.grid(row = 15, \ column = 2, \ sticky = W, \ padx = 30) Please suggest. Thanks, Rajat From deets at nospam.web.de Sun Aug 10 07:24:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 10 Aug 2008 13:24:53 +0200 Subject: some kind of trace facility ? In-Reply-To: References: Message-ID: <6g81g6Febc52U1@mid.uni-berlin.de> Stef Mientki schrieb: > hello, > > I want to investigate on a regular base the flow of my Python (most of > them using wxPython) programs. > So I want to have some log facilty, that logs things like > - every time a function / method is called > - the time spent in that function / method (or even better start / > finish time) > - in case the function / method has some predefined variables, the > values of these variables > - the caller > > As an extra condition, I'm only interested in my own program modules > (located in a specific subdirectory). > > Is there a module available that can perform such a task ? > Any hints to get started ? THere is the module profile and the sys.trace-hook. Diez From greg at cosc.canterbury.ac.nz Wed Aug 27 05:48:59 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 27 Aug 2008 21:48:59 +1200 Subject: ANN: Pyrex 0.9.8.5 Message-ID: Pyrex 0.9.8.5 is now available: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ Various minor bug fixes and improvements. What is Pyrex? -------------- Pyrex is a language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. From tarundevnani at gmail.com Tue Aug 19 01:58:43 2008 From: tarundevnani at gmail.com (tarun) Date: Tue, 19 Aug 2008 11:28:43 +0530 Subject: Python Query: Related to locking a resource in a multithreaded environment Message-ID: Hello All, I've a configuration.ini file. This particular can be accessed by several threads of my application. Each thread can read/write configuration parameters from/to the configuration.ini file. I am using threading (Rlock) to lock the resource (configuration.ini file) while accessing it from any thread. I use the file available at http://www.voidspace.org.uk/python/configobj.html for read/write. I did the following in one of my files: import threading class Synchronization: def __init__(self): self.mutex = threading.RLock() Now this I can create instances of the class Synchronization and use acquire/release to work on the shared resource. But every thread would need to import this class and hence each thread would create a separate instance of the class. This means several lock variables. But I think we need a global lock flag that is accessible across all the threads. How do i do this? Please let me know ASAP. Thanks In Advance, Tarun -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Aug 28 12:10:43 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 28 Aug 2008 18:10:43 +0200 Subject: List of modules available for import inside Python? In-Reply-To: <0f716a9c-8c24-4765-a8ca-381b09575d93@w7g2000hsa.googlegroups.com> References: <0f716a9c-8c24-4765-a8ca-381b09575d93@w7g2000hsa.googlegroups.com> Message-ID: pruebauno at latinmail.com wrote: >> Is there a way to view all the modules I have available for import >> from within Python? >> Like writing in the interpreter: >> import.modules >> >> Also, is there anything like Cpan for Python? > > Isn't the most obvious answer to the first question this link? depends on whether you want a list of the modules that you might be able to import, or the modules that are actually present on your system. From fredrik at pythonware.com Thu Aug 14 09:36:27 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 15:36:27 +0200 Subject: reading plist files In-Reply-To: References: Message-ID: William Purcell wrote: > This is how it cut and pasted.. > bplist00? > This is what it looks like in a text editor (emacs)... > bplist00\324^@^A^@^B^@^C^@^D^@^E^C1^@ looks like a binary file, and is definitely not XML. probably a binary property list: http://developer.apple.com/documentation/Cocoa/Conceptual/PropertyLists/Articles/SerializedPListsConcept.html From bearophileHUGS at lycos.com Sat Aug 30 10:04:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 30 Aug 2008 07:04:58 -0700 (PDT) Subject: Advice on the style to use in imports References: <3f0d61c40808300512x1dcd5061t19ad7323b7ef15e9@mail.gmail.com> Message-ID: Marco Bizzarri: > I'm just confused because PEP8 seems to suggest that the from module > import Class style is acceptable; is there a big "if you know what are > doing" before, which I'm unable to see? from somemodule import somename is often acceptable IHMO, but there are some things to consider: - you and the person that reads your code have to remember where somename comes from. So you can do it for well known names like izip or imap, but if you import lots of names from lots of modules, things may become too much complex. So often it can be better to import just the modules, and use somemodule.somename. - somemodule.somename is longer to write and to read, and if it's repeated many times it may worsen the program readability, making lines of code and expressions too much long and heavy. So you have to use your brain (this means that you may have to avoid standard solutions). Note that you can use a compromise, shortening the module name like this: import somemodule as sm Then you can use: sm.somename - somemodule.somename requires an extra lookup, so in long tight loops (if you don't use Psyco) it slows down the code. This can be solved locally, assigning a local name into a function/method (or even in their argument list, but that's a hack to be used only once in a while): localname = somemodule.somename Bye, bearophile From bearophileHUGS at lycos.com Wed Aug 13 13:35:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 13 Aug 2008 10:35:11 -0700 (PDT) Subject: Replace Several Items References: <513926b0-64fe-4fdc-bb33-bc4b8ad3ab10@a70g2000hsh.googlegroups.com> Message-ID: gjhames: > What's the better way to do it? Better is a relative term. If with better you mean "faster" (in some circumstances), then the translate method is your friend, as you can see its second argument are the chars to be removed. As first argument you can use something like: "".join(map(chr, xrange(256))) If your strings are unicode you will need something different (a dict with Null values for the key chars you want to remove). Bye, bearophile From bignose+hates-spam at benfinney.id.au Tue Aug 12 20:53:42 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 13 Aug 2008 10:53:42 +1000 Subject: Free software and video codecs References: <024fd4b4-2823-47f8-bd60-e6fd65db596a@b1g2000hsg.googlegroups.com> <4e28ce82-306d-4a53-84c1-37ac3642ee17@x41g2000hsb.googlegroups.com> <87r68wxgwn.fsf_-_@benfinney.id.au> <0125ce9e-edad-4413-b40b-67162a0c7def@r66g2000hsg.googlegroups.com> Message-ID: <87prodwx9l.fsf@benfinney.id.au> mimiyin at gmail.com writes: > Do you have a recommendation for how I can convert the quicktime and > flash movies to ogg? That would produce an inferior result, since the Quicktime and Flash movies have (I assume) already been converted to a lossy codec . To process that data again through another lossy codec will cause a poor result, similar to making a photocopy of a photocopy. Much better would be to start with the video in its non-lossy form (either uncompressed, or compressed only with some lossless codec) and use that as the source for conversion to Dirac or Theora. This is the same principle as making a photocopy from the original, rather than from another photocopy. Presumably the Quicktime and Flash videos were created from some original lossless data source. Any further encoding should be done from a source as close to the original as possible. > I've had a hard time finding conversion apps for the Mac.I'd also be > happy to turn over the original movies to anyone who can help me > convert them. I don't know anything about MacOS applications. I do know that the BBC developed the "Schroedinger" (Schr?dinger) implementation for encoding video to Dirac; you may want to see if that's available for your OS. -- \ ?I cannot conceive that anybody will require multiplications at | `\ the rate of 40,000 or even 4,000 per hour ?? ?F. H. Wales, 1936 | _o__) | Ben Finney From srikrishnamohan at gmail.com Tue Aug 19 09:27:58 2008 From: srikrishnamohan at gmail.com (km) Date: Tue, 19 Aug 2008 18:57:58 +0530 Subject: ANN: Resolver One 1.2 released In-Reply-To: <59f2f4c8-5713-4779-8bcf-e1683645bd64@a70g2000hsh.googlegroups.com> References: <59f2f4c8-5713-4779-8bcf-e1683645bd64@a70g2000hsh.googlegroups.com> Message-ID: Hi, sounds great - but disappointing to find it only available on window$. Is there any Linux release in near future ??? KM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ On Tue, Aug 19, 2008 at 6:10 PM, giles.thomas at gmail.com < giles.thomas at gmail.com> wrote: > We are proud to announce the release of Resolver One, version 1.2 - > the largest IronPython application in the world, we think, at 38,000 > lines of production code backed up by 150,000 lines of unit and > functional tests. > > Resolver One is a Rapid Application Development tool for analysing and > presenting business data, using a familiar spreadsheet interface > combined with a powerful IronPython-based scripting capability that > allows you to insert your own code directly into the recalculation > loop. > > For version 1.2, we have on big headline feature; a new function > called > RunWorkbook that allows you to "call" one spreadsheet from another, > passing in parameters and pulling out results - just like functions, > but > without having to code the function by hand. This allows you to mix > spreadsheet-based and code-based logic, using the best paradigm for > the job in hand. > > We've also added a whole bunch of usability enhancements - the full > (long!) changelist is up on our website, or you can see a screencast: > > > It's free for non-commercial use, so if you would like to take a > look, > you can download it from our website: > (registration no longer > required). > > > Best regards, > > Giles > -- > Giles Thomas > MD & CTO, Resolver Systems Ltd. > giles.tho... at resolversystems.com > +44 (0) 20 7253 6372 > > Try out Resolver One! > > 17a Clerkenwell Road, London EC1M 5RD, UK > VAT No.: GB 893 5643 79 Registered in England and Wales as company > number 5467329. > Registered address: 843 Finchley Road, London NW11 8NA, UK > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lanny at freshells.ch Wed Aug 13 19:13:14 2008 From: lanny at freshells.ch (Lanny) Date: Wed, 13 Aug 2008 16:13:14 -0700 Subject: Random Problems Message-ID: Well the othe day I was making a program to make a list of all the songs in certian directorys but I got a problem, only one of the directorys was added to the list. Heres my code: import random import os import glob songs = glob.glob('C:\Documents and Settings\Admin\My Documents\LimeWire\Saved\*.mp3') asongs = glob.glob('C:\Documents and Settings\Admin\My Documents\Downloads\*\*.mp3') songs.append(asongs) asongs = glob.glob('C:\Documents and Settings\Admin\My Documents\Downloads\*\*\*.mp3') songs.append(asongs) asongs = glob.glob('C:\Documents and Settings\Admin\My Documents\Downloads\*\*\*\*.mp3') songs.append(asongs) pick = random.choice(songs) all goes well but pick awalys is from the first directory but songs awalys includes all the files I want it to. Im baffaled. -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- From mccredie at gmail.com Thu Aug 28 18:54:58 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 28 Aug 2008 15:54:58 -0700 (PDT) Subject: Python in a Nutshell -- Book vs Web References: Message-ID: On Aug 28, 3:05?pm, "W. eWatson" wrote: > I read an Amazon of Python in a Nutshell. The first edition is supposedly > much like the web site. What web site? The second edition apparently adds > more to the book than the web site. O'Reilly seems to just read all of the available documentation and regurgitate it in book form. The "in a nutshell" series being the worst offender. Most of "Python in a Nutshell" tells you the same information that you can find at http://docs.python.org, which is probably "the web site" being referenced. Matt From mathieu.prevot at gmail.com Thu Aug 7 15:56:14 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Thu, 7 Aug 2008 21:56:14 +0200 Subject: kill thread Message-ID: <3e473cc60808071256g6b359032tb72115a2d86fad37@mail.gmail.com> Hi, I have a threading.Thread class with a "for i in range(1,50)" loop within. When it runs and I do ^C, I have the error [1] as many as loops. I would like to catch this exception (and if possible do some cleanup like in C pthreads) so the program finishes cleanly. Where and how can I do this ? in __run__ ? __init__ ? a try/except stuff ? Thanks, Mathieu [1]: ^CException in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 486, in __bootstrap_inner self.run() File "./youfetch.py", line 148, in run self.getids() File "./youfetch.py", line 145, in getids self.ids.append(self.getidsatpage(i)) File "./youfetch.py", line 138, in getidsatpage self.child = subprocess.Popen(cmd.split(),stdout=subprocess.PIPE) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/subprocess.py", line 594, in __init__ errread, errwrite) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/subprocess.py", line 1011, in _execute_child self.pid = os.fork() KeyboardInterrupt From Lie.1296 at gmail.com Thu Aug 28 08:52:18 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 28 Aug 2008 05:52:18 -0700 (PDT) Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> <6fe0scFaus40U1@mid.uni-berlin.de> <6bc8bc07-eab0-4303-b8a4-c9470f96038d@c65g2000hsa.googlegroups.com> <6fe1n2Faus40U3@mid.uni-berlin.de> <6ff0ifFbbpfbU1@mid.uni-berlin.de> Message-ID: On Aug 1, 6:35?am, "Diez B. Roggisch" wrote: > squishywaf... at gmail.com schrieb: > > > On Jul 31, 10:47 am, "Diez B. Roggisch" wrote: > >> I take the freedom to do so as I see fit - this is usenet... > > > Fine, then keep beating a dead horse by replying to this thread with > > things that do nobody any good. It seems like there are a lot better > > way to waste time, though. > > You mean like trying to wrap ones head around the rather simple Python C > API, not getting a callback mechanism implemented? > > For the record: I've wrapped C-libs myself, including callbacks. Been > there, done that, discovered (years later) cytpes, been there for good. > > > The Python/C API can get me back further without reliance on third- > > party libraries than ctypes. > > You don't consider your own library a third party lib? And unless you're > wrapping C++, you're opinion is as uninformed as it is wrong. > > > It also isn't subject to the quirks that > > ctypes is on platforms other than Windows (the target application runs > > on Windows, Mac, and eventually Linux once the original distributor > > has drivers for the device). I'm not even sure ctypes could load the > > lib/driver the distributor packaged. > > Oh please. I'm 98% working on linux & osx. ctypes does a great job on > these platforms. > > Regarding your objections I can only say: whatever the python runtime > can load because of the underlying ld, ctypes can load. simply because > they are the same. If *that* was the actual cause of problems, we > wouldn't even talk about callbacks here. > > > So really, I appreciate the option in ctypes, it's good stuff. But > > it's not for this project. > > Stop finding lame excuses for not wanting to ditch the work you've done > in favor of a easier solution. You like your code, you want to keep it, > you want to discover the intricasies of the Python C API? Be my guest. > > But stop embarassing yourself inventing reasons like licensing or linker > problems you don't support with any facts whatsoever. > > > Once again, the original question stands for anyone who has experience > > with the Python/C API callbacks. > > You know what? Just for the fun of it, I'll take a stab at it. > > ? It's easy: Create a "proxy-function" that matches the prototype of the > c8allback which converts the passed arguments to python values using the > C-api. Then call the registered python function using > PyObject_CallFunction. > > Convert the return-value back to C, and return it. > > Make the function get the PyObject* for the call fetch from a global > variable you set in the register-callback function, where you also > register the proxy-function for the first time, or de-register if the > passed value is None or such. > > Have fun. > > Diez Zen's lesson for today: THOU SHALT NOT MESS WITH ANY PYTHON'S SEMI-GODS, DEMI-GODS, AND PYTHON'S GOD. You're lucky Diez still want to help you with your attitude like that. May I remind you that we here helps you for free in our free time, be rude, especially to a frequent member, and you'll get what you deserve. From pavlovevidence at gmail.com Fri Aug 29 21:45:27 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 29 Aug 2008 18:45:27 -0700 (PDT) Subject: When to use try and except? References: <8a2dd955-6641-493d-b7eb-3e29c14686a5@26g2000hsk.googlegroups.com> <914fde08-5084-455f-ac68-bef7e06cc3dc@i76g2000hsf.googlegroups.com> Message-ID: <3a6cde6c-885e-470f-a7b1-0752b63e8f94@y21g2000hsf.googlegroups.com> On Aug 29, 1:56?pm, cnb wrote: > On Aug 29, 7:40?pm, Daniel wrote: > > > > > On Aug 29, 11:23?am, cnb wrote: > > > > If I get zero division error it is obv a poor solution to do try and > > > except since it can be solved with an if-clause. > > > > However if a program runs out of memory I should just let it crash > > > right? Because if not then I'd have to write exceptions everywhere to > > > prevent that right? > > > > So when would I actually use try-except? > > > > If there can be several exceptions and I just want to catch 1 or 2? > > > Like > > > try: > > > ? ? blahaba > > > except SomeError: > > > ? ? do something > > > I'm not sure whay you're trying to do, but I think catching a > > ZeroDivisionError exception is a good use of try-except. > > > I'm also not sure that I would say you just let a program crash if it > > runs out of memory. ?I would think that from the user perspective, you > > would want to check memory conditions and come up with an exception > > indicating that some memory threshold has been reached. ?When that > > exception is raised you should indicate that to the user and exit > > gracefully. > > A ZeroDivisionError is better avoided wth an if-clause, don't you > think? It is a predictable exception... Many Pythonistas would disagree with that. Anyway there are some types of errors for which catching exceptions is more robust because there's a gap between the time something is checked and the time it's used, between which the circumstances can change. For instance, the following test can be subject to sporadic failures: if os.path.exists(filename): f = open(filename) Between the call to os.path.exists and the call to open, the file could be removed by another process, which will result in an unhandled exception. Also, sometimes files fail to open for other reasons, such as permissions. For things like divide-by-zero, there's no way a local value can change between the zero test and the operation (except in uncommon situations), so it's just a matter of style which way you do it. Carl Banks From maduma at pt.lu Tue Aug 19 10:45:12 2008 From: maduma at pt.lu (maduma at pt.lu) Date: Tue, 19 Aug 2008 07:45:12 -0700 (PDT) Subject: who to call a list of method inside the class itself References: <95910272-2045-4170-ab6e-549489b12108@d77g2000hsb.googlegroups.com> Message-ID: On Aug 19, 4:33 pm, Fredrik Lundh wrote: > mad... at pt.lu wrote: > > Is the following code is ok. who to call all method. > > It is working but the call to m() without a reference to self seems > > strange > > > Thanks for your help > > > class CustomMethod: > > def method1(self): > > .... > > def method2(self): > > .... > > def method3(self): > > .... > > > def getAllMethod(self): > > return [self.method1, self.method2, self.method3] > > > def applyAll(self): > > for m in self.getAllMethod(): > > # how to call all methods ? > > # is it correct > > m() > > what happens when you run the code? > > The code it is running fine but i just wondering if it's the syntax is correct (avoid any side effect) -Stephane From brtzsnr at gmail.com Wed Aug 27 07:49:40 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Wed, 27 Aug 2008 04:49:40 -0700 (PDT) Subject: use of Queue References: Message-ID: <39824ccb-7e35-4ef4-a150-692af64c0ba5@j1g2000prb.googlegroups.com> On Aug 27, 1:06?pm, Gerhard H?ring wrote: > Alexandru Mosoi wrote: > > how is Queue intended to be used? I found the following code in python > > manual, but I don't understand how to stop consumers after all items > > have been produced. I tried different approaches but all of them > > seemed incorrect (race, deadlock or duplicating queue functionality) > > > ? ? def worker(): > > ? ? ? ? while True: > > ? ? ? ? ? ? item = q.get() > > ? ? ? ? ? ? ? ?if item is None: > ? ? ? ? ? ? ? ? ? ?break > > > ? ? ? ? ? ? do_work(item) > > ? ? ? ? ? ? q.task_done() > > > ? ? q = Queue() > > ? ? for i in range(num_worker_threads): > > ? ? ? ? ?t = Thread(target=worker) > > ? ? ? ? ?t.setDaemon(True) > > ? ? ? ? ?t.start() > > > ? ? for item in source(): > > ? ? ? ? q.put(item) > > # stop all consumers > for i in range(num_worker_threads): > ? ? ?q.put(None) > > > > > ? ? q.join() ? ? ? # block until all tasks are done > > This is how I do it. > > -- Gerhard Your solution works assuming that you know how many consumer threads you have :). I don't :). More than that, it's not correct if you have more than one producer :). Having a sentinel was my very first idea, but as you see... it's a race condition (there are cases in which not all items are processed). From ewertman at gmail.com Sat Aug 30 10:57:50 2008 From: ewertman at gmail.com (Eric Wertman) Date: Sat, 30 Aug 2008 10:57:50 -0400 Subject: Writing to ms excel In-Reply-To: References: Message-ID: <92da89760808300757n5f4f05dpad8c16e8a61bd36e@mail.gmail.com> > I'm trying to find a way to write data to excel cells (or to be more > specific to an .xls file), let's say for the sake of argument, data > readen from a file (although it will be calculated in the process). > I've been searching, but couldn't find any examples which allows that. The answer will depend on your base os.. if you are on windows there will be some options using the COM interfaces I bet.. but I don't know anything about them. If you are on a unix based os, your choices are limited. If you can, I would just write to a csv file and open it with Excel. If you have to interface with an exsisting excel file, you can try http://pypi.python.org/pypi/xlrd , but it may not support writing xls files, still. From gagsl-py2 at yahoo.com.ar Sun Aug 24 06:32:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 24 Aug 2008 07:32:47 -0300 Subject: EOF References: Message-ID: En Fri, 22 Aug 2008 16:53:58 -0300, Wojtek Walczak escribi?: > On Fri, 22 Aug 2008 22:18:37 +0530, Anjanesh Lekshminarayanan wrote: > >> Im trying to download a file from a server. But how do I detect EOF ? > > Whenever read() method returns empty string/list. > > >> while f1: # When to stop ? > retval = f1.read() > if not retval: > break > f2.write(retval) Those read() should be read(size) - read() tries to get the whole contents in memory. Anyway, shutil.copyfileobj already implements that logic. -- Gabriel Genellina From http Fri Aug 29 02:42:29 2008 From: http (Paul Rubin) Date: 28 Aug 2008 23:42:29 -0700 Subject: Lining Up and PaddingTwo Similar Lists References: <4mKtk.11732$vn7.11459@flpi147.ffdc.sbc.com> Message-ID: <7x4p54fhka.fsf@ruckus.brouhaha.com> "W. eWatson" writes: > [a.dat, c.dat, g.dat, k.dat, p.dat] > [a.txt, b.txt, g.txt, k.txt r.txt, w.txt] > > What I need is to pair up items with the same prefix and use "None", > or some marker, to indicate the absence of the opposite item. This is functionally influenced but should be straightforward: dat = ['a.dat', 'c.dat', 'g.dat', 'k.dat', 'p.dat'] txt = ['a.txt', 'b.txt', 'g.txt', 'k.txt', 'r.txt', 'w.txt'] # just get the portion of the filename before the first period def prefix(filename): return filename[:filename.find('.')] # make a dictionary mapping prefixes to filenames def make_dict(plist): return dict((prefix(a),a) for a in plist) pdat = make_dict(dat) ptxt = make_dict(txt) # get a list of all the prefixes, use "set" to remove # duplicates, then sort the result and look up each prefix. for p in sorted(set(pdat.keys() + ptxt.keys())): print pdat.get(p), ptxt.get(p) From ptmcg at austin.rr.com Wed Aug 6 19:24:03 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 6 Aug 2008 16:24:03 -0700 (PDT) Subject: Parsing of a file References: Message-ID: On Aug 6, 3:14?pm, "Shawn Milochik" wrote: > Regular expressions will do the trick nicely. > Or just use str.split, and create dicts using dict(list_of_tuples) constructor. This code creates a single dict for the input lines, keyed by id. Each value contains elements labeled 'id', 'ra', and 'mjd'. -- Paul data = """\ Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames 5 Set 1 Field f31448: Ra=20:24:58.13 Dec=+79:39:43.9 MJD=53370.06811620 Frames 5 Set 2 Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames 5 Set 3 Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames 5 Set 4 Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames 5 Set 5 Field f30560: Ra=20:27:01.82 Dec=+74:47:50.3 MJD=53370.06860400 Frames 5 Set 6 Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames 5 Set 7 Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames 5 Set 8 Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames 5 Set 9 Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames Set 10 """.splitlines() d = dict( (rec.split()[1][:-1], dict([('id',rec.split()[1][:-1])] + [map(str.lower,f.split('=')) for f in rec.split()[2:5]] ) ) for rec in data ) print d.keys() for id in d.keys(): print d[id].items() From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 13 03:13:33 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 13 Aug 2008 09:13:33 +0200 Subject: Python web framework choice In-Reply-To: References: Message-ID: <48a28992$0$19706$426a74cc@news.free.fr> david.lyon at preisshare.net a ?crit : > Quoting Mahdi : > >> I need to develop a medium-sized database web application for my >> company. Given that: >> I don't know much about building web UI(s) but i have fair knowledge >> about HTML & My schedule is tight. >> >> a recommendation is v v v appreciated. > > I'm in the same boat.... a few weeks in..... > > I've found that most of the python frameworks are based on the python > cherrypy server. "most" ? Turbogears < 2.x set aside (TG2 runs on top of pylons), I didn't heard of much cherrypy-based frameworks (except possibly for home-grown unpublished ones). > Thats a good place to work out how the webserver part > of the non-zope systems work. ie django etc Django was initially designed to run on mod_python, then added support for fcgi and wsgi IIRC. > So that is the webserver part.... > > then you need to build your webpages.... > > I have found Cheetah.... which is pretty powerful... that is a > templating system to build the actual pages from the database content... from whatever content... > that works nicely... There are quite a couple other templating systems. One could mention Mako, Genshi, TAL, Breve, Jinja, etc... > obviously django and pylons wrap all these basics into a 'product'... Django has it's own templating system (and it's own ORM)[1]. Pylons (which is a 100% wsgi-based framework) default to Mako (templating) and SQLAlchemy (ORM), but these are only defaults [1] you can of course use other templating systems and ORMs with it, but then you'd loose most of what makes Django interesting... From tjreedy at udel.edu Fri Aug 8 17:08:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 08 Aug 2008 17:08:57 -0400 Subject: small issue with Idle In-Reply-To: References: <2c192ba3-bc94-4f55-9d59-0fe14b8069a0@z6g2000pre.googlegroups.com> Message-ID: Mike Driscoll wrote: > There's a free version of Wing IDE that has an IDLE-like interface > that doesn't have this issue...or you could just use the command line > version of IDLE. What are you referring to? From deets at nospam.web.de Tue Aug 26 11:56:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Aug 2008 17:56:13 +0200 Subject: atomic increment References: <6297cf93-5eec-4bf3-9104-0605a82f7186@p10g2000prf.googlegroups.com> Message-ID: <6hinduFmfmsrU1@mid.uni-berlin.de> Alexandru Mosoi wrote: > how can i do an atomic read+increment? something like > > with lock: > old = atomic_int > atomic_int += 1 > > but in one operation As above - the lock (under the assumption that it is actually a threading.Lock) will ensure that. Diez From gagsl-py2 at yahoo.com.ar Fri Aug 22 12:59:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 22 Aug 2008 13:59:41 -0300 Subject: urllib2 HTTPBasicAuthHandler and resumingbroken downloads References: <63d6d10e-c023-4ec6-9f11-0687d7ae8254@k37g2000hsf.googlegroups.com> Message-ID: En Fri, 22 Aug 2008 08:55:57 -0300, Brendan escribi?: > On Aug 21, 3:57?pm, "Gabriel Genellina" > wrote: >> En Thu, 21 Aug 2008 15:37:41 -0300, Brendan >> ? >> escribi : >> >> > Is there any way to resume an https file download using urllib2 and an >> > HTTPBasicAuthHandler? >> >> You should provide the Range header (and probably If-Range too) in the ? >> request.http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 > > Ug. Why does everything in Python boil down to reading rfcs? It really > slows us non computer science types down. I'll probably spend a day on > this instead of an hour. I did search the web but had no luck finding > an example, so I posted here as a last resort. The easy way is to use wget... If you want a Python example, go to the Python cookbook: http://code.activestate.com/recipes/langs/python/ enter "resume download" in the search box, and the very first recipe shows how to use the Range header. -- Gabriel Genellina From grflanagan at gmail.com Mon Aug 18 04:11:18 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Mon, 18 Aug 2008 01:11:18 -0700 (PDT) Subject: online tutorials? References: <6013d717-7c4b-4f34-8f58-d9a1e7387f5c@k37g2000hsf.googlegroups.com> Message-ID: On Aug 18, 12:53?am, Gits wrote: > I want to learn how to program in python and would like to know if you > guys know of any free online tutorials. ?Or is it too complicated to > learn from a site or books? Some texts and examples here: http://thehazeltree.org/ hth G. From gustavo at grahal.net Tue Aug 12 17:18:48 2008 From: gustavo at grahal.net (Gustavo Rahal) Date: Tue, 12 Aug 2008 21:18:48 +0000 (UTC) Subject: xmlrpc client through proxy to https server Message-ID: Hi I'm trying to build a xmlrpc client that uses a proxy to connect to a xmlrpc server in https. I've googled and came up with a code snippet that doesn't actually work. What is missing? class ProxiedTransport(xmlrpclib.Transport): def set_proxy(self, proxy): self.proxy = proxy def make_connection(self, host): self.realhost = host # i've also tried httplib.HTTPS, in this case I get # "socket.sslerror: (1, 'error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol')" h = httplib.HTTP(self.proxy) #trivial setup for ssl socket # proxy_connect='CONNECT %s:%s HTTP/1.1\r\n'%('ftp3.linux.ibm.com', '443') # user_agent='User-Agent: python\r\n' # proxy_pieces=proxy_connect+user_agent+'\r\n' # proxy=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # proxy.connect(('9.47.67.150', 3128)) # proxy.sendall(proxy_pieces) # response=proxy.recv(8192) # ssl = socket.ssl(proxy, None, None) # sock = httplib.FakeSocket(proxy, ssl) # h.sock = sock return h def send_request(self, connection, handler, request_body): connection.putrequest("POST", 'https://%s%s' % (self.realhost, handler)) def send_host(self, connection, host): connection.putheader('Host', self.realhost) p = ProxiedTransport() p.set_proxy('9.47.67.150:3128') server = xmlrpclib.Server('https://ftp3.linux.ibm.com/rpc/index.php', transport=p) print server.user.ingroup("username", "group") ------------------- The Result: xmlrpclib.ProtocolError: The method i'm calling is "implemented". If I try straight xmlrpc connection through a machine that is not behind a firewall things work fine. Appreciate help Thanks Gustavo From pw at panix.com Fri Aug 22 21:52:27 2008 From: pw at panix.com (Paul Wallich) Date: Fri, 22 Aug 2008 21:52:27 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: Martin Gregorie wrote: > On Fri, 22 Aug 2008 22:56:09 +0000, sln wrote: > >> On Thu, 21 Aug 2008 09:11:48 -0500, rpw3 at rpw3.org (Rob Warnock) wrote: >> >>> sln at netherlands.com> wrote: >>> *IS* raw machine code, *NOT* assembler!! >> [snip] >> >> I don't see the distinction. >> Just dissasemble it and find out. >> > There's a 1:1 relationship between machine code and assembler. > Unless its a macro-assembler, of course! > >> Each op is a routine in microcode. >> That is machine code. Those op routines use machine cycles. >> > Not necessarily. An awful lot of CPU cycles were used before microcode > was introduced. Mainframes and minis designed before about 1970 didn't > use or need it and I'm pretty sure that there was no microcode in the > original 8/16 bit microprocessors either (6800, 6809, 6502, 8080, 8086, > Z80 and friends). > > The number of clock cycles per instruction isn't a guide either. The only > processors I know that got close to 1 cycle/instruction were all RISC, > all used large lumps of microcode and were heavily pipelined. > > By contrast the ICL 1900 series (3rd generation mainframe, no microcode, > no pipeline, 24 bit word) averaged 3 clock cycles per instruction. > Motorola 6800 and 6809 (no microcode or pipelines either, 1 byte fetch) > average 4 - 5 cycles/instruction. One problem with this discussion is that the term "microcode" isn't really well-defined. There's the vertical kind, the horizontal kind, with and without internal control-flow constructs, and then there are various levels of visibility to the user -- see e.g. the pdp-8 manual, where "microcoding" is used to mean piling the bits for a bunch of instructions together in the same memory location, which works fine as long as the instructions in question don't use conflicting sets of bits. paul From fredrik at pythonware.com Wed Aug 13 18:39:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Aug 2008 00:39:37 +0200 Subject: Can't use DB name with dashes using pymssql ??? In-Reply-To: <65c3648d0808131530w29728a78ib646dde89481e656@mail.gmail.com> References: <65c3648d0808131354x333a7e0cica29217a26f4ce42@mail.gmail.com> <65c3648d0808131530w29728a78ib646dde89481e656@mail.gmail.com> Message-ID: Samuel Morhaim wrote: > I believe there is a bug in Python.. _mssql ... I am not too familiar > with Python yet, but after adding several breakpoints and watching the > variable, the last step of pymssql.py is > > # open the connection > con = _mssql.connect(dbhost, dbuser, dbpasswd) > > > con.select_db(dbbase) > At this point the contents of dbbase is "Gcare4UI-B6_3_dev" (no > quotes)... however, the immediate error is that > "Gcare4UI" does not exist. reading the documentation might help: http://pymssql.sourceforge.net/troubleshooting.html#dbid From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 28 09:49:42 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 28 Aug 2008 15:49:42 +0200 Subject: PYTHONPATH and modules In-Reply-To: <954d5e6f-f809-483f-ab6c-4d5c14f8c809@m36g2000hse.googlegroups.com> References: <954d5e6f-f809-483f-ab6c-4d5c14f8c809@m36g2000hse.googlegroups.com> Message-ID: <48b6acba$0$18567$426a74cc@news.free.fr> Juan a ?crit : > Hi > > I am programming a little script that makes use of a module I > developed before. The utils are inside the directory src of the > directory utils, and the package is nutum.utils. The script is in the > directory src inside the directory sysinfo, and the package is > nutum.sysinfo. Won't work, cf below. > Well, if not clear, this is the list of files: > > ls -lR ~/workspace (imaginary output): > > utils/src/nutum/__init__.py > utils/src/nutum/utils/__init__.py > utils/src/nutum/utils/general.py > utils/src/nutum/utils/elapsed_time.py > utils/src/nutum/utils/execute_command.py > utils/src/nutum/utils/size_units.py > > sysinfo/src/nutum/__init__.py > sysinfo/src/nutum/sysinfo/__init__.py > sysinfo/src/nutum/sysinfo/sysinfo.py > sysinfo/src/nutum/sysinfo/modules/__init__.py > sysinfo/src/nutum/sysinfo/modules/base_module.py > sysinfo/src/nutum/sysinfo/modules/os.py A Python package is a filesystem directory with an __init__.py file in it. In your above layout, you have two *distinct, unrelated* packages both named nutum. The first found in sys.path will shadow the second. You either need to rename one, or "refactor" your layout to have utils and sysinfo under the same root package, ie: workspace/src/nutum/__init__.py workspace/src/nutum/utils/__init__.py workspace/src/nutum/utils/general.py workspace/src/nutum/utils/elapsed_time.py workspace/src/nutum/utils/execute_command.py workspace/src/nutum/utils/size_units.py workspace/src/nutum/sysinfo/__init__.py workspace/src/nutum/sysinfo/sysinfo.py workspace/src/nutum/sysinfo/modules/__init__.py workspace/src/nutum/sysinfo/modules/base_module.py workspace/src/nutum/sysinfo/modules/os.py HTH From goldnery at gmail.com Fri Aug 22 09:09:10 2008 From: goldnery at gmail.com (Gandalf) Date: Fri, 22 Aug 2008 06:09:10 -0700 (PDT) Subject: gridSizer inside a panel element Message-ID: <8d7dd1ee-596c-4810-b03c-97f3a00d2c7b@56g2000hsm.googlegroups.com> why when I try to insert gridSizer to a panel which already inside another panel the gridSizer doesn't work? this is the code: panel3= wx.Panel(self, -1, (0, 60), size=(400, 240) , style=wx.SIMPLE_BORDER); panel3.SetBackgroundColour('#dadadb') panel = wx.Panel(panel3, wx.ID_ANY, style=wx.SIMPLE_BORDER, size=(150, 60)) panel.SetBackgroundColour("#fffFFF") bmp = wx.ArtProvider.GetBitmap(wx.ART_TIP, wx.ART_OTHER, (16, 16)) inputIco = wx.StaticBitmap(panel, wx.ID_ANY, bmp) labelThree= wx.StaticText(panel, wx.ID_ANY, 'Hello') label2=wx.StaticText(panel, wx.ID_ANY, 'Pease, Quite, Hello, Shalom') topSizer = wx.BoxSizer(wx.VERTICAL) gridSizer = wx.GridSizer(rows=2, cols=1, hgap=5, vgap=5) input = wx.BoxSizer(wx.HORIZONTAL) output = wx.BoxSizer(wx.HORIZONTAL) input.Add((20,20), 1, wx.EXPAND) # this is a spacer input.Add(inputIco, 0, wx.ALL, 5) input.Add(labelThree, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5) output.Add((20,20), 1, wx.EXPAND) # this is a spacer output.Add(label2, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5) gridSizer.Add(input, 0, wx.ALIGN_LEFT) gridSizer.Add(output, 0, wx.ALIGN_RIGHT) topSizer.Add(gridSizer, 0, wx.ALL|wx.EXPAND, 5) panel.SetSizer(topSizer) From aahz at pythoncraft.com Sun Aug 10 20:06:46 2008 From: aahz at pythoncraft.com (Aahz) Date: 10 Aug 2008 17:06:46 -0700 Subject: ANN: Chandler 1.0 References: Message-ID: In article , Heikki Toivonen wrote: > >The Chandler Project is pleased to announce the release of Chandler >Desktop 1.0! Congrats! It's been a long, strange road.... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From grante at visi.com Sun Aug 3 18:57:10 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 03 Aug 2008 17:57:10 -0500 Subject: Decimals not equalling themselves (e.g. 0.2 = 0.2000000001) References: Message-ID: On 2008-08-03, Larry Bates wrote: >> However, it appears that when n in 1/n is a power of two, the decimal >> does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2 >> and not 0.20000000000000001? >> >> This discrepancy is very minor, but it makes the whole n-th root >> calculator inaccurate. :\ > > What are they teaching in computer science classes these days? When I was an undergrad the only courses that dealt with FP issues were classes on numerical analysis. I don't even know if numerical analysis classes were required for CS majors. I think most of us in that class were engineering majors. -- Grant Edwards grante Yow! I wish I was a at sex-starved manicurist visi.com found dead in the Bronx!! From Scott.Daniels at Acm.Org Sat Aug 23 09:55:07 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 23 Aug 2008 06:55:07 -0700 Subject: Using Tkinter In-Reply-To: <78a600a0-1285-4659-92b1-ffca44410750@o40g2000prn.googlegroups.com> References: <78a600a0-1285-4659-92b1-ffca44410750@o40g2000prn.googlegroups.com> Message-ID: J-Burns wrote: > Hello. Im a bit new to using Tkinter and im not a real pro in > programming itself... :P. Need some help here. OK, looks like you are getting direct answers, but I thought I'd mention an easy way to experiment with Tkinter programming. If you start Idle with the "-n" switch (*), then anything you do shares the same "mainloop" as Idle, and your window manipulation is "live". This means, that immediately after typing in: >>> import Tkinter >>> f = Tkinter.Frame() You will see the frame f show up. You can experiment directly with watching the effects of calls that you make in the interactive interpretter. (*) Easy way to do this: On some systems, associate a button with "pythonw -m idlelib.idle -n". On a Windows system with an Idle shortcut/button/icon already: Copy the shortcut/button/icon Right-click the shortcut and select the "properties" menu. On the "General" tab of the Properties window: Give the shortcut a nicer name (I use Idle25-n for mine). On the "Shortcut" tab of the properties window, add a space and a -n to the target line. Click OK, and try out your new button. --Scott David Daniels Scott.Daniels at Acm.Org From hdante at gmail.com Wed Aug 6 19:00:05 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Wed, 6 Aug 2008 16:00:05 -0700 (PDT) Subject: Parsing of a file References: Message-ID: On Aug 6, 3:55?pm, Tommy Grav wrote: > I have a file with the format > > Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames ? > 5 Set 1 > Field f31448: Ra=20:24:58.13 Dec=+79:39:43.9 MJD=53370.06811620 Frames ? > 5 Set 2 > Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames ? > 5 Set 3 > Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames ? > 5 Set 4 > Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames ? > 5 Set 5 > Field f30560: Ra=20:27:01.82 Dec=+74:47:50.3 MJD=53370.06860400 Frames ? > 5 Set 6 > Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames ? > 5 Set 7 > Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames ? > 5 Set 8 > Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames ? > 5 Set 9 > Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames ? > 5 Set 10 > > I would like to parse this file by extracting the field id, ra, dec ? > and mjd for each line. It is > not, however, certain that the width of each value of the field id, ? > ra, dec or mjd is the same > in each line. Is there a way to do this such that even if there was a ? > line where Ra=****** and > MJD=******** was swapped it would be parsed correctly? > > Cheers > ? ?Tommy Did you consider changing the file format in the first place, so that you don't have to do any contortions to parse it ? Anyway, here is a solution with regular expressions (I'm a beginner with re's in python, so, please correct it if wrong and suggest better solutions): import re s = """Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames 5 Set 1 Field f31448: Ra=20:24:58.13 Dec=+79:39:43.9 MJD=53370.06811620 Frames 5 Set 2 Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames 5 Set 3 Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames 5 Set 4 Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames 5 Set 5 Field f30560: Dec=+74:47:50.3 Ra=20:27:01.82 MJD=53370.06860400 Frames 5 Set 6 Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames 5 Set 7 Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames 5 Set 8 Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames 5 Set 9 Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames 5 Set 10""" s = s.split('\n') r = re.compile(r'Field (\S+): (?:(?:Ra=(\S+) Dec=(\S+))|(?:Dec=(\S+) Ra=(\S+))) MJD=(\S+)') for i in s: match = r.findall(i) field = match[0][0] Ra = match[0][1] or match[0][4] Dec = match[0][2] or match[0][3] MJD = match[0][5] print field, Ra, Dec, MJD From p at ulmcnett.com Thu Aug 28 19:28:03 2008 From: p at ulmcnett.com (Paul McNett) Date: Thu, 28 Aug 2008 16:28:03 -0700 Subject: [1,2,3] exactly same as [1,2,3,] ? In-Reply-To: References: Message-ID: <48B73483.1020000@ulmcnett.com> mh at pixar.com wrote: > x=[1,2,3] > and > x=[1,2,3,] > > are exactly the same, right? When confronted with this type of question, I ask the interpreter: {{{ mac:~ pmcnett$ python Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> [1,2,3] == [1,2,3,] True }}} Paul From flarefight at googlemail.com Wed Aug 27 12:51:29 2008 From: flarefight at googlemail.com (ff) Date: Wed, 27 Aug 2008 09:51:29 -0700 (PDT) Subject: Custom PyQt4 TableWidget References: Message-ID: <00ef9f45-0b92-481d-b3a8-8bff98b3c0ed@m45g2000hsb.googlegroups.com> > > setSelectionMode()? > > Phil Ive tried that, it does half the job, it stops you selecting more than one item in the table at any one time but it doesnt stop the top-left 'thing', thanks though, From a.schmolck at gmail.com Fri Aug 8 12:37:01 2008 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Fri, 08 Aug 2008 17:37:01 +0100 Subject: python-mode is missing the class browser References: <6361fac8-3bfb-4d7e-b13b-84261ebeea10@b1g2000hsg.googlegroups.com> Message-ID: "Adam Jenkins" writes: > On Fri, Aug 8, 2008 at 7:32 AM, Michele Simionato > wrote: >> On Aug 7, 5:55 pm, Alexander Schmolck wrote: > ... >> >> I have solved by using ipython.el which was already installed. For the >> sake of >> future googlers using Ubuntu 8.04, emacs and ipython, it is enough if >> you just add >> >> (setq ipython-command "/usr/bin/ipython") >> (require 'ipython) >> >> to your .emacs. It is nice since I get the occasion to try ipython.el >> which I am >> sure I will like ;) > > So, I'm looking at the .el, but I'm not sure. What else does > ipython.el give you than just the ipython shell? What else could you possibly want? :) Seriously, ipython.el is a simple kludge whose only function is to make python-mode work with ipython (rather than python[*]). Despite this certain primitiveness (c.f. slime), Emacs+ipython makes quite a powerful development environment, significantly more so than ipython alone or emacs + python. Most importantly thre is: 1. debug. Try it: write some code that will throw an unhandled exception, and just type ``debug``. Type ``u`` and ``d`` to go up and down the stack frame, and see the right file and line pop up in emacs. I really find that combined with the ability to do arbitrary things with the things I find on the stack incredibly useful for development. 2. ? and ?? as well as ed. To get help on foo you just write ``foo?``. To get its source code as well type ``foo??``. Finally to edit the code that correspond's to foo's class or function definition (also works on class instances)) type ``ed foo`` (IIIRCk the default behavior is autoexecution, so you might want to re-alias). 3. Autocompletion with tab. 4. run (including -d and -p options). Try ``run?`` 5. Matplotlib and gui stuff works interactively. (-pylab cmdline option) 6. Convenient Shell interaction (ls, !, int) and interpolation from and too python 7. Pretty printing. But there's plenty more stuff. The most useful in terms of added functionality via emacs is 1, but isearch and emacs editing power make the ipython shell output also noticably more useful (and thus things like ?, ?? and pretty printing). cheers, 'as [*] Inter alia the prompt parsing stuff needs to be different and the ansi color formatting needs to be dealt with. From fredrik at pythonware.com Tue Aug 19 10:33:10 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Aug 2008 16:33:10 +0200 Subject: who to call a list of method inside the class itself In-Reply-To: <95910272-2045-4170-ab6e-549489b12108@d77g2000hsb.googlegroups.com> References: <95910272-2045-4170-ab6e-549489b12108@d77g2000hsb.googlegroups.com> Message-ID: maduma at pt.lu wrote: > Is the following code is ok. who to call all method. > It is working but the call to m() without a reference to self seems > strange > > Thanks for your help > > class CustomMethod: > def method1(self): > .... > def method2(self): > .... > def method3(self): > .... > > def getAllMethod(self): > return [self.method1, self.method2, self.method3] > > def applyAll(self): > for m in self.getAllMethod(): > # how to call all methods ? > # is it correct > m() what happens when you run the code? From alia_khouri at yahoo.com Wed Aug 27 19:01:26 2008 From: alia_khouri at yahoo.com (Alia Khouri) Date: Wed, 27 Aug 2008 16:01:26 -0700 (PDT) Subject: doctesting practices Message-ID: <037c599c-5e64-4527-b112-95d57c6f8531@f63g2000hsf.googlegroups.com> I was wondering the other day how other pythonistas incorporate doctests into their coding practices. I have acquired the habit of keeping an editor open in one window and an ipython instance open in another and then using something similar to the format of the module below. In this case, I incorporate a switch in the _test function whereby covered=False means the doctest is still being written (and is easy to test using the command line) and covered=True means it is somewhat complete and ready to be incorporated into a test suite. This still seems to me to be somewhat hackish and convoluted (execing into globals() and all), and one wonders if there are better coding workflows out there that specifically incorporate doctests as the primary means of testing. Thanks in advance for any feedback AK ''' Simple doctest of a module usage:: >>> fib(0) 0 >>> fib(1) 1 >>> fib(10) 55 >>> fib(15) 610 ''' def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) def _test(covered=False): import doctest if covered: doctest.testmod() else: exec doctest.script_from_examples(__doc__) in globals() if __name__ == '__main__': _test() From Lie.1296 at gmail.com Fri Aug 15 06:56:26 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 15 Aug 2008 03:56:26 -0700 (PDT) Subject: You advice please References: <79efa424-4ed8-4f5c-a4ea-e75899befa5c@r66g2000hsg.googlegroups.com> Message-ID: <8ca31461-4ae7-4cbe-87ea-3aa25570df9e@p31g2000prf.googlegroups.com> On Aug 13, 6:14?pm, Hussein B wrote: > Hey, > I'm a Java/Java EE developer and I'm playing with Python these days. > I like the Python language so much and I like its communities and the > Django framework. > My friends are about to open a Ruby/Rails shop and they are asking me > to join them. > I don't know what, sure I'm not leaving Java, but they are asking me > to stop learning Python and concentrate on Ruby/Rails. A real programmer can learn as much language as he pleases and tell him that concentrating on one language is always a bad idea, since that narrows the mind and diversing language learning is great since it allows you to think of a problem from different angles (especially if the nature of the languages are very different, like one object oriented language and one functional language and one procedural and another dynamic language and another static language). > The sad fact (at least to me), Ruby is getting a lot of attention > these days. I don't know, but the data (http://www.tiobe.com/index.php/content/ paperinfo/tpci/index.html and http://www.langpop.com/) shows that python is more popular than ruby in most cases, nearly by a factor of two. > Why Python isn't getting this attention although is a much more mature > language and it is used by many big, big names? > And do I dare to say it is much more charming? > What do you think of Ruby/Rails? do they worth learning and working > with? Yes, every language have its own good and bad (yeah, even assembly). I have only brushed Ruby once though, so I can't give detailed explanation about it. A good teacher would encourage his students to learn from other masters even though he might be one of the most prominent expert in the subject, a good teacher would even encourage his students to learn from sides that opposed his side of view (learn from your enemy[1]). [1] The usage of the word "enemy" is over-exaggerated. > Any way, I'm not leaving Python and I will try to study it every time > I get a chance... > Thanks. From gagsl-py2 at yahoo.com.ar Thu Aug 14 23:34:44 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 15 Aug 2008 00:34:44 -0300 Subject: Cutting and Pasting in Windows IDLE References: <4dc0cfea0808120904o507da4tdf855e01994802ff@mail.gmail.com> Message-ID: En Tue, 12 Aug 2008 13:04:05 -0300, Victor Subervi escribi?: > A couple of weeks ago I asked how to cut and paste multiple lines in the > Windows IDLE interface. I can only paste one line at a time! > Frustrating. I > want it to work like my Linux interpreter. Why doesn?t it? Please help. Instead of complaining here, report a bug at http://bugs.python.org/ -- Gabriel Genellina From coolman.guron at gmail.com Thu Aug 14 04:47:16 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Thu, 14 Aug 2008 01:47:16 -0700 (PDT) Subject: Read from serial port References: <4ddf48b8-983a-44bf-a579-fd58a16feb3a@x41g2000hsb.googlegroups.com> Message-ID: On Aug 14, 6:11 am, mmrash... at gmail.com wrote: > Hi, > I am newbie in python. I am working on Telit GM862 GPS/GPRS module > which has python interpreter built in. But it seems this problem is > pretty much related to general python structure. > > I need a promt/terminal when the device is connected to PC. If user > enters a command by serial port and press "Enter" then the data is > read by the device and work on the command. This is similar to > readline() function. Unfortunately there is no readline() function for > GM862 device. The following functions are available for serial port > data receive- > > SER.read() - reads whole string at a time from buffer > SER.receive(timeout) - reads if there is any input in the buffer > andwait for the input upto timeout > SER.receivebyte(timeout) - reads if there is any byte sent in the > buffer and wait for the input upto timeout > > Now, is this possible to build a readline() using the functions above? > Can I redirect the terminal or serial port data to receive it as a > whole string when entered "\n"? > > Please advise me how can I solve this problem. > > Thanks a lot. Well i dont think its much of a problem. What i think you should be doing is to read the data into a secondary buffer. it could be a simple string or a specialized buffer class. You would need a method to update() this secondary buffer. ie read from port and append the read data to our buffer. That done you can easily make a readline function. lol i think even a 15yr old can make a readline() from here. btw does ur gm862 support multiple thread? if yes u can put the update() function code and also a method launcher when ever a particular command is sent to the device using a serial connection! hope it helps ! BJ From ewertman at gmail.com Thu Aug 14 14:39:08 2008 From: ewertman at gmail.com (Eric Wertman) Date: Thu, 14 Aug 2008 14:39:08 -0400 Subject: a question about mysqldb In-Reply-To: <20080814183036.DB3D21E4007@bag.python.org> References: <20080814183036.DB3D21E4007@bag.python.org> Message-ID: <92da89760808141139s4ee9ec98w4c59cc2d3a35a939@mail.gmail.com> Just to make sure I understand what you are showing me here: > columns = ('tID', 'tNote') > table_name = 'tmp' > sql = 'select %s from %s where tID=:1' % ( ', '.join(columns), table_name) > cursor.execute(sql, (1,)) > > # sql is now 'select tID, tNote from tmp where tID=:1' > # note the comma in argument tuple to execute (1,) This means I could use this type of syntax? sql = 'SELECT (date,time,name,size,count,stuff,flavor) FROM crazyTable where monster=:1 and feet=:2 and price=:3' cursor.execute(sql,('cookie','3',77.44)) ? I've not encountered that argument style before. From castironpi at gmail.com Sat Aug 30 00:28:43 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 29 Aug 2008 21:28:43 -0700 (PDT) Subject: struct.Struct random access References: <4beb85a8-38eb-4f8e-bc30-024fe3e3b8fa@y21g2000hsf.googlegroups.com> Message-ID: <71141c6e-32d4-4cb3-89da-15c2a1ea07b4@b1g2000hsg.googlegroups.com> On Aug 29, 10:30?pm, Tim Roberts wrote: > castironpi wrote: > > >CMIIW correct me if I'm wrong, I don't think that pack_into returns a > >value the way that pack does. > > Sorry, I was not aware that struct.pack_into and struct.unpack_from already > existed (they were added in Python 2.5). ?I thought you were proposing them > as new additions. > > Because of that, the rest of my post doesn't make much sense. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. I was a lot less enthusiastic too when I discovered 'PyObject_AsWriteBuffer'. Nevertheless I think it could be instructive as well as a benefit. The ctypes conversion, cast( buffer_p + offset ), is a bit of a kludge. With the introduction of 'namedtuple' type, I think it falls right in line with the direction Python is going in. It might suffice to merely expose the 'offset' member of the items in the array of 'formatcode'. Though, the addition of the dictionary to lookup offsets by field name could offset the benefit somewhat. From tjreedy at udel.edu Fri Aug 29 14:56:20 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 29 Aug 2008 14:56:20 -0400 Subject: Using class-attribute as key to sort? In-Reply-To: <712b9e5d-9127-4213-8478-8cf49349068e@a1g2000hsb.googlegroups.com> References: <712b9e5d-9127-4213-8478-8cf49349068e@a1g2000hsb.googlegroups.com> Message-ID: cnb wrote: > In median grade, can I sort on Review-grade somehow? Google "Python sort key attribute" the first hit (after your post) is http://wiki.python.org/moin/HowTo/Sorting Find 'attribute' on that page for your answer (two options). From timothy.grant at gmail.com Mon Aug 11 11:33:54 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Mon, 11 Aug 2008 08:33:54 -0700 Subject: Wildcards for regexps? In-Reply-To: <7de4bd2e-bb0e-44b8-b7ed-24ca7f46ab2b@25g2000hsx.googlegroups.com> References: <7de4bd2e-bb0e-44b8-b7ed-24ca7f46ab2b@25g2000hsx.googlegroups.com> Message-ID: On Sun, Aug 10, 2008 at 9:10 PM, ssecorp wrote: > If I have an expression like "bob marley" and I want to match > everything with one letter wrong, how would I do? > so "bob narely" and "vob marley" should match etc. At one point I needed something like this so did a straight port of the double-metaphone code to python. It's horrible, it's ugly, it's non-pythonic in ways that make me cringe, it has no unit tests, but it does work. -- Stand Fast, tjg. [Timothy Grant] From bj_666 at gmx.net Thu Aug 28 01:12:55 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Aug 2008 05:12:55 GMT Subject: [Q] How to ignore the first line of the text read from a file References: Message-ID: <6hmqenFmpekqU1@mid.uni-berlin.de> On Wed, 27 Aug 2008 21:11:26 -0700, youngjin.michael at gmail.com wrote: > I want to read text line-by-line from a text file, but want to ignore > only the first line. I know how to do it in Java (Java has been my > primary language for the last couple of years) and following is what I > have in Python, but I don't like it and want to learn the better way of > doing it. > > file = open(fileName, 'r') > lineNumber = 0 > for line in file: > if lineNumber == 0: > lineNumber = lineNumber + 1 > else: > lineNumber = lineNumber + 1 > print line > > Can anyone show me the better of doing this kind of task? input_file = open(filename) lines = iter(input_file) lines.next() # Skip line. for line in lines: print line input_file.close() Ciao, Marc 'BlackJack' Rintsch From dblubaugh at belcan.com Tue Aug 26 17:41:04 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Tue, 26 Aug 2008 17:41:04 -0400 Subject: Using Python to shared memory resources between Linux and Windows In-Reply-To: <6hj8rvFmlbhkU1@mid.uni-berlin.de> References: <6hj8rvFmlbhkU1@mid.uni-berlin.de> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3804CF5B81@AWMAIL04.belcan.com> Diez, What you have said is extremely concerning. I am now using VMware. With Linux as the Master and windows as the guest operating system. I was wondering if you have ever had to develop a share memory resource between Linux and windows within a Vmware setup? Thanks for the help. I will not be forgotten, David Blubaugh -----Original Message----- From: Diez B. Roggisch [mailto:deets at nospam.web.de] Sent: Tuesday, August 26, 2008 4:54 PM To: python-list at python.org Subject: Re: Using Python to shared memory resources between Linux and Windows Blubaugh, David A. schrieb: > To All, To whom else if I may ask? > I was wondering if it was possible to utilize python to share a memory > resource between a linux and windows system?? It should be stated > that both the Linux (CENTOS 5) and windows are physically located on > the same computer. Is any of this possible? No, not as that. You can use IPC-mechanisums such as XMLRPC, CORBA or Pyro. But software such as VMWare or VirtualBox tries hard to *not* let guest and host os influence each other. Diez This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From atrooja1998 at gmail.com Fri Aug 29 02:45:24 2008 From: atrooja1998 at gmail.com (atrooja1998 at gmail.com) Date: Thu, 28 Aug 2008 23:45:24 -0700 (PDT) Subject: computer support Message-ID: <01e84436-c94a-42e4-b5db-2ce0f5908498@k30g2000hse.googlegroups.com> hello every body in the group From med.swl at gmail.com Fri Aug 22 17:14:08 2008 From: med.swl at gmail.com (Medardo Rodriguez (Merchise Group)) Date: Fri, 22 Aug 2008 17:14:08 -0400 Subject: Regex on a huge text In-Reply-To: References: <4891add70808221319o1dba87e2gb0d5793737e6227a@mail.gmail.com> Message-ID: <4891add70808221414o248e4c16x5e0fa871e9c3bd48@mail.gmail.com> On Fri, Aug 22, 2008 at 4:48 PM, Terry Reedy wrote: > Does not grep only work a line at a time? Just like the code below? My understanding was that if the regex contains "^" and "$", it will matches in the full file. I wasn't never test it. I tested just before, and didn't work :( If you have a notion of the maximum amount of lines, there is an easy solution. Regards From hniksic at xemacs.org Mon Aug 25 10:22:55 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 25 Aug 2008 16:22:55 +0200 Subject: Equivalents of Ruby's "!" methods? References: <87d4jxutrd.fsf@benfinney.id.au> Message-ID: <874p59uqbk.fsf@mulj.homelinux.net> "Simon Mullis" writes: > There is no equivalent in Python (as far as I know, and I'm only in > my second week of Python so I'm more than likely incorrect!). Python uses strings for that purpose, which works well due to their immutability. Python automatically interns strings used in source code that look like identifiers, so memory is saved. An even closer equivalent of symbols are interned strings (see the "intern" built-in), but they are not as nice to work with as "real" symbols. From roopesh.raj at gmail.com Wed Aug 20 23:10:59 2008 From: roopesh.raj at gmail.com (Roopesh) Date: Wed, 20 Aug 2008 20:10:59 -0700 (PDT) Subject: How to make xss safe strings Message-ID: <919a78ae-8ed8-41ab-a283-6c642462b712@m45g2000hsb.googlegroups.com> Hi, How can I make a string XSS safe? Will simply .replace('<','<').replace('>','>').... do the work? Or are there some other issues to take into account?. Is there already a function in python which will do this for me. Regards Roopesh From __peter__ at web.de Fri Aug 29 14:58:18 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 29 Aug 2008 20:58:18 +0200 Subject: Memory Leek, critique me. Thanks!!! References: Message-ID: Kevin McKinley wrote: > # I posted a few days ago about a memory leak that I think i'm having > # with my first Tkinter program. I've had trouble pinpointing what is > # wrong so i thought i would submit the code and see if anyone would like > # to critique it. Don't create new widgets every time you switch the tab. Instead hide/show the relevant page. You may be able to reuse the idlelib.tabpage.TabPageSet class for that. > # I have one more problem that i can't figure out either. There are a > # bunch of Entry widgets that require number values. > # My problem is if someone inputs a letter or space the program will > # have error that makes part of the Program nonfunctional. You can wrap access to the DoubleVars with try...except, e. g.: try: value = self.COG1.get() except ValueError: # show an error message else: # continue calculation Peter From bockman at virgilio.it Fri Aug 8 06:42:48 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Fri, 8 Aug 2008 03:42:48 -0700 (PDT) Subject: kill thread References: <704879e6-1b21-4c91-99ce-f10e3866c8da@a8g2000prf.googlegroups.com> Message-ID: <28037f13-ac3a-424b-8860-2d65666338f5@t54g2000hsg.googlegroups.com> On 8 Ago, 10:03, "Mathieu Prevot" wrote: > 2008/8/8 Miki : > > > Hello, > > >> I have a threading.Thread class with a "for i in range(1,50)" loop > >> within. When it runs and I do ^C, I have the error [1] as many as > >> loops. I would like to catch this exception (and if possible do some > >> cleanup like in C pthreads) so the program finishes cleanly. Where and > >> how can I do this ? in __run__ ? __init__ ? a try/except stuff ? > > You can have a try/except KeyboardException around the thread code. > > > HTH, > > -- > > Miki > > Of course, but I don't know where. I placed this inside loop, within > called functions from the loop, I still have the problem. > > Mathieu Try this: loop_completed = True for i in range(1,50): try: # your code here except KeyboardException: loop_completed = False break # this breaks the loop # end loop if loop_completed: # code to be executed in case of normal completion else: # code to be executed in case of interruption # code to be executed in both cases From circularfunc at yahoo.se Mon Aug 25 20:50:19 2008 From: circularfunc at yahoo.se (cnb) Date: Mon, 25 Aug 2008 17:50:19 -0700 (PDT) Subject: Return a string result with out breaking loop References: Message-ID: def somefunc(): for action, files in results: full_filename = os.path.join(path_to_watch, files) theact = ACTIONS.get(action, "Unknown") yield str(full_filename) + " " + str(theact) ? Here is an example if that doesn't work, using yield, to show how to use yield: def yi(x): while x > 0: yield str(x) x -= 1 >>> yi(4) >>> a=yi(4) >>> a.next() '4' >>> a.next() '3' >>> a.next() '2' >>> a.next() '1' >>> a.next() Traceback (most recent call last): File "", line 1, in a.next() StopIteration >>> From paul at boddie.org.uk Fri Aug 15 07:30:23 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 15 Aug 2008 04:30:23 -0700 (PDT) Subject: a podcast for music algo-comped with python References: <4600e196-16eb-44da-80ad-42e3589ab31f@f36g2000hsa.googlegroups.com> <7b604f15-945b-4e8a-8ee9-9e0a86746279@r66g2000hsg.googlegroups.com> Message-ID: <2894fe35-1dbf-46aa-aaf6-c59ee7b2331b@l42g2000hsc.googlegroups.com> On 15 Aug, 05:50, castironpi wrote: > On Aug 14, 4:01?pm, Paul Boddie wrote: > > > I'm not sure if I follow the question. I don't have much experience > > with making sound effects, preferring to compose and "pre-render" my > > music, but I imagine there are some tricks that are possible with > > waveform generation and real-time sequencing/playback. > > Oh really, sounds interesting. ?What tricks? Getting it to work, mostly. ;-) I've seen some code reminiscent of the microcomputer era, if I remember correctly, where one is able to specify envelopes and things like that, but I'll have to dig around to see where that was posted. Paul From lists at cheimes.de Fri Aug 22 14:41:27 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 22 Aug 2008 20:41:27 +0200 Subject: Should Python raise a warning for mutable default arguments? In-Reply-To: <3b854a73-21ce-4556-8d0f-5c2ec6fcd6b6@x41g2000hsb.googlegroups.com> References: <00becb2d$0$20312$c3e8da3@news.astraweb.com> <3b854a73-21ce-4556-8d0f-5c2ec6fcd6b6@x41g2000hsb.googlegroups.com> Message-ID: MRAB wrote: > Could there be a new special method __mutable__? Why should we add a new method? Seriously, why should Python be cluttered and slowed down to warn about mutable arguments. It's neither a design flaw nor a surprising feature *ONCE* you have understood how functions work. I agree that the behavior may be surprising for a newbie but it's logical once you got the big picture. Christian From manfredpssnd6 at googlemail.com Sun Aug 24 12:01:34 2008 From: manfredpssnd6 at googlemail.com (manfredpssnd6 at googlemail.com) Date: Sun, 24 Aug 2008 09:01:34 -0700 (PDT) Subject: =?ISO-8859-1?Q?www_single_treff_dresden_in_G=FCnzburg_www_erotik_kon?= =?ISO-8859-1?Q?taktanzeigen_net_erotik_kontaktanzeigen_schwerin_sex_kontakt?= =?ISO-8859-1?Q?anzeigen_berlin_fremdgehen_zu?= Message-ID: <4fbda310-7d6f-47a9-9701-b612b2ea4262@s50g2000hsb.googlegroups.com> www single treff dresden in G?nzburg www erotik kontaktanzeigen net erotik kontaktanzeigen schwerin sex kontaktanzeigen berlin fremdgehen zu + + EROTIK KONTAKTE - EROTISCHE KONTAKTANZEIGEN http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ http://WWW.ADULT-KONTAKT.DE/ + + + + + + + + + + + kontaktanzeigen heilbronn in Grevenbroich kontaktanzeigen fotos in Ludwigshafen kontaktanzeigen beep de in Rhoen sex kontaktanzeigen luebeck in Bernkastel die boerse kontaktanzeigen in Bad Kissingen lustige kontaktanzeigen in Homberg / Efze fremdgehen vertrauen in Delitzsch fremdgehen folgen in Barnim http://www.speedreading.com/phpBB2/ftopic147687.html - serioese erotische kontaktanzeigen in Freyung http://www.meinews.net/cialis-t244331.html - erotik kontaktanzeigen berlins in Bad http://www.bloglines.com/forums/read.php?10,71584 - kontaktanzeigen duisburg in Neuruppin http://draconian.com/dragon-forum/showthread.php?t=17661 - single treff mainz in Peine http://www.bloglines.com/forums/read.php?10,98522 - www internet erotik kontaktanzeigen com in Viersen http://www.meinews.net/comprar-t244436.html - kontaktanzeigen berlins in Emmendingen http://draconian.com/dragon-forum/showthread.php?t=20445 - schwule kontaktanzeigen de in Barnim http://forum.tag-board.com/showthread.php?t=23725 - www erotische kontaktanzeigen in Dillingen http://www.bebin.tv/forum/showthread.php?t=31389 - kontaktanzeigen mit bild in Neustadt http://www.meinews.net/yolur-t244563.html - erotik kontaktanzeigen ukraine in Landau http://www.bloglines.com/forums/read.php?10,71539 - nrw kontaktanzeigen in Cloppenburg http://www.gamesforum.ca/showthread.php?t=318761 - singletreff schweiz in Offenbach http://www.dvd.tv/forums/showthread.php?t=8960 - kontaktanzeigen in leipzig in Wittenberg From dudeja.rajat at gmail.com Thu Aug 21 03:04:17 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Thu, 21 Aug 2008 03:04:17 -0400 Subject: WindowsXP/ CTypes - How to convert ctypes array to a string? In-Reply-To: References: Message-ID: On Tue, Aug 19, 2008 at 8:14 AM, Fredrik Lundh wrote: > dudeja.rajat at gmail.com wrote: > >> I also add the letter 'v' same as you suggested. However, I'm looking >> to store this into some variable ( that variable could be be a string, >> tuple or anything, Im not sure which is the suited one) > > the expression gives you a string object; you'll store it in a variable in > the same way as you'd store any other expression result in Python. > > version = "v%d.%d.%d.%d" % tuple(version) > > but when you find yourself getting stuck on things like this, it might a > good idea to take a step back and read the tutorial again: > > http://docs.python.org/tut/tut.html > > pay special attention to the parts that discuss how variables work in > Python. > > if you prefer some other entry level tutorial, the following is said to be > really good: > > http://www.ibiblio.org/g2swap/byteofpython/read/ > > > > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks Fredrik for your support. Regrads, Rajat From pavlovevidence at gmail.com Thu Aug 7 15:43:08 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 7 Aug 2008 12:43:08 -0700 (PDT) Subject: .cpp to .pyd References: Message-ID: On Aug 7, 3:25?am, vedrandeko... at yahoo.com wrote: > Hello, > > I want to build my C++ (.cpp) script to (.pyd) like this: > > http://en.wikibooks.org/wiki/Python_Programming/Extending_with_C%2B%2B > > I have installed "Microsoft Visual studio .NET 2003" and "Boost > Python" and then after I run my setup script: > > python setup.py build > > I get this error: > > running build > running build_ext > building 'hello' extension > D:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\cl.exe /c / > nologo /Ox > ?/MD /W3 /GX /DNDEBUG -IC:\Panda3D-1.5.2\python\include -IC: > \Panda3D-1.5.2\pytho > n\PC /Tphellomodule.cpp /Fobuild\temp.win32-2.5\Release > \hellomodule.obj > hellomodule.cpp > hellomodule.cpp(9) : fatal error C1083: Cannot open include file: > 'boost/python/ > module.hpp': No such file or directory > error: command '"D:\Program Files\Microsoft Visual Studio .NET > 2003\Vc7\bin\cl.e > xe"' failed with exit status 2 > > I think that my MS visual studio ?cannot find "boost python", if > that's the problem then can you tell me how can I solve it. > This is very begginer question,but I can't find answer nowhere, and I > don't have any expirience with Microsoft products. > > Sorry for my bad english! > Regards, > Veki First, locate the boost header files. Suppose you find the file module.hpp in this location: C:\boost-whatever-version\include\boost\python\module.hpp The part that comes before boost\python\module.hpp is the required include directory. You can tell setup to use this directory by adding the following argument to the Extension call: include_dirs = ['C:\\boost-whatever-version\\include'] Notice the doubling of backslashes. Remember to add the directory where the boost header files lie on your system; don't add this line exactly. You should end up with a setup call that looks like this: setup(name="blah", ext_modules=[ Extension("hello", ["hellomodule.cpp"], libraries = ["boost_python"], include_dirs = ['C:\\boost-whatever-version\\include']) ]) Carl Banks From timr at probo.com Tue Aug 5 00:18:30 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 05 Aug 2008 04:18:30 GMT Subject: SMTP via GMAIL References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> Message-ID: mmm wrote: > >After reading about and using the smtplib module, I thought code such >as below would ignore the 'Cc: ' body line below when sending messages >and instead simply use the RECEIVERS list Correct. It is required by the SMTP spec to behave that way. >But when using smtp.gmail.com as the server I learned that any >@gmail.com address in the Cc: text block would >receive mail even if I changed the code to have the RECEIVERS list to >ignore the CC addresses or not include the gmail address in the CC >list as below Interesting. If true, that is incorrect behavior. >And does anyone have a general routine that lets one also have Bcc: >addresses usign SMTP? To make a Bcc, all you do is include the address in the RECEIVERS list, but don't mention it in the body at all. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From rajanikanth at gmail.com Sat Aug 23 17:54:09 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Sat, 23 Aug 2008 14:54:09 -0700 Subject: dropwhile question Message-ID: <84bdef3c0808231454v3e6f347eucae1f7abeabe193d@mail.gmail.com> >>> list(itertools.dropwhile(lambda x: x<5,range(10))) [5, 6, 7, 8, 9] Why doesn't this work? >>> list(itertools.dropwhile(lambda x: 2 References: <76fd5acf0808101249p1202684epcd7ca3139322f308@mail.gmail.com> Message-ID: Calvin Spealman wrote: > dont quote me but i do think this check is being removed. No, the check hasn't been removed - technically speaking. In Python 3.0 the behavior of the method descriptor has been changed. aclass.somemethod doesn't give you an instancemethod wrapper any more. It's a plain function object like aclass.somemethod.im_func in the 2.x series. Only instances return a bound instancemethod wrapper in Python 3.0. Christian From xtd8865 at gmail.com Tue Aug 26 17:11:30 2008 From: xtd8865 at gmail.com (fred8865) Date: Tue, 26 Aug 2008 22:11:30 +0100 Subject: floating point arithmetic Message-ID: <6k_sk.92243$6s4.59352@newsfe14.ams2> Hi all, I understand that due to different arithmetic used in floating points they are just approximations. Hence, 180/100=1 in my python interpreter. How can I tackle this problem of inaccurate floating point numbers? thank you regards xtd From healey.rich at gmail.com Sat Aug 9 01:17:52 2008 From: healey.rich at gmail.com (Rich Healey) Date: Sat, 09 Aug 2008 15:17:52 +1000 Subject: sending to an xterm In-Reply-To: References: <20080808205821.GJ23567@dragontoe.org> Message-ID: <489D2880.9090208@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Kent Tenney wrote: > Derek Martin pizzashack.org> writes: > >> On Fri, Aug 08, 2008 at 08:25:19PM +0000, Kent Tenney wrote: >>> Howdy, >>> >>> I want to open an xterm, send it a command and have it execute it. >> You can't do that. xterm doesn't execute shell commands passed on >> stdin... It can, however, execute one passed on the command line. >> >> Instead of just running xterm, you can run "xterm -e 'cmd foo bar'" >> where cmd is the program to run and foo and bar are its arguments. >> The problem is that as soon as the program exits, xterm will exit >> also. >> > > OK, I see that. > > (getting off topic) > > any chance of keeping the xterm open after running the command? > > Thanks, > Kent > xterm -hold -e "whatever" > > > -- > http://mail.python.org/mailman/listinfo/python-list - -- Rich Healey - healey.rich at gmail.com Developer / Systems Admin - OpenPGP: 0x8C8147807 MSN: bitchohealey at hotmail.com AIM: richohealey33 irc.psych0tik.net -> #hbh #admins richohealey irc.freenode.org -> #hbh #debian PythonNinja -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkidKIAACgkQLeTfO4yBSAclUwCg3uuvxxWHgZ/vqenrmaNIV/iE ceQAn3e8oC6t0rTLtVhpeisujnqq8jlh =4s8n -----END PGP SIGNATURE----- From pmaupin at gmail.com Fri Aug 29 14:18:38 2008 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 29 Aug 2008 11:18:38 -0700 (PDT) Subject: subclassing complex References: <3ce33299-e13c-4ce0-8a09-eab6d0359033@a3g2000prm.googlegroups.com> Message-ID: <0b908015-59c2-4dc9-a279-e42ce920fe03@d45g2000hsc.googlegroups.com> On Aug 29, 4:24 am, Peter Otten <__pete... at web.de> wrote: > A minimal example is > > >>> class Complex(complex): > > ... def __radd__(self, other): print "radd" > ...>>> 1j + Complex() > > 1j > > versus > > >>> class Int(int): > > ... def __radd__(self, other): print "radd" > ...>>> 1 + Int() > > radd > > I think the complex subclass should behave like the int subclass. > To get an authoritative answer you should file a bug report. Hmm, good point. I shouldn't look at newsgroups when I'm too tired to see the whole problem. According to the documentation at http://docs.python.org/ref/numeric-types.html: "Note: If the right operand's type is a subclass of the left operand's type and that subclass provides the reflected method for the operation, this method will be called before the left operand's non- reflected method. This behavior allows subclasses to override their ancestors' operations." I think this makes it pretty clear that the OP found a bug in how complex works. (Before I read this note, I would have assumed that the int() handling was broken, but it looks like a supportable design decision. Probably whoever implemented it wasn't even thinking about complex numbers, but for consistency, I would think they should be made to work the same.) Regards, Pat From maric at aristote.info Wed Aug 13 20:00:36 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 14 Aug 2008 02:00:36 +0200 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: <1d473f6a-ba34-46b8-a8e4-c7c55b85630d@j33g2000pri.googlegroups.com> References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> <1d473f6a-ba34-46b8-a8e4-c7c55b85630d@j33g2000pri.googlegroups.com> Message-ID: <200808140200.36702.maric@aristote.info> Le Wednesday 13 August 2008 21:04:30 Rhamphoryncus, vous avez ?crit?: > class X(object): > ? ? foo = 42 > > ? ? def bar(self): > ? ? ? ? print foo > ? ? ? ? print self.foo > X.foo = 7 Yes this is a problem, function could not bind their free vars to the class namespace without introducing a subtle incompatibility with actual code. This is exactly this case which would be a problem (your example raise an error and is not exactly a "running code"): G = 1 class A(object) : G = 0 def f(self) : return G -- _____________ Maric Michaud From larry.bates at vitalEsafe.com Sat Aug 30 08:48:58 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Sat, 30 Aug 2008 07:48:58 -0500 Subject: Ensure only single application instance. In-Reply-To: References: Message-ID: Cameron Laird wrote: > In article , > Uberman wrote: >> On Fri, Aug 29, 2008 at 6:51 AM, Heston James wrote: >>> Good afternoon all. >>> >>> I have an application/script which is launched by crontab on a regular >>> basis. I need an effective and accurate way to ensure that only one instance >>> of the script is running at any one time. >> You could create a named pipe in /tmp with a unique (static) name and >> permissions that disallow any kind of read/write access. Then simply have >> your script check for its existence when it starts. If it exists, then >> another instance of your script is running, and just terminate. Make sure >> your original instance removes the pipe when it exits. > > I'll write an article on this subject this fall. The > essentials are: > A. There's no canonical answer; every apparent solution > has problems; > B. The suggestions offered you are certainly among the > popular ones; > C. My personal favorite is to open a (network) socket > server. For reasons I'll eventually explain, this > has particularly apt semantics under Unix. Cameron, I found this recipe (http://code.activestate.com/recipes/474070/) on ActiveState's site that had a working version of a single instance class for Windows that I've used quite successfully. Since I also work a lot Linux, I wrote and donated this version (http://code.activestate.com/recipes/546512/) for Linux that also seems to work well for me. -Larry From frankrentef at yahoo.com Tue Aug 26 12:46:00 2008 From: frankrentef at yahoo.com (frankrentef) Date: Tue, 26 Aug 2008 09:46:00 -0700 (PDT) Subject: Newbie needs help Message-ID: <077ddd87-e944-44e0-935f-2d5cf1368e14@w39g2000prb.googlegroups.com> Greetings all, I'm wanting to maintain what values in one file and call them in another. The purpose being to keep a single location where url's, login's and passwords can be maintained, then called as needed from another file. In file #1 I have... import time import os import sys url = 'http://zoo/' adminlogin = 'Zebra' adminpassword = 'Zebra12$' --------------------------------------------- In file #2 I have the following... from cPAMIE import PAMIE #Imports - used to setup / control finding files import time import os import sys import loginout #name of the file retaining all url/login info from log import log #Create New Pamie Object ie=PAMIE() ie=Visible =1 t=time adminlogin (ie,url) if ie.findText ('Site Status: Active'): log ('PASSED -- ADMIN Module - ADMIN Login & Admin Tab Navigation Successful') else: log ('WARNING -- ADMIN Module Login & Admin Tab Navigation FAILED') time.sleep(2) What am I doing incorrectly to not have file two log in when executed. All files are in the same directory. Keep it simple... I'm new at this. THNX From your.master at gmail.com Mon Aug 11 03:27:46 2008 From: your.master at gmail.com (Brandon) Date: Mon, 11 Aug 2008 00:27:46 -0700 (PDT) Subject: updating dictionaries from/to dictionaries Message-ID: Hi all, I am not altogether experienced in Python, but I haven't been able to find a good example of the syntax that I'm looking for in any tutorial that I've seen. Hope somebody can point me in the right direction. This should be pretty simple: I have two dictionaries, foo and bar. I am certain that all keys in bar belong to foo as well, but I also know that not all keys in foo exist in bar. All the keys in both foo and bar are tuples (in the bigram form ('word1', 'word2)). I have to prime foo so that each key has a value of 1. The values for the keys in bar are variable integers. All I want to do is run a loop through foo, match any of its keys that also exist in bar, and add those key's values in bar to the preexisting value of 1 for the corresponding key in foo. So in the end the key,value pairs in foo won't necessarily be, for example, 'tuple1: 1', but also 'tuple2: 31' if tuple2 had a value of 30 in bar. I *think* the get method might work, but I'm not sure that it can work on two dictionaries the way that I'm getting at. I thought that converting the dictionaries to lists might work, but I can't see a way yet to match the tuple key as x[0][0] in one list for all y in the other list. There's just got to be a better way! Thanks for any help, Brandon (trying hard to be Pythonic but isn't there yet) From a.harrowell at gmail.com Wed Aug 27 09:37:56 2008 From: a.harrowell at gmail.com (TYR) Date: Wed, 27 Aug 2008 06:37:56 -0700 (PDT) Subject: JSON from Python mysqldb References: <998cfbb4-3a72-4e51-9274-518caadd9ed7@m44g2000hsc.googlegroups.com> Message-ID: <09fd0a05-ea98-4765-ad0d-00ad89a9bc21@79g2000hsk.googlegroups.com> There's always the naive option. query = ('species', 'lifestyle', 'coolness', 'tentacles=>8') db.execute('SELECT %s, %s, %s % FROM creatures WHERE %s;' % query) record = dict(zip((query), (db.fetchall())) array = '''{ ''' for k,v in record: array.append('"(k)":"(v)"') array.append(''' }''') From timothy.grant at gmail.com Sun Aug 3 13:51:22 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Sun, 3 Aug 2008 10:51:22 -0700 Subject: Teething troubles with Python on a Mac In-Reply-To: References: <6651edd6-d47f-4e10-bf0b-0875190b9bc2@a1g2000hsb.googlegroups.com> <489546F1.9050102@cosc.canterbury.ac.nz> <3dcf39de-3c3c-4e47-abb4-508d1601a9e2@z11g2000prl.googlegroups.com> Message-ID: On Sun, Aug 3, 2008 at 10:44 AM, Avinash Vora wrote: >> You will likely cause more problems updating the system python than >> managing the two separate installations. > > That's sadly worrying. > >> OSX relies on the version of python they ship. > > I think that helps my point--there *are* bug fixes between major versions > despite the new language changes, and that can really only be a good thing. > >> While there are likely cases where it could be >> replaced completely safely the risks of having to re-install your OS >> at some point because it has the wrong version of python are not worth >> it. > > > I haven't been a Mac user long enough to see a major version change (I was > on Linux/XP/Vista for most of 2.4 and switched distributions right after 2.5 > came out, and then XP before that), so I've never seen a version change, but > is this the sort of thing that will be upgraded in Software Update? > > - Avinash I haven't paid enough attention to the system python in my four years as an Apple user to know. I simply installed the python I wanted and went from there. I honestly don't think it is a cause for concern though. The situation is very similar to on Linux (Red Hat has their version of python) you simply install what you want and use it. -- Stand Fast, tjg. [Timothy Grant] From PaulAlexWilson at gmail.com Mon Aug 4 11:08:26 2008 From: PaulAlexWilson at gmail.com (Wilson) Date: Mon, 4 Aug 2008 08:08:26 -0700 (PDT) Subject: Limits of Metaprogramming References: <0c56829a-7ad2-4ff2-b225-7981538e7c7a@j22g2000hsf.googlegroups.com> Message-ID: <64c69a68-aa00-4f59-a84e-52f5cfa14913@z66g2000hsc.googlegroups.com> On 4 Aug, 14:47, Tomasz Rola wrote: > On Mon, 4 Aug 2008, Wilson wrote: > > Hi all, > > Howdy, > > I am not sure if my remarks will be of any use for you, but here it goes. > > > I have an interesting problem that I'm hoping can be solved with > > metaprogramming, but I don't know how far Python supports code > > generation (and I don't know if I'm taking the correct approach > > either... hence why I'm asking on this group): > > > I'd like to write a program that writes/manipulates a statemachine. My > > idea was that I would define states in a .py file along with their > > transitions and other metadata. I could then write a suite of programs > > that would manipulate these states in interesting ways, such as > > generate diagrams and documentation, test suites, do verifications and > > also edit them. These programs would import the .py file and use > > introspection upon the module's classes (states would be modelled as > > classes). For example, a documentation tool could use graphviz to draw > > the statediagram with the transition table and docstring... > > Maybe you have actually two problems. > > One problem is processing source code into something useful, but > not executable. So it does not necessarily need metaprogramming to be > solved, just some "code comprehension" (like get a python grammar, > lex/yacc and read a lot of docs how to use them). I do want my resultant code to be executable; I want to be able to use "import" to get programmatical access to the classes and structures it contains, such that they can be manipulated, added to, exercised and drawn (using graphviz) via introspection... After any manipulation, i'd like to be able to flatten them back into a .py file (as source such that they are readable as Python code). > > My problem is that I don't know if it's possible to edit these states > > and then write them back to .py. Firstly, if my editing tool was to > > create a new state, I would want to create the class (using type) and > > attach it to the imported state module somehow. I can't find > > information on whether this is possible. Secondly, I'd like to > > manipulate the class and then use the inspect module to get the source > > and write it back to file. Now I'm pretty sure the inspect module will > > only write the source code as found in the original .py file. Is there > > a way to generate the code for a class or other python objects in a > > generic way? Or will I have to bite the bullet and write to custom > > file and generate code from that (like glade with XML)? Or is there > > another solution with templates that I'm over looking? > > Well, "everything" is doable in a Turing-complete language :-). However, > this one problem - code generation and using it on the fly - may be better > solved with some other language, perhaps? > > Not that I want to dissuade you (or anyone else) from using Python, but > last time I checked the state of things (was a good couple of years ago, I > wanted to solve some math-related problem with metaprogramming in Python) > I decided I would do better if I learned Scheme. At least in Scheme, > program structure is so simple, it is just a list (or a sequence of them), > so manipulating code is IMHO much easier. > > I mean, even if in theory every language in Turing-complete class is equal > to each other (one can do the same kind of stuff in one as in the other), > in practice they are not equal at all. So doing everything in one ultimate > language of choice is not very wise from my point of view. > > It does not mean you should immediately go to > > http://en.wikipedia.org/wiki/Scheme_(programming_language) > > but you may do so, and then make an informed choice by yourself. To be > better informed, you may also google for more material - introductions, > opinions, comparisons and some first-hand experience. > > On the other hand, writing "metafiles" and interpreters for them - ugh... > :-). I have read somewhere, that some programmers resist using Scheme > (or some other Lisp) for solving their problem and end up with writing > their own Lisp-like (language|file format) and interpreter(s) for it. So > you better watch yourself. If this effort is going to be something more > permament than "done and go", then you will probably find yourself in the > situation of reinventing the wheel, as your project goes more and more > complex. If this is going to happen, you might use existing wheels and > save some time for thinking on something better. I appreciate these comments, and I know the quote that you are refering to although I can't find it now... Something like: " Every sufficiently large application has a poor/incomplete implementation of LISP embedded within it ". I've looked at LISP before and do appreciate its elegance, but Python has a beauty of its own in its pragmatism, standard libraries and community. So I'll choose to stick with it. > > Having the classes in memory, editing their attributes, adding methods > > and then serialising them to code has an elegance to it in my mind and > > would hopefully simplify things. The result would be directly > > executable by the interpreter itself and editable by python > > developers. But I fear that I may need an intermediary notation/format > > for storage. Any advice/hints would be very useful. > > Yes, there is something elegant in this way of thinking, at least for me. > > As I (indirectly) said above, I am not up to date with recent Python > abilities (I still use Python for a lot of things, I just do not overuse > it for things, that it seems to be not so good at). I hope someone knows > better and steps in to prove me wrong - it is always good to learn > something new. Also, if you have just one problem, then learning a new > language because of it is a bit too much (or maybe not, if you enjoy it > :-) ). But if you plan doing similar or more difficult things in the > future, then knowing Scheme may be good for you. Even if you choose to not > use it, you will be aware of what can be done with it so this knowledge > can provide some ready to use templates. I've been through quite a few of the SICP lectures and again, do appreciate its elegance and they have changed the way I program. > And yes, there are also some other languages in Lisp family, but I think > Scheme is best choice if you don't know any of them already. It is quite > small, it is well defined (I mean, it has some real specification, > instead of being "specified by its implementation") and there is a lot of > info about it on the net that could be easily understood. And, last but > not least, it has metaprogramming included with nice bunch of additional > stuff. For a start, PLT's DrScheme looks nice (IMHO - yes, there are > other nice looking Scheme implementations but this one is probably best > fitted for a beginner): > http://www.plt-scheme.org/ > > Regards, > Tomasz Rola Thanks for your comments. But I believe my solution may lie in using a template language such as cheetah. Too much is already invested in Python! Best Regards, Paul From giles.thomas at gmail.com Tue Aug 19 08:40:02 2008 From: giles.thomas at gmail.com (giles.thomas at gmail.com) Date: Tue, 19 Aug 2008 05:40:02 -0700 (PDT) Subject: ANN: Resolver One 1.2 released Message-ID: <59f2f4c8-5713-4779-8bcf-e1683645bd64@a70g2000hsh.googlegroups.com> We are proud to announce the release of Resolver One, version 1.2 - the largest IronPython application in the world, we think, at 38,000 lines of production code backed up by 150,000 lines of unit and functional tests. Resolver One is a Rapid Application Development tool for analysing and presenting business data, using a familiar spreadsheet interface combined with a powerful IronPython-based scripting capability that allows you to insert your own code directly into the recalculation loop. For version 1.2, we have on big headline feature; a new function called RunWorkbook that allows you to "call" one spreadsheet from another, passing in parameters and pulling out results - just like functions, but without having to code the function by hand. This allows you to mix spreadsheet-based and code-based logic, using the best paradigm for the job in hand. We've also added a whole bunch of usability enhancements - the full (long!) changelist is up on our website, or you can see a screencast: It's free for non-commercial use, so if you would like to take a look, you can download it from our website: (registration no longer required). Best regards, Giles -- Giles Thomas MD & CTO, Resolver Systems Ltd. giles.tho... at resolversystems.com +44 (0) 20 7253 6372 Try out Resolver One! 17a Clerkenwell Road, London EC1M 5RD, UK VAT No.: GB 893 5643 79 Registered in England and Wales as company number 5467329. Registered address: 843 Finchley Road, London NW11 8NA, UK From ggpolo at gmail.com Thu Aug 28 10:54:44 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 28 Aug 2008 11:54:44 -0300 Subject: Tkinter tkMessageBox problem - message box is displayed with an additional window In-Reply-To: References: Message-ID: On Thu, Aug 28, 2008 at 10:29 AM, wrote: > Hi, > I'm working on Windows Platform > > I'm facing some problem with the tkMessageBox. My code is as below: > > import tkMessageBox > import Tix > from Tkinter import * > > if len(installedLibPath) != len(listOfLibraries): > if tkMessageBox.askyesno("Question", \ > type='yesno', icon='warning', \ > message="Some of the libraries are > not installed. Do you wish to continue with the remaining?"): > myRoot = Tix.Tk() > myAppGUIObject = myAppGUI(myRoot) #Class for my GUI > myRoot.mainloop() > else: > sys.exit(0) > It is good to post a short code sample that demonstrates the problem, but it has to run by itself at least. > > The Message Box is called before the Tix.Tk mainloop(). The problems > are as under : > > 1. Since the message box is displayed before the mainloop() is > started, the message box is displayed with another window that is > blank. This should not be displayed. > > 2. As a results of this messagebox (called before the mainloop) the > original Gui started by mainloop doesnot work as desired. Some of the > checkbuttons are displayed as unset (i.e un-ticked). These > checkbuttons used to be set at initialization before I stared using > this messagebox. tkMessageBox blocks till you finish it, maybe that is what is causing your problem but it is hard to tell what you are doing wrong in that myAppGui without seeing it (preferably reduced code demonstrating the problem). Now.. an attempt to solve your problem. Tk always has a root window going on, so that "another window" is inevitable, but you can hide and show it again when needed. You could do something like this: import tkMessageBox import Tkinter class App(object): def __init__(self, master): self.master = master print "tkMessageBox is gone now" root = Tkinter.Tk() root.withdraw() tkMessageBox.askyesno("Question", message="Do you use Python?", type='yesno', icon='warning', master=root) root.deiconify() app = App(root) root.mainloop() > > > Please help. > > Thanks and regards, > Rajat > -- > Regrads, > Rajat > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From bdesth.quelquechose at free.quelquepart.fr Tue Aug 12 11:52:59 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 12 Aug 2008 17:52:59 +0200 Subject: __getattr__, __setattr__ and pickle In-Reply-To: References: Message-ID: <48a1cdce$0$14748$426a74cc@news.free.fr> mwojc a ?crit : > Hi! > My class with implemented __getattr__ and __setattr__ methods cannot be > pickled because of the Error: > > ====================================================================== > ERROR: testPickle (__main__.TestDeffnet2WithBiases) > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "deffnet.py", line 246, in testPickle > cPickle.dump(self.denet, file) > TypeError: 'NoneType' object is not callable > > ---------------------------------------------------------------------- > > Is there an obvious reason i don't know, which prevents pickling with those > methods (if i comment them out the pickling test passes)? > > I'm using Python 2.4.4 on Gentoo Linux. The mentioned methods goes as > follows: > > def __setattr__(self, name, value): > if name == 'weights': > j = 0 > for net in self.nets: > w1 = self.wmarks[j] > w2 = self.wmarks[j+1] > net.weights = value[w1:w2] > j += 1 > else: > self.__dict__[name] = value > > def __getattr__(self, name): > if name == 'weights': > j = 0 > for net in self.nets: > w1 = self.wmarks[j] > w2 = self.wmarks[j+1] > self._weights[w1:w2] = net.weights > j += 1 > return self._weights __getattr__ should raise an AttributeError when name != 'weight' instead of (implicitely) returning None. pickle looks for a couple special method in your object[1], and it looks like it doesn't bother to check if what it found was really callable. [1] cf http://docs.python.org/lib/pickle-inst.html FWIW, you'd be better using a property instead of __getattr__ / __setattr__ if possible. And while we're at it, you dont need to manually take care of your index in the for loop - you can use enumerate(iterable) instead: for j, net in enumerate(self.nets): w1 = self.wmarks[j] w2 = self.wmarks[j+1] self._weights[w1:w2] = net.weights return self._weights HTH > Greetings, From deets at nospam.web.de Mon Aug 18 04:37:11 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 18 Aug 2008 10:37:11 +0200 Subject: if in expression In-Reply-To: <87k5eeafw3.fsf@mulj.homelinux.net> References: <6gsnsqFhdofgU1@mid.uni-berlin.de> <87k5eeafw3.fsf@mulj.homelinux.net> Message-ID: <6gsqlnFhgre0U1@mid.uni-berlin.de> Hrvoje Niksic schrieb: > "Diez B. Roggisch" writes: > >> Since python 2.5, it is >> >> if else >> >> If you want lazy evaluation, you can use lambdas: >> >> iif(cond, lambda: then, lambda: else_)() > > Your code uses "iif" and attempts to evaluate a tuple; could you post > an example that works? > I ask because it's not clear what you mean by lazy evaluation in this > context. The ternary "if" expression introduced in Python 2.5 only > evaluates then_value or else_value depending on the outcome of cond. > How is that different than using a lambda? If iif is defined as this: def iif(cond, then, else_): if cond: return then else: return else_ you have the problem that "then" and "else_" get evaluated *before* they get passed. So for example this factorial function will fail with too deep recursion error: def f(n): return iif(n> 1, n * f(n-1), 1) But if you do it like this, the then and else_ will be functions that get returned and then they need to be called to be acutally evaluated: def f(n): return iif(n> 1, lambda: n * f(n-1), lambda: 1)() Diez From avinashvora at gmail.com Mon Aug 4 04:51:33 2008 From: avinashvora at gmail.com (Avinash Vora) Date: Mon, 4 Aug 2008 14:21:33 +0530 Subject: Peer-to-Peer Chat Program In-Reply-To: <98ad656a0808032214w23b51020j29d97fac1249d14a@mail.gmail.com> References: <98ad656a0808032214w23b51020j29d97fac1249d14a@mail.gmail.com> Message-ID: <007EC863-1A30-499B-A85B-AC1254800C7D@gmail.com> On Aug 4, 2008, at 10:44 AM, Trevor Slocum wrote: > Python seemed like the right choice for writing a peer-to-peer > application, as the support for sockets is adequate and the cross- > platform ability is nominal. That's why I searched around for P2P > frameworks in Python, and didn't have much luck. I've had this problem too. > Like I said, I didn't know anything about P2P before this, and I'm > sure much of what I've done so far can be improved upon. That's why > I'm posting here. I'd like to make an open request to anyone who > would like to assist me in the application development to reduce the > resource usage and improve the overall network efficiency. Even > simple "Ah, I saw you were doing this in your code, I recommend you > do this..." would be of great help. Well, I have about the same level of experience that you do, but I'll take a look at the code and see if I can offer assistance. > If you are interested, you may view the Google Code page at http://code.google.com/p/kaishi/ > or checkout the SVN repository directly using http://kaishi.googlecode.com/svn/trunk/ I haven't read the code itself yet, but I'm extremely interested in the project. I'm a fairly experienced Pythonista, yet I've never really worked on networked projects in any programming language before. Not only does it interest me, but it's a good way to expand my knowledge base. > I have proper hosting and can set up a specific website for > collaboration on project ideas and such if support is carried after > this message. I thank anyone who has taken their time to read this. I would be interested in collaborating in a project like this, I think. Feel free to email me privately to talk further if you wish. -- Avi From george.sakkis at gmail.com Fri Aug 22 14:06:03 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 22 Aug 2008 11:06:03 -0700 (PDT) Subject: property() usage - is this as good as it gets? References: <1138d51d-3454-49a3-8ee4-584e85245992@2g2000hsn.googlegroups.com> Message-ID: On Aug 22, 12:18 pm, David Moss wrote: > Hi, > > I want to manage and control access to several important attributes in > a class and override the behaviour of some of them in various > subclasses. > > Below is a stripped version of how I've implemented this in my current > bit of work. > > It works well enough, but I can't help feeling there a cleaner more > readable way of doing this (with less duplication, etc). > > Is this as good as it gets or can this be refined and improved > especially if I was to add in a couple more attributes some fairly > complex over-ride logic? A small improvement as far as overriding goes is the OProperty recipe: http://infinitesque.net/articles/2005/enhancing%20Python's%20property.xhtml George From steve at REMOVE-THIS-cybersource.com.au Thu Aug 14 18:35:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2008 22:35:53 GMT Subject: for y in range (0,iNumItems)--> not in order? References: <8514d915-95bf-4e57-a16a-68866e0ad789@l42g2000hsc.googlegroups.com> <48a45818$0$1135$426a34cc@news.free.fr> Message-ID: <00b4ae4d$0$14351$c3e8da3@news.astraweb.com> On Thu, 14 Aug 2008 10:54:25 -0700, korean_dave wrote: > Well, here is the whole problem. > > It works perfectly. I can see why that might be a problem. To solve it, open the source code in a text editor and make random changes to the code. -- Steven From vlastimil.brom at gmail.com Sun Aug 17 16:05:52 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sun, 17 Aug 2008 22:05:52 +0200 Subject: like a "for loop" for a string In-Reply-To: <19022694.post@talk.nabble.com> References: <19022098.post@talk.nabble.com> <19022155.post@talk.nabble.com> <19022694.post@talk.nabble.com> Message-ID: <9fdb569a0808171305x6345ec17ife5afd87c2a0c3b7@mail.gmail.com> 2008/8/17 Alexnb > > Basically I want the code to be able to pick out how many strings there are > and then do something with each, or the number. When I say string I mean > how > many "strings" are in the string "string string string non-string string" > > Does that help? > > Not quite sure, if i underestand the task you want to achieve correctly, but do you maybe mean something like the following? (here under "string" the exact wording "string" is meant; obviously any section of the input string will be a string too) >>> fun_string = "string string string non-string non-string string" >>> fun_words = fun_string.split() >>> fun_words ['string', 'string', 'string', 'non-string', 'non-string', 'string'] >>> strings_from_fun_words = [word for word in fun_words if word == "string"] >>> strings_from_fun_words ['string', 'string', 'string', 'string'] >>> len(fun_words) 6 >>> len(strings_from_fun_words) 4 >>> HTH Vlasta -------------- next part -------------- An HTML attachment was scrubbed... URL: From rex.eastbourne at gmail.com Fri Aug 15 20:21:56 2008 From: rex.eastbourne at gmail.com (Rex) Date: Fri, 15 Aug 2008 17:21:56 -0700 (PDT) Subject: Confused: looking for a simple XML parser Message-ID: <04f57893-3f08-41a6-b2a7-defb069c4978@x16g2000prn.googlegroups.com> Hello, I am a Python programmer facing my first small XML project. I am looking to find a simple tool to take an XSD file and convert the XSD tree structure to another text format (e.g. an adjacency matrix for the tree's graph), or convert one xml file format definition into another, non-xml one. I don't need to validate XML documents created by this schema or do anything else fancy. I just need to be able to traverse this tree programmatically and find which child attributes belong to which parent attributes, etc. There seem to be so many Python libraries and programs out there that I don't know what to use. What tool should I use? Thanks, Rex From aassime1 at hotmail.fr Thu Aug 21 08:18:41 2008 From: aassime1 at hotmail.fr (aassime abdellatif) Date: Thu, 21 Aug 2008 05:18:41 -0700 (PDT) Subject: ISLAM and the AIM of LIFE Message-ID: ISLAM and the AIM of LIFE What is your purpose in life? What is the rationale behind our life? Why do we live in this life? These questions frequently intrigue people who try to find accurate answers. People provide different answers to these questions. Some people believe the purpose of life is to accumulate wealth. But one may wonder: What is the purpose of life after one has collected colossal amounts of money? What then? What will the purpose be once money is gathered? If the purpose of life is to gain money, there will be no purpose after becoming wealthy. And in fact, here lies the problem of some disbelievers or misbelievers at some stage of their life, when collecting money is the target of their life. When they have collected the money they dreamt of, their life loses its purpose. They suffer from the panic of nothingness and they live in tension and restlessness. Can Wealth Be an Aim? We often hear of a millionaire committing suicide, sometimes, not the millionaire himself but his wife, son, or daughter. The question that poses itself is: Can wealth bring happiness to one?s life? In most cases the answer is NO. Is the purpose of collecting wealth a standing purpose? As we know, the five-year old child does not look for wealth: a toy for him is equal to a million dollars. The eighteen-year old adolescent does not dream of wealth because he is busy with more important things. The ninety-year old man does not care about money; he is worried more about his health. This proves that wealth cannot be a standing purpose in all the stages of the individual's life. Wealth can do little to bring happiness to a disbeliever, because he/ she is not sure about his fate. A disbeliever does not know the purpose of life. And if he has a purpose, this purpose is doomed to be temporary or self destructive. What is the use of wealth to a disbeliever if he feels scared of the end and skeptical of everything. A disbeliever may gain a lot of money, but will surely lose himself. Worshipping Allah as an Aim On the contrary, faith in Allah gives the believer the purpose of life that he needs. In Islam, the purpose of life is to worship Allah. The term "Worship" covers all acts of obedience to Allah. The Islamic purpose of life is a standing purpose. The true Muslim sticks to this purpose throughout all the stages of his life, whether he is a child, adolescent, adult, or an old man. Worshipping Allah makes life purposeful and meaningful, especially within the framework of Islam. According to Islam this worldly life is just a short stage of our life. Then there is the other life. The boundary between the first and second life is the death stage, which is a transitory stage to the second life. The type of life in the second stage a person deserves depends on his deeds in the first life. At the end of the death stage comes the day of judgment. On this day, Allah rewards or punishes people according to their deeds in the first life. The First Life as an Examination So, Islam looks at the first life as an examination of man. The death stage is similar to a rest period after the test, i. e. after the first life. The Day of Judgment is similar to the day of announcing the results of the examinees. The second life is the time when each examinee enjoys or suffers from the outcome of his behavior during the test period. In Islam, the line of life is clear, simple, and logical: the first life, death, the Day of Judgment, and then the second life. With this clear line of life, the Muslim has a clear purpose in life. The Muslim knows he is created by Allah. Muslims know they are going to spend some years in this first life, during which they have to obey God, because God will question them and hold them responsible for their public or private deeds, because Allah knows about all the deeds of all people. The Muslim knows that his deeds in the first life will determine the type of second life they will live in. The Muslim knows that this first life is a very short one, one hundred years, more or less, whereas the second life is an eternal one. The Eternity of the Second Life The concept of the eternity of the second life has a tremendous effect on a Muslims during their first life, because Muslims believe that their first life determines the shape of their second life. In addition, this determines the shape of their second life and this determination will be through the Judgment of Allah, the All just and Almighty. With this belief in the second life and the Day of Judgment, the Muslim's life becomes purposeful and meaningful. Moreover, the Muslim's standing purpose is to go to Paradise in the second life. In other words, the Muslim's permanent purpose is to obey Allah, to submit to Allah, to carry out His orders, and to keep in continues contact with Him through prayers (five times a day), through fasting (one month a year), through charity (as often as possible), and through pilgrimage (once in one's life). The Need for a Permanent Purpose Disbelievers have purposes in their lives such as collecting money and property, indulging in sex, eating, and dancing. But all these purposes are transient and passing ones. All these purposes come and go, go up and down. Money comes and goes. Health comes and goes. Sexual activities cannot continue forever. All these lusts for money, food and sex cannot answer the individual's questions: so what? Then What? However, Islam saves Muslims from the trouble of asking the question, because Islam makes it clear, from the very beginning, that the permanent purpose of the Muslim in this life is to obey Allah in order to go to Paradise in the second life. We should know that the only way for our salvation in this life and in the hereafter is to know our Lord who created us, believe in Him, and worship Him alone. We should also know our Prophet whom Allah had sent to all mankind, believe in Him and follow Him. We should, know the religion of truth which our Lord has commanded us to believe in, and practice it ? Those in search of truth Who have an open mind and heart, Islamic Education Foundation Welcome You. Objectives: - To Convey the message of Islam To Educate Muslims about Islam To keep in close contact with new Muslims. Activities: Offering Courses and presenting lectures about Islam in several languages. Teaching Islam and Arabic. Teaching new Muslims to receive the Holy Quran. Helping Non- Muslims embrace Islam and complete the required procedures From rtw at freenet.co.uk Sat Aug 2 17:14:11 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 02 Aug 2008 16:14:11 -0500 Subject: Profiling weirdness: Timer.timeit(), fibonacci and memoization References: <59994541-2fb7-450c-ac14-9922d87b6aa1@m45g2000hsb.googlegroups.com> <2m3lk.118118$9I1.20910@newsfe16.ams2> Message-ID: Stefaan Himpe wrote in news:2m3lk.118118$9I1.20910 at newsfe16.ams2 in comp.lang.python: > Nothing weird about this ... > The difference will become larger as your input value becomes larger. > > You can easily understand why if you try to calculate fib(10) by hand, > i.e. work through the algorithm with pencil and paper, > then compare the work you have to do to the memoized version which just > takes fib(9) and fib(8) from memory and adds them together. > I think you missed the point. The problem is that the un-decorated, loop only version takes 35 seconds when called by timeit.Timer. However if you apply the decorator it takes less that a second. In *both* cases the function (fib) only gets called once. Note, I timed the call fib(100) with time.clock() and got a value of less than 1 ms, the memozed version takes about 10 times longer. So the question is: whats going on with timeit.Timer ? Rob. -- http://www.victim-prime.dsl.pipex.com/ From mattheww at chiark.greenend.org.uk Tue Aug 5 13:53:08 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 05 Aug 2008 18:53:08 +0100 (BST) Subject: URLs and ampersands References: <00a78f7e$0$20302$c3e8da3@news.astraweb.com> Message-ID: Gabriel Genellina wrote: > Steven D'Aprano wrote: >> I have searched for, but been unable to find, standard library >> functions that escapes or unescapes URLs. Are there any such >> functions? > Yes: cgi.escape/unescape, and xml.sax.saxutils.escape/unescape. I don't see a cgi.unescape in the standard library. I don't think xml.sax.saxutils.unescape will be suitable for Steven's purpose, because it doesn't process numeric character references (which are both legal and seen in the wild in /href/ attributes). -M- From deets at nospam.web.de Mon Aug 11 03:05:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 11 Aug 2008 09:05:39 +0200 Subject: Wildcards for regexps? In-Reply-To: <7de4bd2e-bb0e-44b8-b7ed-24ca7f46ab2b@25g2000hsx.googlegroups.com> References: <7de4bd2e-bb0e-44b8-b7ed-24ca7f46ab2b@25g2000hsx.googlegroups.com> Message-ID: <6ga6m3Fetd0fU1@mid.uni-berlin.de> ssecorp schrieb: > If I have an expression like "bob marley" and I want to match > everything with one letter wrong, how would I do? > so "bob narely" and "vob marley" should match etc. Fuzzy matching is better done using Levensthein-distance [1] or n-gram-matching [2]. Diez [1] http://en.wikipedia.org/wiki/Levenshtein_distance [2] http://en.wikipedia.org/wiki/Ngram#n-grams_for_approximate_matching From george.trojan at noaa.gov Mon Aug 25 12:13:23 2008 From: george.trojan at noaa.gov (George Trojan) Date: Mon, 25 Aug 2008 16:13:23 +0000 Subject: tkinter: Round Button - Any idea? In-Reply-To: References: Message-ID: akineko wrote: > Hello everyone, > > I'm trying to implement a virtual instrument, which has buttons and > displays, using Tkinter+Pmw. > One of items on the virtual instrument is a round button. > This is imitating a tact switch. > > Tkinter has a Button class, which I can assign a button image. > However, when the button is depressed, the rectangle is sunken (rather > than the round button). > > Probably I need to prepare two images, normal one and depressed one, > and implement all button behaviours by myself. > But before reinventing everything by myself, I'm wondering if there is > an easy way to implement or there is existing widget example of such > button. > So far, I couldn't find any good examples. > > Any suggestions are highly appreciated. > > Best regards, > Aki Niimura Try http://search.cpan.org/~darnold/Tk-StyledButton-0.10/lib/Tk/StyledButton.pod. This is Perl, but it might be worthwhile to take a look at implementation. George From deets at nospam.web.de Wed Aug 20 10:43:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 20 Aug 2008 16:43:50 +0200 Subject: simple Question about using BeautifulSoup References: Message-ID: <6h2outFidk8kU1@mid.uni-berlin.de> Alexnb wrote: > > Okay, I have used BeautifulSoup a lot lately, but I am wondering, how do > you open a local html file? > > Usually I do something like this for a url > > soup = BeautifulSoup(urllib.urlopen('http://www.website.com') > > but the file extension doesn't work. So how do I open one? The docs for urllib.urlopen clearly state that it returns a file-like object. Which BS seems to grok. So... how about passing another file-like object, like... *drumroll* - a file? soup = BeautifulSoup(open("myfile.html")) Apart from the documented possibility to pass the html as string, which means soup = BeautifulSoup(open("myfile.html").read()) will work as well. Diez From deets at nospam.web.de Wed Aug 6 08:16:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 06 Aug 2008 14:16:09 +0200 Subject: enhancing decorator signatures Message-ID: <6ftj2fFd70cgU1@mid.uni-berlin.de> Hi, I'm using Michele S's decorator-module to create decorators with matching signatures, for better error-catching. However, I now want to enrich the signature of a generic wrapper so that the new function will accept more parameters (keyword only). These additional parameters are consumed by the wrapper and not passed to the decorated function. So something like this would be cool: @enriched_decorator("bar") def some_decorator(f, **args, **kwargs): bar = kwargs.pop("bar") return f(**args, **kwargs) Anybody has done something like this? Diez From bill.pursell at gmail.com Wed Aug 6 01:34:59 2008 From: bill.pursell at gmail.com (William Pursell) Date: Tue, 5 Aug 2008 22:34:59 -0700 (PDT) Subject: What Python looks like References: Message-ID: <5fbe65a5-c2ea-465c-ab3c-c2fe1daa8931@m36g2000hse.googlegroups.com> On 5 Aug, 16:08, Brett Ritter wrote: > On Aug 4, 3:43?pm, Gary Herron wrote: > > > A page of Python code looks *clean*, ?with not a lot of > > punctuation/special symbols and (in particular) no useless lines > My first impression of Python was that it was visually hard to parse. > > Put another way, imagine math went from: > 2 + 2 = 4 > to: > two plus two equals four > and then someone decided to abbreviate: > two pl two eq four That looks more like tcl than python to me. My first reaction to python was a strong dislike of indentation as a block delimeter and the convention of using '__*__' names. I got over my issue with indentation fairly quickly, but still don't care for the excessive underscores. However, overall I thought it was extremely clean and easy to write. By the time I saw Python, I had already essentially given up on Perl, but it only took 20 minutes going through the tutorial to completely nail down the lid on the coffin of my Perl self. To summarize the first impression: clean, simple, powerful, and a lot of potential. From jura.grozni at gmail.com Mon Aug 11 11:49:44 2008 From: jura.grozni at gmail.com (azrael) Date: Mon, 11 Aug 2008 08:49:44 -0700 (PDT) Subject: Eclipse, Python, wxPython and code completion References: <94acefa8-f3ec-4d5a-a7cb-a3bf769d35e9@79g2000hsk.googlegroups.com> <9d29ac73-dbe0-44fc-b3a9-b9f74a6aa38c@34g2000hsh.googlegroups.com> Message-ID: <2518f2ba-f2f9-4bee-a388-764d443f52fd@z72g2000hsb.googlegroups.com> if you need a good python ide with great code completition, then why don't you try WingIde. On 11 kol, 10:49, leon.domi... at gmail.com wrote: > On 11 ago, 04:34, "SPE - Stani's Python Editor" > > > > > > wrote: > > On 10 aug, 20:42, leon.domi... at gmail.com wrote: > > > > Hello, > > > > I've installed Eclipse, Python 2.5 and wxPython on Ubuntu 8.04. The > > > problem is that I can't get code completion for wx module. I don't > > > know if it occurs the same with other libraries outside the python > > > "core". > > > > If I compile/run my code containing the wx library, I get an > > > application running correctly, so it looks that definition works fine. > > > Obviously, the obstacle is that I don't know (I don't want to either) > > > the name of every method of every wxPython class so it's difficult to > > > develop anything within this environment. > > > > Thanks a lot > > > > Note: I'm a newbie-coming-from-"Billy's"-WindowsXP > > > You can try SPE which is written in wxPython itself and has very good > > code completion for wxPython. It also includes some wxPython GUI > > builders such as wxGlade and XRCed. I improved it a lot for Hardy, > > which I use myself: > > sudo apt-get install spe > > > Stani > > Thanks, Stani > > I will check this out From kyosohma at gmail.com Wed Aug 6 16:02:33 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 6 Aug 2008 13:02:33 -0700 (PDT) Subject: Parsing of a file References: Message-ID: <760c7cd4-5a23-4e8e-801d-31670afd050b@l42g2000hsc.googlegroups.com> On Aug 6, 1:55?pm, Tommy Grav wrote: > I have a file with the format > > Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames ? > 5 Set 1 > Field f31448: Ra=20:24:58.13 Dec=+79:39:43.9 MJD=53370.06811620 Frames ? > 5 Set 2 > Field f31226: Ra=20:24:45.50 Dec=+78:26:45.2 MJD=53370.06823860 Frames ? > 5 Set 3 > Field f31004: Ra=20:25:05.28 Dec=+77:13:46.9 MJD=53370.06836020 Frames ? > 5 Set 4 > Field f30782: Ra=20:25:51.94 Dec=+76:00:48.6 MJD=53370.06848210 Frames ? > 5 Set 5 > Field f30560: Ra=20:27:01.82 Dec=+74:47:50.3 MJD=53370.06860400 Frames ? > 5 Set 6 > Field f30338: Ra=20:28:32.35 Dec=+73:34:52.0 MJD=53370.06872620 Frames ? > 5 Set 7 > Field f30116: Ra=20:30:21.70 Dec=+72:21:53.6 MJD=53370.06884890 Frames ? > 5 Set 8 > Field f29894: Ra=20:32:28.54 Dec=+71:08:55.0 MJD=53370.06897070 Frames ? > 5 Set 9 > Field f29672: Ra=20:34:51.89 Dec=+69:55:56.6 MJD=53370.06909350 Frames ? > 5 Set 10 > > I would like to parse this file by extracting the field id, ra, dec ? > and mjd for each line. It is > not, however, certain that the width of each value of the field id, ? > ra, dec or mjd is the same > in each line. Is there a way to do this such that even if there was a ? > line where Ra=****** and > MJD=******** was swapped it would be parsed correctly? > > Cheers > ? ?Tommy I'm sure Python can handle this. Try the PyParsing module or learn Python regular expression syntax. http://pyparsing.wikispaces.com/ You could probably do it very crudely by just iterating over each line and then using the string's find() method. Mike From spe.stani.be at gmail.com Sun Aug 10 22:34:44 2008 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: Sun, 10 Aug 2008 19:34:44 -0700 (PDT) Subject: Eclipse, Python, wxPython and code completion References: <94acefa8-f3ec-4d5a-a7cb-a3bf769d35e9@79g2000hsk.googlegroups.com> Message-ID: On 10 aug, 20:42, leon.domi... at gmail.com wrote: > Hello, > > I've installed Eclipse, Python 2.5 and wxPython on Ubuntu 8.04. The > problem is that I can't get code completion for wx module. I don't > know if it occurs the same with other libraries outside the python > "core". > > If I compile/run my code containing the wx library, I get an > application running correctly, so it looks that definition works fine. > Obviously, the obstacle is that I don't know (I don't want to either) > the name of every method of every wxPython class so it's difficult to > develop anything within this environment. > > Thanks a lot > > Note: I'm a newbie-coming-from-"Billy's"-WindowsXP You can try SPE which is written in wxPython itself and has very good code completion for wxPython. It also includes some wxPython GUI builders such as wxGlade and XRCed. I improved it a lot for Hardy, which I use myself: sudo apt-get install spe Stani From gopsychonauts at gmail.com Sun Aug 24 04:18:31 2008 From: gopsychonauts at gmail.com (MeTheGameMakingGuy) Date: Sun, 24 Aug 2008 01:18:31 -0700 (PDT) Subject: No method overloading References: <569491c4-f7e2-4575-8f10-451f8ddb1916@k7g2000hsd.googlegroups.com> Message-ID: On Aug 24, 6:15?pm, Hussein B wrote: > Hey, > Please correct me if I'm wrong but Python doesn't support method > overload, right? > -- > def method(self): > ?#code > def method(self, data): > ?#code > -- > The last declaration of method() erase the previous one (like > JavaScript). > Thanks. Correct. The second declaration overwrites the first. Give data a default argument instead: def method(self, data=None): if data is None: # Normal code else: # data included code Not sure how Pythonic that is, but it should work the way you're requesting... I think. From gminick at nie.ma.takiego.adresu.w.sieci.pl Tue Aug 12 05:05:33 2008 From: gminick at nie.ma.takiego.adresu.w.sieci.pl (Wojtek Walczak) Date: Tue, 12 Aug 2008 09:05:33 +0000 (UTC) Subject: very rare python expression References: Message-ID: Dnia Tue, 12 Aug 2008 16:39:27 +0800, =?GB2312?B?zPC5zw==?= napisa?(a): > Howdy everyone, > > I saw a strange python code in pygame project. What does "while > not(x&528or x in l):" mean? Below code works in python2.5, so "x&528" > is not HTML strings. It looks like a check if 528 flag is set. In this way you can set more than one flag in signle variable: >>> flag1 = 1 >>> flag2 = 2 >>> flag3 = 4 >>> flag4 = 8 >>> flag5 = 10 >>> flags_set = flag2 | flag4 >>> flags_set & flag1 0 >>> flags_set & flag2 2 >>> flags_set & flag3 0 >>> flags_set & flag4 8 >>> flags_set & flag5 0 -- Regards, Wojtek Walczak, http://www.stud.umk.pl/~wojtekwa/ From rajanikanth at gmail.com Wed Aug 20 17:44:35 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Wed, 20 Aug 2008 14:44:35 -0700 Subject: Detect a sequence of keystrokes in an os independent way In-Reply-To: <84bdef3c0808201421tf88ef1dg5e828c00091c4ade@mail.gmail.com> References: <84bdef3c0808201421tf88ef1dg5e828c00091c4ade@mail.gmail.com> Message-ID: <84bdef3c0808201444t193f8045n18bf96990e270e6f@mail.gmail.com> Hi! I was able to do this in the following way: import os fKey= raw_input('') if fKey=='ab': print(os.listdir(os.getcwd())) Is there a better way to do this? Thanks, Raj On Wed, Aug 20, 2008 at 2:21 PM, Rajanikanth Jammalamadaka wrote: > Hi! > > Can somebody tell me if there is an os independent way to detect a > sequence of key strokes. For example, I want to start some other > program once the user presses a couple of keys: ex: key a and then key > b > > Thanks, > > Raj > > -- > "For him who has conquered the mind, the mind is the best of friends; > but for one who has failed to do so, his very mind will be the > greatest enemy." > > Rajanikanth > -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From tjreedy at udel.edu Mon Aug 18 18:21:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 18 Aug 2008 18:21:48 -0400 Subject: Programming Languages Decisions In-Reply-To: References: Message-ID: > This report is intended for any computer programming experts who > would like to propose that their favorite programming language is the one > that should be used for the potentially important application that is being > discussed here. I believe more scientists are happy programming in Python than Perl. Python reads like 'executable pseudocode'. It is, I believe, easier for most people to read and understand than Perl. Rather than explain further, I suggest that you visit python.org and read some of the tutorial to see what *you* think. http://docs.python.org/tut/tut.html tjr From andrew at ilium.invalid Fri Aug 29 02:55:16 2008 From: andrew at ilium.invalid (andrew) Date: Fri, 29 Aug 2008 16:55:16 +1000 Subject: computer support References: <01e84436-c94a-42e4-b5db-2ce0f5908498@k30g2000hse.googlegroups.com> Message-ID: <20080829165448.574@ilium.andrews-corner.org> On 2008-08-29, atrooja1998 at gmail.com wrote: > hello every body in the group Hello Dr Nick :-) -- http://www.andrews-corner.org From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 5 05:28:33 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 05 Aug 2008 11:28:33 +0200 Subject: Python-URL! - weekly Python news and links (Jul 28) In-Reply-To: References: Message-ID: <48981d41$0$17009$426a74cc@news.free.fr> Gabriel Genellina a ?crit : > QOTW: "Python's goals are to maximize opportunities for good > programming, which is quite different." - Bruno Desthuilliers, contrasting > Python with Java > I'm afraid I mostly (and approximatly) quoted somebody else here (just don't ask me for a link to the original...). From sjmachin at lexicon.net Sun Aug 31 20:26:43 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 31 Aug 2008 17:26:43 -0700 (PDT) Subject: Is this a closure? References: <762bc148-281d-4076-8225-280e42d081bd@d45g2000hsc.googlegroups.com> Message-ID: <2e688db6-9fa5-4595-9bcd-91961bf79a05@b30g2000prf.googlegroups.com> On Sep 1, 9:53 am, ssecorp wrote: > A method on a class: > > def printSelf(self): > def printReviews(): > for review in self.reviews: > review.printSelf() > print "Idnbr: ", self.idnumber, "Reviews: ", printReviews() > The above appears to be more or less identical in effect to: def printSelf(self): print "Idnbr: ", self.idnumber, "Reviews: " for review in self.reviews: review.printSelf() except for spacing and more importantly the second version won't print the gratuitous None value returned by printReviews(). What are you aiming for? If your purpose is to explore/understand lexical scopes, I suggest that you get it right in your head in the context of a simple non-recursive function, then /if necessary/ try to do it in a recursive class method. HTH, John From nospam at invalid.com Thu Aug 7 03:01:53 2008 From: nospam at invalid.com (jlist) Date: Thu, 7 Aug 2008 00:01:53 -0700 Subject: benchmark References: <2%qmk.32691$co7.22610@nlpi066.nbdc.sbc.com> Message-ID: I think what makes more sense is to compare the code one most typically writes. In my case, I always use range() and never use psyco. But I guess for most of my work with Python performance hasn't been a issue. I haven't got to write any large systems with Python yet, where performance starts to matter. > That Python code is bad, it contains range() instead of xrange, the > big loop is in the main code instead of inside a function, uses == > None, etc. That person can try this (with Psyco), I have changed very > little, the code is essentially the same: From python-url at phaseit.net Tue Aug 5 09:51:13 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 5 Aug 2008 13:51:13 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Aug 5) Message-ID: QOTW: "As a project manager, I have never had trouble finding people with crazy ideas. I have trouble finding people who can execute. IOW, 'innovation' is way oversold. And it sure as hell shouldn't be applied to products like MS Word or Open office." - Linus http://www.simple-talk.com/opinion/geek-of-the-week/linus-torvalds,-geek-of-the-week/ A very long thread: now arguing against "self", and whether "if x:" enhances polymorphism or not: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a5fa8ff0ffadd6ee/ Floating point representation errors explained (0.2==0.20000000000000001): http://groups.google.com/group/comp.lang.python/browse_thread/thread/9e4f8dce08743c22/ Difference between "type" and "class": http://groups.google.com/group/comp.lang.python/browse_thread/thread/5ae03a438383ba65/ Recursive inner functions aren't destroyed as soon as the outer function exits: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4dbf149b6ded7b84/ "Interpreted" vs "Compiled" programs and languages: http://groups.google.com/group/comp.lang.python/browse_thread/thread/d36bc1db8e64e18c/ Iterating over a sequence by two elements at a time: http://groups.google.com/group/comp.lang.python/browse_thread/thread/85e416759ce1b314/ Coming from Java, "module" and "import" can be confusing terms: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c0a78d37bc010e4e/ __getattr__ with multiple inheritance requires cooperative base classes: http://groups.google.com/group/comp.lang.python/browse_thread/thread/8d05f8 b6c7575c6f/ The different 64-bit architectures and their names are rather confusing: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b8bcb70ad78030dd/ How to define "static variables" in Python: http://groups.google.com/group/comp.lang.python/browse_thread/thread/86db8568d09b5344/ ======================================================================== 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. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org 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 Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html 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 Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. 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://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. 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://www.python.org/dev/peps/pep-0042/ 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!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From gstaniak at wp.pl Mon Aug 25 13:04:07 2008 From: gstaniak at wp.pl (Grzegorz Staniak) Date: Mon, 25 Aug 2008 17:04:07 +0000 (UTC) Subject: Equivalents of Ruby's "!" methods? References: <74d712c2-9a6c-41ab-8d24-4a8084b8e56b@d45g2000hsc.googlegroups.com> Message-ID: On 25.08.2008, Terry Reedy wroted: > The newish sorted() and reversed() built-ins were meant to complement > list.sort and list.reverse, not replace them. BTW, is there a reason why sorted() on a list returns a list, while reversed() on the same list returns an iterator? GS -- Grzegorz Staniak From vedrandekovic at yahoo.com Fri Aug 8 13:11:28 2008 From: vedrandekovic at yahoo.com (vedrandekovic at yahoo.com) Date: Fri, 8 Aug 2008 10:11:28 -0700 (PDT) Subject: .cpp to .pyd References: Message-ID: <8a2eea23-1d72-4653-8a8f-c2bb56bc47f6@l64g2000hse.googlegroups.com> On 7 kol, 21:43, Carl Banks wrote: > On Aug 7, 3:25?am, vedrandeko... at yahoo.com wrote: > > > > > Hello, > > > I want to build my C++ (.cpp) script to (.pyd) like this: > > >http://en.wikibooks.org/wiki/Python_Programming/Extending_with_C%2B%2B > > > I have installed "Microsoft Visual studio .NET 2003" and "Boost > > Python" and then after I run my setup script: > > > python setup.py build > > > I get this error: > > > running build > > running build_ext > > building 'hello' extension > > D:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\cl.exe /c / > > nologo /Ox > > ?/MD /W3 /GX /DNDEBUG -IC:\Panda3D-1.5.2\python\include -IC: > > \Panda3D-1.5.2\pytho > > n\PC /Tphellomodule.cpp /Fobuild\temp.win32-2.5\Release > > \hellomodule.obj > > hellomodule.cpp > > hellomodule.cpp(9) : fatal error C1083: Cannot open include file: > > 'boost/python/ > > module.hpp': No such file or directory > > error: command '"D:\Program Files\Microsoft Visual Studio .NET > > 2003\Vc7\bin\cl.e > > xe"' failed with exit status 2 > > > I think that my MS visual studio ?cannot find "boost python", if > > that's the problem then can you tell me how can I solve it. > > This is very begginer question,but I can't find answer nowhere, and I > > don't have any expirience with Microsoft products. > > > Sorry for my bad english! > > Regards, > > Veki > > First, locate the boost header files. ?Suppose you find the file > module.hpp in this location: > > C:\boost-whatever-version\include\boost\python\module.hpp > > The part that comes before boost\python\module.hpp is the required > include directory. ?You can tell setup to use this directory by adding > the following argument to the Extension call: > > include_dirs = ['C:\\boost-whatever-version\\include'] > > Notice the doubling of backslashes. ?Remember to add the directory > where the boost header files lie on your system; don't add this line > exactly. > > You should end up with a setup call that looks like this: > > setup(name="blah", > ? ? ext_modules=[ > ? ? ? ? Extension("hello", ["hellomodule.cpp"], > ? ? ? ? ? ? libraries = ["boost_python"], > ? ? ? ? ? ? include_dirs = ['C:\\boost-whatever-version\\include']) > ? ? ]) > > Carl Banks Hi, Thanks for quick reply.Maybe I'm crazy but I did what you said and I stll get the same error :( :( :( :(.I have boost version 1.34.1 and I'm running it on Windows XP SP2. Regards, Veki From tjreedy at udel.edu Thu Aug 7 15:19:26 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 07 Aug 2008 15:19:26 -0400 Subject: Best practise implementation for equal by value objects In-Reply-To: <573362d6-5356-4029-8ee4-f43248263976@p25g2000hsf.googlegroups.com> References: <135eb396-6daa-4ff4-a722-253ba149889c@27g2000hsf.googlegroups.com> <573362d6-5356-4029-8ee4-f43248263976@p25g2000hsf.googlegroups.com> Message-ID: Slaunger wrote: > On 6 Aug., 21:36, Terry Reedy wrote: > OK, the situation is more complicated than that then. In the case here > though, > the attributes would always be sinmple bulit-in types, where > eval(repr(x))==x > or, where the attribute is a user-defined equal-by-value class, that I > have > control over. I think most would agree that a more accurate and informative representation is better than a general representation like Pythons default. For instance, >>> a=range(2,10,2) # 3.0 >>> a range(2, 10, 2) is nicer than . So when the initializers for instances are all 'nice' (as for range), go for it (as in 'Age(10)'). And test it as you are by eval'ing the rep. Just accept that the eval will only work in contexts with the class name bound to the class. For built-in like range, it always is, by default -- unless masked by another assignment! Terry Jan Reedy From python6+4 at ulfbaur.de Tue Aug 19 15:55:12 2008 From: python6+4 at ulfbaur.de (mounty) Date: Tue, 19 Aug 2008 21:55:12 +0200 Subject: Idle is not accepting backslashes on some Mac OSX keyboards Message-ID: <48AB2520.7060503@ulfbaur.de> Hi list, I am using a German keyboard on Mac OS X 10.4.11. Idle 1.2.2 is constantly blocking entering the backslash character '\' which is for instance perfectly accepted by my mail application, as you can see for yourself. If I switch to an US, Australian or English keyboard layout the backslash can be entered. Unfortunately this key position is the pound- sign '#' on a German keyboard. The same applies to (German) Switzerland and Austrian keyboards as well. google lists several inquiries like this one: http://bugs.python.org/issue3493 It seems to me that the backslash is hard coded to the physical key in Idle. However this key position is occupied by the '#' pound-sign in the lower-case position of the German keyboard layout. The upper case letter for this physical key is a single quote "'". If I copy the backslash character from a different application into idle, the character will be processed. And as there is no input problem with the terminal program which is shipped with OS X, the problem should be somewhere in Idle. IMHO of course. Here is a photo of the German keyboard layout: http://de.wikipedia.org/wiki/Bild:2007_09_30_de_Apple-Tastatur.jpg If anybody is curious about how we have to enter a backslash, it's "Alt-Shift-7" no matter if you are using OS X, Windows or Linux. Can anyone advise how to proceed. Many thanks Ulf From sjmachin at lexicon.net Fri Aug 29 19:28:20 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 29 Aug 2008 16:28:20 -0700 (PDT) Subject: Date Comparison and Manipulation Functions? References: <6cdf0c14-80b6-42c4-8047-8c01fda8b87c@r15g2000prh.googlegroups.com> <9U8tk.19080$cW3.13729@nlpi064.nbdc.sbc.com> <8AVtk.8079$np7.5970@flpi149.ffdc.sbc.com> Message-ID: <4ad1c85c-479c-44e5-ac1b-ca0509d40c42@s20g2000prd.googlegroups.com> On Aug 30, 2:32 am, "W. eWatson" wrote: > I just tried the following code, and got an unexpected result. > > from pyfdate import * > t = Time() > > ts = Time(2008, 8, 29,15,20,7) > tnew = ts.plus(months=6) > print "new date: ", tnew > > Result: > new date: 2009-02-28 15:20:07 > > I believe that should be April 1, 2009. Presuming that we are talking about the Gregorian calendar, and not one of your own invention, you are (one trusts) alone in that belief. There are SEVEN whole months and a bit between August 29, 2008 and April 1, 2009. Count the months: Sep, Oct, Nov, Dec, Jan, Feb, Mar. > If I use months = 1 and day =31, I > get Sept. 30, 2008 and not Oct. 1, 2008. Is there a way to get around this? Because the number of days in a month is not constant, adding a number of months to a date is capable of more than one interpretation. Most folk are happy with adding the months on and then ensuring that the day is not later than the last day of the resultant (year, month) combination -- this is what the pyfdate routine appears to be doing. However there are some interesting ideas floating around e.g. IIRC an eminent personage once asserted in this newsgroup that adding 1 month to 31 Jan in a non-leap year should produce 3 Mar. There is also the general question with date intervals of whether the first day is included in the calculation or not. E.g. work on Monday, Tuesday, Wednesday: that's 3 days service. Put money into the bank on Monday, withdraw it on Wednesday: that's likely to attract 2 days interest. One needs to understand exactly what calculation is required, and exactly what calculation is provided by the software that is proposed to be used. HTH, John From sriramrajan at acm.org Mon Aug 4 19:54:19 2008 From: sriramrajan at acm.org (Sriram Rajan) Date: Mon, 4 Aug 2008 16:54:19 -0700 Subject: Module re, extract on string match Message-ID: I am wondering if I can use re.search to extract from a particular location in a string. Example: string1='/Users/sriram/folder1/folder2/folder3/folder4/folder5/file' re.search ('folder3,string1) Thanks, Sriram From sjmachin at lexicon.net Thu Aug 21 18:41:24 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 21 Aug 2008 15:41:24 -0700 (PDT) Subject: Could anyone point me to a good site for pearl compiler download References: <437b50e2-d1dc-42e6-ba52-d369312ab5d8@j1g2000prb.googlegroups.com> Message-ID: <8ec528e9-b21a-4a38-99da-7b11db2a91e9@r15g2000prh.googlegroups.com> On Aug 22, 5:01 am, thejm... at gmail.com wrote: > I think he wants to know where he can find good abalone. Which he may have confused with baloney. From circularfunc at gmail.com Tue Aug 12 13:14:05 2008 From: circularfunc at gmail.com (ssecorp) Date: Tue, 12 Aug 2008 10:14:05 -0700 (PDT) Subject: super, object and type? Message-ID: <6632d5a3-78b1-44f8-badb-626605971303@k37g2000hsf.googlegroups.com> >>> super(object, type) , > >>> super(type, object) , > >>> how can both work? they can't both be the superclass of each other right? or is it some sort of mutually recursive definition? >>> help(object) Help on class object in module __builtin__: class object | The most base type >>> help(type) Help on class type in module __builtin__: class type(object) | type(object) -> the object's type | type(name, bases, dict) -> a new type From mu at problemlos.ch Tue Aug 19 07:50:25 2008 From: mu at problemlos.ch (Kurt Mueller) Date: Tue, 19 Aug 2008 13:50:25 +0200 Subject: Getting pid of a remote process In-Reply-To: <197551.74424.qm@web7904.mail.in.yahoo.com> References: <197551.74424.qm@web7904.mail.in.yahoo.com> Message-ID: <48AAB381.1060200@problemlos.ch> srinivasan srinivas schrieb: > Thanks a lot. > But i am wondeing will it return correct pid if more than one instance of run on the remote machine?? > Thanks, > Srini On UNIX-like OS: If you start the process in the background, you can get the PID with: :~> ssh 'ls -l & echo PID=$!' | grep PID PID=30596 :~> see: man bash -> Special Parameters Gr?essli -- Kurt M?ller, mu at problemlos.ch From mh at pixar.com Tue Aug 26 12:42:30 2008 From: mh at pixar.com (mh at pixar.com) Date: Tue, 26 Aug 2008 16:42:30 GMT Subject: Best idiom for looping over input? Message-ID: What's the best Python idiom for this C construct? while ((x = next()) != END) { .... } Now I'm doing x = next() while x != END: .... x = next() There's not an iterator for this function, or I would just use for x in ... Many TIA! Mark -- Mark Harrison Pixar Animation Studios From tjreedy at udel.edu Fri Aug 8 00:04:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 08 Aug 2008 00:04:48 -0400 Subject: how to find out if an object is a class? In-Reply-To: <2de677cb-7dc8-43db-b249-cef11ea62f03@m36g2000hse.googlegroups.com> References: <2de677cb-7dc8-43db-b249-cef11ea62f03@m36g2000hse.googlegroups.com> Message-ID: Carl Banks wrote: > On Aug 7, 8:56 pm, Terry Reedy wrote: >> That is only true and only works for 2.x old-style classes and not for >> 2.x new-style classes and all 3.0 classes, for which isinstance(Q,type) >> is True. > > isinstance(Q,type) is also true for built in types and C extension > types That is rather the point of new and improved classes -- that the implementation language of a class be pretty much irrelevant from the user api viewpoint ;-) From mmanns at gmx.net Sun Aug 24 18:52:56 2008 From: mmanns at gmx.net (Martin Manns) Date: Mon, 25 Aug 2008 00:52:56 +0200 Subject: ANN: pyspread 0.0.9 Message-ID: pyspread 0.0.9 has been released. About: pyspread is a spreadsheet that accepts a pure python expression in each cell. New features: + Find & Replace + Undo & Redo + New context menu in grid + Improved speed especially for large grids + Relative addressing revamped + CSV import improved + Icons changed to Tango iconset + Docstrings improved + Bug fixes in print framework Highlights: + Numpy high performance arrays for spreadsheet calculation + Full access to python batteries from each cell + No non-python syntax add-ons + 3D grid + Cell access via slicing of numpy array S + X, Y, and Z yield current cell location for relative reference Notes: Please use distutils for installation. Make sure that the old files are deleted: $ su $ rm -Rf [MyPythonPath]/site-packages/pyspread* $ python setup.py install $ exit $ pyspread.py Requires: Python >=2.4, Numpy >=1.1.0, and wxPython >=2.8.7.1. License: GPL Project page: http://pyspread.sourceforge.net Enjoy Martin From deets at nospam.web.de Tue Aug 19 02:54:34 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 19 Aug 2008 08:54:34 +0200 Subject: Python Substitute for PHP GD, Resizing an image on the client side In-Reply-To: <02f733bb-e734-46a9-b42f-5b664cdddd3f@v26g2000prm.googlegroups.com> References: <02f733bb-e734-46a9-b42f-5b664cdddd3f@v26g2000prm.googlegroups.com> Message-ID: <6gv91bFhm5u5U1@mid.uni-berlin.de> brahmaforces schrieb: > Hi Folks, > > I am using cherrypy and python. I am trying to get a user profile > image to resize on the client side before uploading to the server. PHP > has a gd library that does it it seems. Has anyone done this in a > python environment without uploading to the server? Everything PHP is server-side. And displaying images is *always* done through uploading and then displaying it. The resizing is done using JavaScript, and then communicating back the selected rectangle to the server - *then* GD or whatnot (PIL, ImageMagick) are used to resize the image. Diez From tjreedy at udel.edu Tue Aug 26 22:34:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 26 Aug 2008 22:34:51 -0400 Subject: sum up numbers in a list In-Reply-To: References: Message-ID: sharon kim wrote: > is there a way to sum up all the numbers in a list? >>> help(sum) sum(...) sum(iterable[, start]) -> value Returns the sum of an iterable of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). When the iterable is empty, returns start. >>> L=[28,39,20,78490,37373,22,2,33,4,5] >>> sum(L) 116016 From timothy.grant at gmail.com Sun Aug 10 01:38:34 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Sat, 9 Aug 2008 22:38:34 -0700 Subject: some kind of trace facility ? In-Reply-To: <489E24F0.6030508@gmail.com> References: <489E24F0.6030508@gmail.com> Message-ID: n Sat, Aug 9, 2008 at 4:14 PM, Stef Mientki wrote: > hello, > > I want to investigate on a regular base the flow of my Python (most of them > using wxPython) programs. > So I want to have some log facilty, that logs things like > - every time a function / method is called > - the time spent in that function / method (or even better start / finish > time) > - in case the function / method has some predefined variables, the values of > these variables > - the caller > > As an extra condition, I'm only interested in my own program modules > (located in a specific subdirectory). > > Is there a module available that can perform such a task ? > Any hints to get started ? > > thanks, > Stef Mientki As is often the case, I have never used this technique, but have read about it: You may want to investigate a logging decorator. Python's Decorator module has a decorator factory that should allow you to log at least the calls. I'm not sure it would help you much with the time the method took, but I could very well be wrong about that. -- Stand Fast, tjg. [Timothy Grant] From timr at probo.com Mon Aug 11 20:58:51 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 11 Aug 2008 17:58:51 -0700 Subject: Broken examples In-Reply-To: <48A0DAF6.4040207@hughes.net> References: <48A0DAF6.4040207@hughes.net> Message-ID: <48A0E04B.1040006@probo.com> norseman wrote: > Tim; > Finally got a chance to test your snippet. Thank you for it! > > I took the liberty of flushing it out a bit. > ================ > #!/--- > # > import os > import win32com.client > > excel = win32com.client.Dispatch( 'Excel.Application' ) > excel.Visible=1 # shows the spreadsheet (can be handy) > xlCSV = 6 > # substitute for list generation > list = ["c:\\temp\\test.xls", "c:\\temp\\test1.xls"] > > for nm in list: > csv = os.path.splitext( nm )[0] + '.csv' > print "Procesing file:", csv > if os.path.exists(csv): # window$ won't auto overwrite > os.unlink(csv) > wb = excel.Workbooks.Open( nm ) > wb.SaveAs( csv, xlCSV ) > print wb.Close() # requires manual verification > # eliminating unattended runs > > #wb.Exit() & wb.Quit() # generate ERROR(s) - no such thing(s) > # leaving Excel open > > excel.Visible=0 # actually closes Excel if no sheet open > # verified via task manager > > print "Check to see if this worked." > > # end of file > ================= > The above does in fact work. > Using the above I have a few questions. > Documentation on xlCSV came from where? > " on .Workbooks.Open(file.xls) came from ??? > " on .SaveAs( filename, xlCSV ) came from ??? > " on .Close() came from ??? MSDN has rather extensive documentation on the Excel object model, although it is somewhat spread out. Search for "Excel object model". I cheated on xlCSV. That's the name of the symbol, and I believe it will even be available as win32com.client.constants.xlCSV after you instantiate the application, but I just searched the web for "xlCSV" and hard-coded the 6. > Tell me about the lack of the .Exit() and/or .Quit(), please. Workbooks don't exit or quit. Workbooks can be closed, but exit is something that applies to the application (excel, in your case). You should also be able to say excel = None to get rid of the app. > I ran out of time today. Is it possible to send something like an > keystroke to a Window () box if it accepts same from > actual keyboard? May not work anyway since .Close() hangs (in > interactive) awaiting it's answer. The Workbook.Close method accepts parameters; you should be able to get it to skip the dialog. I believe that wb.Close( False ) should do this. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From circularfunc at gmail.com Mon Aug 11 00:18:53 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 10 Aug 2008 21:18:53 -0700 (PDT) Subject: for x,y in word1, word2 ? Message-ID: Is there a syntax for looping through 2 iterables at the same time? for x in y: for a in b: is not what I want. I want: for x in y and for a in b: From mail at timgolden.me.uk Tue Aug 19 11:58:54 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 19 Aug 2008 16:58:54 +0100 Subject: How to use win32com to convert a MS WORD doc to HTML ? In-Reply-To: <29de18070808190706mfb6224ya189b63545c05d84@mail.gmail.com> References: <29de18070808190706mfb6224ya189b63545c05d84@mail.gmail.com> Message-ID: <48AAEDBE.6090400@timgolden.me.uk> Lave wrote: > Hi, all ! > > I'm a totally newbie huh:) > > I want to convert MS WORD docs to HTML, I found python windows > extension win32com can make this. But I can't find the method, and I > can't find any document helpful. You have broadly two approaches here, both involving automating Word (ie using the COM object model it exposes, referred to in another post in this thread). 1) Use the COM model to have Word load your doc, and SaveAs it in HTML format. Advantage: it's relatively straightforward. Disadvantage: you're at the mercy of whatever HTML Word emits. 2) Use the COM model to iterate over the paragraphs in your document, emitting your own HTML. Advantage: you get control. Disadvantage: the more complex your doc, the more work you have to do. (What do you do with images, for example? Internal links?) To do the first, just record a macro in Word to do what you want and then reproduce the macro in Python. Something like this: import win32com.client doc = win32com.client.GetObject ("c:/data/temp/songs.doc") doc.SaveAs (FileName="c:/data/temp/songs.html", FileFormat=8) doc.Close () To do the second, you have to roll your own html doc. Crudely, this would do it: import codecs import win32com.client doc = win32com.client.GetObject ("c:/data/temp/songs.doc") with codecs.open ("c:/data/temp/s2.html", "w", encoding="utf8") as f: f.write ("") for para in doc.Paragraphs: text = para.Range.Text style = para.Style.NameLocal f.write ('

%(text)s

\n' % locals ()) doc.Close ()
TJG From saptarshi.guha at gmail.com Sat Aug 16 23:37:45 2008 From: saptarshi.guha at gmail.com (sapsi) Date: Sat, 16 Aug 2008 20:37:45 -0700 (PDT) Subject: QT, ctypes dll and SEG Faults Message-ID: Hello, Below is a small class using ctypes and libspectre to read a postscript file. My program is a PyQT 4.4 application and when the user clicks on a entry in a QTableWidget, i run PostScriptImage( filename_as_contained_in_clicked_tableWidgetItem ) However on i get a segfault while trying document_load. Surprisingly, before i run sys.exit(app.exec_()) (i.e before the app starts) if run PostScriptImage(command_line_specified_ps_file) it works! I know the ctypes so file works with QT since i wrote an application using it, but i hadn't separated the ctypes stuff into separate class (i.e the spectre code was in the widget method). Any ideas why the crash? Regards Saptarshi --Python Code-- class PostScriptImage: def __init__(self,filename): print "Doc New" self.document=libspec.spectre_document_new() print "Load Doc" , filename #############crashed in the following line######################### libspec.spectre_document_load(self.document,filename) print "Done load doc" if libspec.spectre_document_status(self.document): return False self.scale=[1.0,1.0] self.quicksetup() def quicksetup(self): print "RC" rc=libspec.spectre_render_context_new() print "Get 0th Page" page=libspec.spectre_document_get_page (self.document, 0) if libspec.spectre_document_status(self.document): raise Exception("Spectre:Setup Document Error") w= c_int() h= c_int() print "Page Size" libspec.spectre_page_get_size(page, byref(w),byref(h)) self.initialSize=(h.value*1.0,w.value*1.0) self.initialAspect=float(h.value)/float(w.value) self.npages=libspec.spectre_document_get_n_pages(self.document) From sjmachin at lexicon.net Sat Aug 9 07:45:48 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 9 Aug 2008 04:45:48 -0700 (PDT) Subject: How to round a floating point to nearest 10? References: Message-ID: On Aug 9, 9:31 pm, Will Rocisky wrote: > I want my 76.1 to be rounded to decimal 80 and 74.9 to decimal 70. > How can I achieve that? >>> import decimal >>> [decimal.Decimal(int(round(x, -1))) for x in (76.1, 74.9)] [Decimal("80"), Decimal("70")] >>> From brtzsnr at gmail.com Tue Aug 12 10:49:03 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Tue, 12 Aug 2008 07:49:03 -0700 (PDT) Subject: python interpreter Message-ID: <29e59f7a-af87-40b4-9c5e-58abe1a28721@t1g2000pra.googlegroups.com> I'm using python's interpreter's to run various commands (like a normal shell). However if sources are modified changes are not reflected so I have to restart interpreter. Is there any way to avoid restarting this? example: import blah blah.Blah() # ... blah.Blah() changed blah.Blah() # ... new behavior From ryntech at gmail.com Tue Aug 5 09:46:55 2008 From: ryntech at gmail.com (rynt) Date: Tue, 5 Aug 2008 06:46:55 -0700 (PDT) Subject: What Python looks like References: Message-ID: <31075ed4-0780-43a4-9440-45e86dbde87b@q5g2000prf.googlegroups.com> On Aug 4, 12:06?pm, iu2 wrote: > Hi, > > This is a little bit strange post, but I'm curious... > > I learned Python from its tutorial step by step, and practicing > writing small scripts. > I haven't seen a Python program before knowing Python. > > I'm curious, what did Python code look like to those of you who have > seen a bunch of Python code for the first time before knowing Python? > > (I can tell, for example, that seeing perl for the first time looked > like C with many $$$, I could see "if" and "for" and "while" but they > were meaningless. Or Lisp for the first time looked like many words, > no operators, how could that make a program???) > > Thanks I stumbled across Python in 2000 when I ran accross GNUe. I decided to look into Python at that time, and was impressed that the code was readable, and, understandable - even before I looked at the language and library refs. I had been working in a subset of Basic and Delphi at the time. I really don't like Pascal or C/C++ with all of the BEGIN/END and braces. I don't work in Python full time, but do use it for scripting, and "hobby" programming. One heck of a cool language! RCB From news1234 at free.fr Wed Aug 13 17:44:08 2008 From: news1234 at free.fr (nntpman68) Date: Wed, 13 Aug 2008 23:44:08 +0200 Subject: The python not starting under cmd.exe In-Reply-To: References: Message-ID: <48a355a8$0$13081$426a74cc@news.free.fr> durumdara at gmail.com wrote: > Hi! > > My problem is that: > The "test.py" is working in every machine that I use except in my home > machine. > Formerly it worked but now not. I don't know what happened, I searching > for some solution. > > The errormessage is this (after I tried to start test.py under cmd.exe): > > Microsoft Windows XP [verzi?sz?m: 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > c:\>test.py > A rendszer nem tudja v?grehajtani a megadott programot. > > c:\> > Did you try start test.py from the command line? Normally this tries to behave as if you clicked on the file from the explorer? bye N > > Sorry for non english, I try to translate it: > "The system cannot execute the program/application." > > Interesting thing that the starting from Explorer, FreeCommander, or > other tool (Double clicking, Hit enter on it) is working good, so the > "py" linked to the python. > I tried to set path, and pathext too but it have no effect. > > This command is working: > "python test.py". > > I don't know, why not working the "test.py" command, because in other > machines it is working good... :-((((( > > Thanks for any advance in this problem! > > dd > From aspersieman at gmail.com Thu Aug 14 02:52:09 2008 From: aspersieman at gmail.com (Aspersieman) Date: Thu, 14 Aug 2008 08:52:09 +0200 Subject: win32service and Python In-Reply-To: <1agogkuyrv3pv$.gtck933m0pt3.dlg@40tude.net> References: <1agogkuyrv3pv$.gtck933m0pt3.dlg@40tude.net> Message-ID: <48A3D619.6030802@gmail.com> David wrote: > I am collecting informations about win32 services for Python but, except for > few basic examples about Mark Hammond's win32serviceutil, I found nothing > useful. > > Any link is welcome. > > Thank you. > David > > This might also be useful: http://support.microsoft.com/kb/137890 It's doesn't register the service using python - but it's generic enough to work. HTH Nicolaas -- The three things to remember about Llamas: 1) They are harmless 2) They are deadly 3) They are made of lava, and thus nice to cuddle. From norseman at hughes.net Mon Aug 11 20:36:06 2008 From: norseman at hughes.net (norseman) Date: Mon, 11 Aug 2008 17:36:06 -0700 Subject: Broken examples Message-ID: <48A0DAF6.4040207@hughes.net> Tim; Finally got a chance to test your snippet. Thank you for it! I took the liberty of flushing it out a bit. ================ #!/--- # import os import win32com.client excel = win32com.client.Dispatch( 'Excel.Application' ) excel.Visible=1 # shows the spreadsheet (can be handy) xlCSV = 6 # substitute for list generation list = ["c:\\temp\\test.xls", "c:\\temp\\test1.xls"] for nm in list: csv = os.path.splitext( nm )[0] + '.csv' print "Procesing file:", csv if os.path.exists(csv): # window$ won't auto overwrite os.unlink(csv) wb = excel.Workbooks.Open( nm ) wb.SaveAs( csv, xlCSV ) print wb.Close() # requires manual verification # eliminating unattended runs #wb.Exit() & wb.Quit() # generate ERROR(s) - no such thing(s) # leaving Excel open excel.Visible=0 # actually closes Excel if no sheet open # verified via task manager print "Check to see if this worked." # end of file ================= The above does in fact work. Using the above I have a few questions. Documentation on xlCSV came from where? " on .Workbooks.Open(file.xls) came from ??? " on .SaveAs( filename, xlCSV ) came from ??? " on .Close() came from ??? Tell me about the lack of the .Exit() and/or .Quit(), please. I ran out of time today. Is it possible to send something like an keystroke to a Window () box if it accepts same from actual keyboard? May not work anyway since .Close() hangs (in interactive) awaiting it's answer. Tim - thank you again! At least this works well enough that a clerk can press until the thing runs out of material. :) Just press and hold the key until the buffer overflow beeps and go do some filing and when the screen 'stops' do it again... Eliminates typos. Thank you. Steve norseman at hughes.net From mblume at socha.net Sun Aug 24 11:05:25 2008 From: mblume at socha.net (mblume) Date: 24 Aug 2008 15:05:25 GMT Subject: recursively change values in list of lists References: Message-ID: <48b178b5$0$16174$5402220f@news.sunrise.ch> Am Sun, 24 Aug 2008 15:17:46 +0100 schrieb Carson Farmer: > Dear list, > > I'm sure this is a relatively trivial problem, but I have been unable to > find any good examples/explanations on how to do this, so here goes: > > I have multi-polygon object, which is simply a list of polygons, where > each polygon is a list of lines, where each line is a list of points. > What I would like to do, is change the x and y values of each point, all > the while keeping the structure of the lists intact. > > So in the end, the only thing that should be changed is the values, not > the lists themselves... clear as mud? > > Any hints, and/or suggestions are greatly appreciated, > I always do something along the lines of: for (i,obj) in enumerate(list_of_objects): obj = do_something_to_obj(obj) list_of_objects[i] = obj HTH. YMMV. Martin From jasmine956 at gmail.com Fri Aug 1 22:42:22 2008 From: jasmine956 at gmail.com (jasmine956 at gmail.com) Date: Fri, 1 Aug 2008 19:42:22 -0700 (PDT) Subject: HELP DESK SOFTWARE APPLICATION DESIGNED Message-ID: HELP DESK SOFTWARE APPLICATION DESIGNED ___________________________________ http://helpdesksoftwaremanagement.blogspot.com From aassime1 at hotmail.fr Thu Aug 21 08:18:48 2008 From: aassime1 at hotmail.fr (aassime abdellatif) Date: Thu, 21 Aug 2008 05:18:48 -0700 (PDT) Subject: ISLAM and the AIM of LIFE Message-ID: ISLAM and the AIM of LIFE What is your purpose in life? What is the rationale behind our life? Why do we live in this life? These questions frequently intrigue people who try to find accurate answers. People provide different answers to these questions. Some people believe the purpose of life is to accumulate wealth. But one may wonder: What is the purpose of life after one has collected colossal amounts of money? What then? What will the purpose be once money is gathered? If the purpose of life is to gain money, there will be no purpose after becoming wealthy. And in fact, here lies the problem of some disbelievers or misbelievers at some stage of their life, when collecting money is the target of their life. When they have collected the money they dreamt of, their life loses its purpose. They suffer from the panic of nothingness and they live in tension and restlessness. Can Wealth Be an Aim? We often hear of a millionaire committing suicide, sometimes, not the millionaire himself but his wife, son, or daughter. The question that poses itself is: Can wealth bring happiness to one?s life? In most cases the answer is NO. Is the purpose of collecting wealth a standing purpose? As we know, the five-year old child does not look for wealth: a toy for him is equal to a million dollars. The eighteen-year old adolescent does not dream of wealth because he is busy with more important things. The ninety-year old man does not care about money; he is worried more about his health. This proves that wealth cannot be a standing purpose in all the stages of the individual's life. Wealth can do little to bring happiness to a disbeliever, because he/ she is not sure about his fate. A disbeliever does not know the purpose of life. And if he has a purpose, this purpose is doomed to be temporary or self destructive. What is the use of wealth to a disbeliever if he feels scared of the end and skeptical of everything. A disbeliever may gain a lot of money, but will surely lose himself. Worshipping Allah as an Aim On the contrary, faith in Allah gives the believer the purpose of life that he needs. In Islam, the purpose of life is to worship Allah. The term "Worship" covers all acts of obedience to Allah. The Islamic purpose of life is a standing purpose. The true Muslim sticks to this purpose throughout all the stages of his life, whether he is a child, adolescent, adult, or an old man. Worshipping Allah makes life purposeful and meaningful, especially within the framework of Islam. According to Islam this worldly life is just a short stage of our life. Then there is the other life. The boundary between the first and second life is the death stage, which is a transitory stage to the second life. The type of life in the second stage a person deserves depends on his deeds in the first life. At the end of the death stage comes the day of judgment. On this day, Allah rewards or punishes people according to their deeds in the first life. The First Life as an Examination So, Islam looks at the first life as an examination of man. The death stage is similar to a rest period after the test, i. e. after the first life. The Day of Judgment is similar to the day of announcing the results of the examinees. The second life is the time when each examinee enjoys or suffers from the outcome of his behavior during the test period. In Islam, the line of life is clear, simple, and logical: the first life, death, the Day of Judgment, and then the second life. With this clear line of life, the Muslim has a clear purpose in life. The Muslim knows he is created by Allah. Muslims know they are going to spend some years in this first life, during which they have to obey God, because God will question them and hold them responsible for their public or private deeds, because Allah knows about all the deeds of all people. The Muslim knows that his deeds in the first life will determine the type of second life they will live in. The Muslim knows that this first life is a very short one, one hundred years, more or less, whereas the second life is an eternal one. The Eternity of the Second Life The concept of the eternity of the second life has a tremendous effect on a Muslims during their first life, because Muslims believe that their first life determines the shape of their second life. In addition, this determines the shape of their second life and this determination will be through the Judgment of Allah, the All just and Almighty. With this belief in the second life and the Day of Judgment, the Muslim's life becomes purposeful and meaningful. Moreover, the Muslim's standing purpose is to go to Paradise in the second life. In other words, the Muslim's permanent purpose is to obey Allah, to submit to Allah, to carry out His orders, and to keep in continues contact with Him through prayers (five times a day), through fasting (one month a year), through charity (as often as possible), and through pilgrimage (once in one's life). The Need for a Permanent Purpose Disbelievers have purposes in their lives such as collecting money and property, indulging in sex, eating, and dancing. But all these purposes are transient and passing ones. All these purposes come and go, go up and down. Money comes and goes. Health comes and goes. Sexual activities cannot continue forever. All these lusts for money, food and sex cannot answer the individual's questions: so what? Then What? However, Islam saves Muslims from the trouble of asking the question, because Islam makes it clear, from the very beginning, that the permanent purpose of the Muslim in this life is to obey Allah in order to go to Paradise in the second life. We should know that the only way for our salvation in this life and in the hereafter is to know our Lord who created us, believe in Him, and worship Him alone. We should also know our Prophet whom Allah had sent to all mankind, believe in Him and follow Him. We should, know the religion of truth which our Lord has commanded us to believe in, and practice it ? Those in search of truth Who have an open mind and heart, Islamic Education Foundation Welcome You. Objectives: - To Convey the message of Islam To Educate Muslims about Islam To keep in close contact with new Muslims. Activities: Offering Courses and presenting lectures about Islam in several languages. Teaching Islam and Arabic. Teaching new Muslims to receive the Holy Quran. Helping Non- Muslims embrace Islam and complete the required procedures From rafesacks at gmail.com Fri Aug 15 09:35:55 2008 From: rafesacks at gmail.com (Rafe) Date: Fri, 15 Aug 2008 06:35:55 -0700 (PDT) Subject: Passing an object through COM which acts like str but isn't Message-ID: Forgive me if I mangle any terminology here, but please correct me if I do... I have an object which acts exactly like a string as long as I stay in Python land. However, I am using the object in Softimage|XSI a 3D application on Windows. It was created while (briefly) owned by Microsoft, so knowledge of COM with excel or anything else should be applicable I should think. I should also say I am a COM novice and still learning Python (there are few that aren't learning though I suppose). Here is an example: class Name(object): def __init__(self, s): self.__data = s def __repr__(self): return repr(self.__data) def __cmp__(self, string): return cmp(self.__data, string) def __contains__(self, char): return char in self.__data __data = "Test" __doc = "Test" def __Set(self, value): self.__data = value def __Get(self): return self.__data data = property(fget = __Get, fset = __Set, fdel = None, doc = "string-like example") It also uses some new-style class Property From castironpi at gmail.com Sun Aug 24 16:36:22 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 24 Aug 2008 13:36:22 -0700 (PDT) Subject: In-place memory manager, mmap References: <1cf85075-17a1-4a1d-8ea5-bf5104541528@s50g2000hsb.googlegroups.com> Message-ID: On Aug 24, 12:19?pm, Kris Kennaway wrote: > castironpi wrote: > > On Aug 24, 9:52 am, Kris Kennaway wrote: > >> castironpi wrote: > >>> Hi, > >>> I've got an "in-place" memory manager that uses a disk-backed memory- > >>> mapped buffer. ?Among its possibilities are: storing variable-length > >>> strings and structures for persistence and interprocess communication > >>> with mmap. > >>> It allocates segments of a generic buffer by length and returns an > >>> offset to the reserved block, which can then be used with struct to > >>> pack values to store. ?The data structure is adapted from the GNU PAVL > >>> binary tree. > >>> Allocated blocks can be cast to ctypes.Structure instances using some > >>> monkey patching, which is optional. > >>> Want to open-source it. ?Any interest? > >> Just do it. ?That way users can come along later. > > >> Kris > > > How? ?My website? ?Google Code? ?Too small for source forge, I think. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Any of those 3 would work fine, but the last two are probably better > (sourceforge hosts plenty of tiny projects) if you don't want to have to > manage your server and related infrastructure yourself. > > Kris I decided on Google Code. The demo creates 'mappedtree.dat' at 3000 bytes, and allocates or frees memory blocks in it at random. There is a insert-stress test, and a concurrent read-write test too. Tested on WinXP with Python 2.5. Have a look. http://code.google.com/p/pymmapstruct/source/browse/trunk/allocbuf.py From pavlovevidence at gmail.com Wed Aug 6 07:03:29 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 6 Aug 2008 04:03:29 -0700 (PDT) Subject: Locking around References: <87ej547vqs.fsf@nokile.rath.org> <87y73aa3se.fsf@nokile.rath.org> <87sktia0uf.fsf@nokile.rath.org> Message-ID: <1836659a-99e9-4b51-953d-b5622c22fec5@k37g2000hsf.googlegroups.com> On Aug 6, 6:34?am, Nikolaus Rath wrote: > Nikolaus Rath writes: > >> This should work, at least the idea is not flawed. However, I'd say > >> there are too many locks involved. Rather, you just need a simple > >> flag and the global lock. Further, you need a condition/event that > >> tells waiting threads that you released some of the files so that it > >> should see again if the ones it wants are available. > > > I have to agree that this sounds like an easier implementation. I > > just have to think about how to do the signalling. Thanks a lot! > > Here's the code I use now. I think it's also significantly easier to > understand (cv is a threading.Condition() object and cv.locked_keys a > set()). > > ? ? def lock_s3key(s3key): > ? ? ? ? cv = self.s3_lock > > ? ? ? ? try: > ? ? ? ? ? ? # Lock set of locked s3 keys (global lock) > ? ? ? ? ? ? cv.acquire() > > ? ? ? ? ? ? # Wait for given s3 key becoming unused > ? ? ? ? ? ? while s3key in cv.locked_keys: > ? ? ? ? ? ? ? ? cv.wait() > > ? ? ? ? ? ? # Mark it as used (local lock) > ? ? ? ? ? ? cv.locked_keys.add(s3key) > ? ? ? ? finally: > ? ? ? ? ? ? # Release global lock > ? ? ? ? ? ? cv.release() > > ? ? def unlock_s3key(s3key): > ? ? ? ? cv = self.s3_lock > > ? ? ? ? try: > ? ? ? ? ? ? # Lock set of locked s3 keys (global lock) > ? ? ? ? ? ? cv.acquire() > > ? ? ? ? ? ? # Mark key as free (release local lock) > ? ? ? ? ? ? cv.locked_keys.remove(s3key) > > ? ? ? ? ? ? # Notify other threads > ? ? ? ? ? ? cv.notify() > > ? ? ? ? finally: > ? ? ? ? ? ? # Release global lock > ? ? ? ? ? ? cv.release() Freaky... I just posted nearly this exact solution. I have a couple comments. First, the call to acquire should come before the try block. If the acquire were to fail, you wouldn't want to release the lock on cleanup. Second, you need to change notify() to notifyAll(); notify alone won't cut it. Consider what happens if you have two threads waiting for keys A and B respectively. When the thread that has B is done, it releases B and calls notify, but notify happens to wake up the thread waiting on A. Thus the thread waiting on B is starved. Carl Banks From notifications at hallmark.com Tue Aug 19 19:05:40 2008 From: notifications at hallmark.com (hallmark.com) Date: Tue, 19 Aug 2008 18:05:40 -0500 (CDT) Subject: You've received A Hallmark E-Card! Message-ID: <20080819230540.826B295834B@crechemania.com> An HTML attachment was scrubbed... URL: From money.maker20096 at gmail.com Sat Aug 16 02:10:54 2008 From: money.maker20096 at gmail.com (money_maker) Date: Fri, 15 Aug 2008 23:10:54 -0700 (PDT) Subject: Google Adsense Program Is Like Finding Money In The Street. Message-ID: <37742f69-1f74-4cbe-94c1-c3bac9f0dadc@m44g2000hsc.googlegroups.com> Google Adsense Program Is Like Finding Money In The Street. http://money-maker2009.blogspot.com/2008/08/google-adsense-program-is-like-finding.html Hit Success Street With Google Adsense http://money-maker2009.blogspot.com/2008/08/hit-success-street-with-google-adsense.html The Google Adsense Program Is A Great Tool For Every Webmaster http://money-maker2009.blogspot.com/2008/08/google-adsense-program-is-great-tool.html Earn Money Running Ads http://money-maker2009.blogspot.com/2008/08/earn-money-running-ads.html Make Money With Adsense ? Who Say Novices Can?t Make Money Using Adsense http://money-maker2009.blogspot.com/2008/08/make-money-with-adsense-who-say-novices.html how And Where To Get Jobs At Home? http://money-maker2009.blogspot.com/2008/08/how-and-where-to-get-jobs-at-home.html How Do You Become A Successful Affiliate Marketer? http://money-maker2009.blogspot.com/2008/08/how-do-you-become-successful-affiliate.html 7 Ways You Can Make Money On-line http://money-maker2009.blogspot.com/2008/08/7-ways-you-can-make-money-on-line.html At Home Moms Jobs http://money-maker2009.blogspot.com/2008/08/2008-at-home-moms-jobs.html Why Do Most People Fail At Working From Home? http://money-maker2009.blogspot.com/2008/08/why-do-most-people-fail-at-working-from.html Work At Home Data Entry Job - Have Your Tried Looking Local? http://money-maker2009.blogspot.com/2008/08/work-at-home-data-entry-job-have-your.html Earn $500 To $1000 Daily Working From Home. http://money-maker2009.blogspot.com/2008/08/earn-500-to-1000-daily-working-from.html Can Money Be Made Online Or Is It Just A Waste Time And Money? http://money-maker2009.blogspot.com/2008/08/can-money-be-made-online-or-is-it-just.html Earn Money Online Securely http://money-maker2009.blogspot.com/2008/08/earn-money-online-securely.html Earn Your Income From An Internet Home Based Business http://money-maker2009.blogspot.com/2008/08/earn-your-income-from-internet-home.html How do I make money from home? http://money-maker2009.blogspot.com/2008/08/how-do-i-make-money-from-home.html Work From Home - Are There Really Good Jobs Available? http://money-maker2009.blogspot.com/2008/08/work-from-home-are-there-really-good.html Trading On The Forex Market With Forexautomoney http://money-maker2009.blogspot.com/2008/07/trading-on-forex-market-with.html Is It Really Necessary To Quit Your Day Job And To Start An Online Home Business http://money-maker2009.blogspot.com/2008/07/is-it-really-necessary-to-quit-your-day.html How Do You Research A Business Opportunity To Find If They Are Legitimate? http://money-maker2009.blogspot.com/2008/07/how-do-you-research-business.html Getting Your Sites Notice And Make Profit With Online Reviews http://money-maker2009.blogspot.com/2008/07/getting-your-sites-notice-and-make.html Stealth Money Maker - Insider's Review http://money-maker2009.blogspot.com/2008/07/stealth-money-maker-insiders-review.html The Best Online Money Maker Ever http://money-maker2009.blogspot.com/2008/07/best-online-money-maker-ever.html How To Trade Forex The Easy Way http://money-maker2009.blogspot.com/2008/07/how-to-trade-forex-easy-way.html Online Trading http://money-maker2009.blogspot.com/2008/07/online-trading.html Quick Ways To Make Money Online 3 http://money-maker2009.blogspot.com/2008/07/quick-ways-to-make-money-online-3.html Click Affiliate Review http://money-maker2009.blogspot.com/2008/07/1-click-affiliate-review.html forex rates, forex options, forex traders, fx forex, global forex, spot forex, forex pips, dollar forex, euro forex, forex pip, valuta forex, forex currencies, forex valutakurser, forex trade, forex exchange, forex se, fxcm forex, oanda forex, forex signals, forex broker, forex markets, forex chart, forex brokers, refco forex, cms forex, forex trader, realtime forex, forex quotes, forex futures, forex forecast, forex stock, forex platform, forex strategy, forex v? xla, forex rate, forex currency, forex analysis, managed forex, forex charting, daily forex, forex account, forex margin, usd forex, hedging forex, forex financial, us forex, forex foreign exchange, forex kurser, acm forex, gft forex, forex street, gci forex, forex directory, forex strategies, interbank forex, forex forecasts, forex signal, forex reuters, cfd forex, forex stocks, forex sek, dealing forex, real time forex, money forex, capital forex, fxstreet forex, trend forex, forex trades, forex com, automated forex, forex spread, forex pairs, forex foreign, forex accounts, forex currency converter, how to trade forex, foreign exchange, forex factory, forex made easy, forex converter, the forex, currency converter, forex exchange rates, forex exchange rate, forex demo, lkp forex, exchange rates, forex cargo, forex currency exchange, currency exchange, easy forex com, global forex trading, forex club, forex technical analysis, forex trading signals, forex arbitrage, exchange rate, forex books, nz forex, forex brokerage, day forex, forex bank, forex blog, forex day trading, www easy forex, v?xla pengar, forex risk, forex demo account, forex managed account, forex trading online, forex review, premiere trade forex, forex uk, forex book, forex company, gold forex, le forex, city forex, forex api, forex indonesia, day trading, forex enterprises, automated forex trading, forex trading hours, scalping forex, live forex rates, forex managed accounts, ???????? forex, forex glossary, forex download, forex prices, forex scams, forex jobs, singapore forex, easy forex co il, peter bain forex, live forex charts, ????? forex, forex definition, forex commentary, northsea forex, forex danmark, forex risk management, forex trading signal, technical analysis, what is forex trading, forex trading tips, forex video, www forex fi, forex stock market, foreign currency, forex technical, forex articles, private forex, live forex quotes, fibo forex, ifx forex, forex sverige, tokyo forex, forex in india, canada forex, forex brokerage firm, real forex, london forex, australian forex, forex reserves india, pannelli forex, forex data feed, pvc forex, north sea forex, premier forex, forex net, forex card, world forex, gain forex, forex ro, forex spreads, forex betting, forex sa, forex outlook, forex on line, icici forex, mt4 forex, forex simulation, forex g?teborg, forex, concorde forex group, forex brasil, rand forex, asp forex, forex material, atic forex, forex market trading, efx forex, forex sweden, forex ?????, forex advice, forex system trading, forex software, broker forex, currency forex trading, forex seminar, forex online trading, beat forex from high identify in market odds pattern percentage profit trading trading wiley, chart forex, forex news, forex learn, forex training, broker broker.drivensuccess.com forex, course forex trading, forex strategy trading, education forex trading, day forex trading, forex software trading, forex online, exchange forex, forex profiting, day forex tactic technique thirty trade trading trading wiley, com forex, account forex managed, forex mini trading, easy forex made, forex system, forex learn trading, easy forex, candlestick cd forex future market pivot point rom setup stock trading trigger, currency forex system trading, forex maniac, forex managed, currency forex online trading, broker forex online, chart forex free, factory forex, forex forum, 6 dollar easy forex made trade ways, forex platform trading, day forex system trading, forex signal trading, forecast forex, forex premier trade, best forex kept maximum off profit secret street trading wall, forex spot, brain forex in left mindset right success technique trading, broker forex trading, currency forex, demo forex, forex global trading, forex online system trading, currency forex learn online trading, forex option, education forex, account demo forex, course course course.com forex forex forex master trading training, forex quote, forex trading training, account forex trading, course course course course.com forex forex forex forex master trading trading training, forex global, book forex, chart forex live, forex future trading, forex learn trade, currency day forex trading, forex free signal, course forex, capital forex market, forex real time, cargo forex, course course course.com forex forex forex master trading trading training, forex hedging, course course course.com forex forex forex master trading trading, data forex, forex managed trading, best broker forex, forex information, enterprise forex, forex premiere trade, forex online software trading, charting forex, forex spot trading, d Why read online stock-trading articles? http://money-maker2009.blogspot.com/2008/07/why-read-online-stock-trading-articles.html HOW TO START AND OPERATE YOUR OWN PROFITABLE IMPORT/EXPORT BUSINESS AT HOME http://money-maker2009.blogspot.com/2008/07/how-to-start-and-operate-your-own.html How To Trade Forex The Easy Way http://money-maker2009.blogspot.com/2008/07/how-to-trade-forex-easy-way.html Mini Forex Trading Golden Tips And Advice http://money-maker2009.blogspot.com/2008/07/mini-forex-trading-golden-tips-and.html Simple Forex Trading System For Faster Forex Profits http://money-maker2009.blogspot.com/2008/07/simple-forex-trading-system-for-faster.html Forex Cash Cow Strategies http://money-maker2009.blogspot.com/2008/07/forex-cash-cow-strategies.html Forex Strategies - How To Develop A System To Win http://money-maker2009.blogspot.com/2008/07/forex-strategies-how-to-develop-system.html From cvrebert+clp at gmail.com Fri Aug 29 14:48:25 2008 From: cvrebert+clp at gmail.com (Chris Rebert) Date: Fri, 29 Aug 2008 11:48:25 -0700 Subject: Using class-attribute as key to sort? In-Reply-To: <712b9e5d-9127-4213-8478-8cf49349068e@a1g2000hsb.googlegroups.com> References: <712b9e5d-9127-4213-8478-8cf49349068e@a1g2000hsb.googlegroups.com> Message-ID: <47c890dc0808291148p10f347b8pe299d22e110c0f76@mail.gmail.com> Just use the "key" argument to list.sort; e.g. class Foo(object): def __init__(self, x): self.x = x def __repr__(self): return "Foo:"+str(self.x) foos = [Foo(75), Foo(10), Foo(-1)] foos.sort(key = lambda foo: foo.x) print foos #=> [Foo:-1, Foo:10, Foo:75] - Chris ======== Follow the path of the Iguana... http://rebertia.com On Fri, Aug 29, 2008 at 11:22 AM, cnb wrote: > In median grade, can I sort on Review-grade somehow? > something like: > sr = self.reviews.sort(key=self.reviews.instance.grade) > > class Review(object): > def __init__(self, movieId, grade, date): > self.movieId = movieId > self.grade = grade > self.date = date > > class Customer(object): > def __init__(self, idnumber, review): > self.idnumber = idnumber > self.reviews = [review] > > def addReview(self, review): > self.reviews.append(review) > > def averageGrade(self): > tot = 0 > for review in self.reviews: > tot += review.grade > return tot / len(self.reviews) > > #general sort that takes list+spec of objectkey to sort on? > def sortReviews(self): > def qsort(lista): > if len(lista) != 0: > return qsort([x for x in lista[1:] if x.grade < > lista[0].grade]) + [lista[0]] + \ > qsort([x for x in lista[1:] if x.grade >= > lista[0].grade]) > else: > return [] > return qsort(self.reviews) > > def medianGrade(self): > length = len(self.reviews) > sr = self.sortReviews() > #sr = self.reviews.sort(key=self.reviews.instance.grade) > if length % 2 == 0: > return (sr[int(length/2)].grade + sr[int(length/ > 2-1)].grade) / 2 > else: > if length == 1: > return sr[0].grade > else: > return sr[int(round(length/2)-1)].grade > -- > http://mail.python.org/mailman/listinfo/python-list > From marco.bizzarri at gmail.com Sat Aug 30 13:37:16 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 30 Aug 2008 19:37:16 +0200 Subject: Writing to ms excel In-Reply-To: References: Message-ID: <3f0d61c40808301037x22eaa45fic5e7b94bf924a65f@mail.gmail.com> On Sat, Aug 30, 2008 at 4:41 PM, Marin Brkic wrote: > Hello all, > > > I'm trying to find a way to write data to excel cells (or to be more > specific to an .xls file), let's say for the sake of argument, data > readen from a file (although it will be calculated in the process). > I've been searching, but couldn't find any examples which allows that. Is it suitable for you to use a python program talking with a running instance of openoffice? in that case, pyuno could help you. -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From sjmachin at lexicon.net Mon Aug 4 18:46:40 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 4 Aug 2008 15:46:40 -0700 (PDT) Subject: xlrd References: Message-ID: <0347252b-95ed-451f-84ad-1a115c8a7236@b30g2000prf.googlegroups.com> On Aug 4, 11:08 pm, Edwin.Mad... at VerizonWireless.com wrote: > here is working code that will read & display contents of all rows & columns in all the sheets, you need xlrd 0.6.1 > > import xlrd, os, sys > > book = xlrd.open_workbook(sys.argv[1]) > print "The number of worksheets is", book.nsheets > for shx in range(book.nsheets): > sh = book.sheet_by_index(shx) > print 'tab:%s rows:%s cols:%s ' % (sh.name, sh.nrows, sh.ncols) > for rx in range(sh.nrows): > for cx in range(sh.ncols): > try: > if sh.row_types(rx)[cx] and sh.row_values(rx)[cx]: Having "and sh.row_values(rx)[cx]" means that it does not "display contents of all rows & columns in all the sheets"; it omits cells which contain 0., "", or FALSE. Consider getting the row_types and the row_values once per row instead of once per cell. > print '%4s %s' % (xlrd.cellname(rx, cx), sh.row_values(rx)[cx]) If the contents of the cell are a date or an error code, the display will be rather meaningless. > except: > print xlrd.cellname(rx, cx), 'Exception - could not read' I'm having difficulty imagining what could go wrong in your try block, apart from an IndexError (but you are not addressing cells outside the arena). If something does go wrong, it would be rather drastic, and very nice to know exactly what the problem is. As well as printing the cellname, you should get sys.exc_info()[:2] and print the exception details. But for unexpected exceptions, I'd prefer to print the "where am I" info and just re-raise the exception, instead of trying to continue. > print You can use the supplied script runxlrd.py to get similar information e.g. on Windows assuming default setup: prompt>c:\python25\scripts\runxlrd.py show yourfile.xls For help on displaying dates and error codes, see the get_row_data function in runxlrd.py, and read the documentation on the Cell class. Cheers, John From fredrik at pythonware.com Wed Aug 13 09:55:36 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Aug 2008 15:55:36 +0200 Subject: Perl to Python using MqSQLdb In-Reply-To: <20080813110520.GD87062@nexus.in-nomine.org> References: <20080813110520.GD87062@nexus.in-nomine.org> Message-ID: Jeroen Ruigrok van der Werven wrote: >> cursor=db.cursor() >> cursor.execute(sql) >> while (1): >> row = cursor.fetchone() >> if row == None: >> break >> combined = ', '.join(row) > > Why not something like: > > for row in cursor.fetchall(): > combined = ', '.join(row) which can be written as combined = ', '.join(cursor.fetchall()) but probably won't work, since fetchall() returns a sequence of tuples, unless I'm mistaken. Try something like this instead: combined = ', '.join(row[0] for row in cursor.fetchall()) From skip at pobox.com Wed Aug 27 06:11:56 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 27 Aug 2008 05:11:56 -0500 Subject: use of Queue In-Reply-To: <6hkmncFmeh9gU1@mid.uni-berlin.de> References: <6hkmncFmeh9gU1@mid.uni-berlin.de> Message-ID: <18613.10348.610110.440906@montanaro-dyndns-org.local> Diez> Put a sentinel into the queue that gets interpreted as "terminate" Diez> for the workers. You need of course to put it in there once for Diez> each worker. Or make the consumers daemon threads so that when the producers are finished an all non-daemon threads exit, the consumers do as well. Skip From straton at lampsacos.demon.co.uk Mon Aug 25 15:09:36 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Mon, 25 Aug 2008 20:09:36 +0100 Subject: Private attribute In-Reply-To: References: Message-ID: Ken Starks wrote: > I have a class with an attribute called 'gridsize' and I want > a derived class to force and keep it at 0.8 (representing 8mm). > > Is this a correct, or the most pythonic approach? > > #################### > > def __getattr__(self,attrname): > if attrname == 'gridsize': > return 0.8 > > def __setattr__(self,attrname,value): > if attrname == 'gridsize': > pass > else: > self.__dict__[attrname]=value > > ##################### > > > Cheers, > Ken. Perhaps I should mention the alternative I had in mind: ################### class xyz: def __init__(self): self.__dict__['a'] = 123 self.b=456 def __setattr__(self,attrname,value): if attrname == 'a': pass else: self.__dict__[attrname]=value # __getattr__() not redefined. ############################ From fredrik at pythonware.com Wed Aug 27 05:56:47 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 27 Aug 2008 11:56:47 +0200 Subject: atomic increment In-Reply-To: <63533495-5cca-4430-9c9d-fbe1cfee0e1e@s50g2000hsb.googlegroups.com> References: <6297cf93-5eec-4bf3-9104-0605a82f7186@p10g2000prf.googlegroups.com> <6hinduFmfmsrU1@mid.uni-berlin.de> <63533495-5cca-4430-9c9d-fbe1cfee0e1e@s50g2000hsb.googlegroups.com> Message-ID: Frank Millman wrote: > Just out of interest, would the following, without a lock, be safe? > > old, atomic_int = atomic_int, atomic_int+1 nope. there's some information here (make sure you read the comments): http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm and some additional discussion here: http://mail.python.org/pipermail/python-dev/2006-November/thread.html#69981 From aahz at pythoncraft.com Wed Aug 13 21:47:02 2008 From: aahz at pythoncraft.com (Aahz) Date: 13 Aug 2008 18:47:02 -0700 Subject: Upgrading to DB-API (was Re: Corrupted images ...) References: <73674d9f-891b-4acb-8a01-a20232ecf8ce@34g2000hsh.googlegroups.com> Message-ID: In article , Fredrik Lundh wrote: > >Ouch. Please use parameters instead of explicit escapes and string >formatting; Python's not PHP. How would you recommend upgrading an application that is more than ten years old and contains something like 100K lines of code? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From mensanator at aol.com Sat Aug 9 18:38:57 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 9 Aug 2008 15:38:57 -0700 (PDT) Subject: How to round a floating point to nearest 10? References: <13cc5423-4437-4359-a4d1-35d727045358@v13g2000pro.googlegroups.com> Message-ID: <14052b1f-8077-4ccc-8c97-7d065bffa8db@56g2000hsm.googlegroups.com> On Aug 9, 4:54?pm, John Machin wrote: > On Aug 10, 1:19 am, Mensanator wrote: > > > On Aug 9, 6:31 am, Will Rocisky wrote: > > > > I want my 76.1 to be rounded to decimal 80 and 74.9 to decimal 70. > > > How can I achieve that? > > >>> print '%.0e' % 74.9 > > 7e+01 > > >>> print '%.0e' % 76.1 > > > 8e+01 > > But:>>> print '%.0e' % 176.1 > > 2e+002 Which would be correct if your goal was to restrain to 1 significant digit. > > Giving the Subject ("How to round a floating point to nearest 10?"), > there's a strong presumption that the OP would want the answer to be > 180, not 200. Well, I can't read the OP's mind and the cases I HAVE encountered are concerned about the number of significant digits. When laboratories report 3 digits, all my manipulations (ppm conversion, dividing non-detect reporting limits by 2, comparison to TACO, etc. are required to also have exactly 3 digits of significance). >>> print '%.2e' % 0.00000123456 1.23e-006 >>> print '%.2e' % 123456 1.23e+005 >>> print '%.2e' % 0.123000456 1.23e-001 It all depends on what the OP actually wants. He's free to ignore my example. From paul at boddie.org.uk Sat Aug 30 14:17:23 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 30 Aug 2008 11:17:23 -0700 (PDT) Subject: Counting Elements in an xml file References: <7dd68868-5490-464d-9cc1-ddf6a2c50dbe@l42g2000hsc.googlegroups.com> Message-ID: <56fb275e-7f2a-45fa-aa2f-a1111638bebe@m36g2000hse.googlegroups.com> On 30 Aug, 19:37, Ouray Viney wrote: > > > > I would like to be able to count the number of TestCases that contain > the "execute=true" but not the ones that contain "execute=false". With XPath-capable libraries, it should be enough to execute an XPath query on the document. For example: import libxml2dom d = libxml2dom.parse(filename) number_of_cases = d.xpath("count(//Testcase[@execute='true'])") This applies the XPath count function to all Testcase elements in the document having an execute attribute with a value of 'true', thus returning the number of matching elements. Paul From drakonik at gmail.com Sun Aug 3 08:44:55 2008 From: drakonik at gmail.com (Nick Dumas) Date: Sun, 03 Aug 2008 08:44:55 -0400 Subject: proposal, change self. to . In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 It's also worth noting that you can use a different name for the object that represents your class. If you did def __init__(foo):pass, then you would be able to access the class's objects with foo.objectname. Using self is simply the recommended standard. Heiko Wundram wrote: > Am 03.08.2008, 12:51 Uhr, schrieb Equand : >> how about changing the precious self. to . >> imagine >> >> self.update() >> >> .update() >> >> simple right? > > What about: > > class x: > > def x(self,ob): > ob.doSomethingWith(self) > > ? Not so simple anymore, isn't it? If you're not trolling, there's > hundreds of reasons why the explicit self is as it is, and it's not going > to go away, just as a thread that produced immense amounts of response > demonstrated around a week ago. Read that, and rethink. > > --- Heiko. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkiVqEcACgkQLMI5fndAv9j8KgCgmS2e+bTOT+sUPLYhtHBOVlyq kxwAn028YSOGYGB4RyHZxYq6n4+tsSd+ =vH9d -----END PGP SIGNATURE----- From CRhode at LacusVeris.com Mon Aug 18 10:19:24 2008 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Mon, 18 Aug 2008 09:19:24 -0500 Subject: Good python equivalent to C goto References: <48a744b6$0$299$7a628cd7@news.club-internet.fr> Message-ID: On Sun, 17 Aug 2008 09:08:35 -0500, Grant Edwards wrote: > In Python one uses try/raise/except. At the risk of introducing an anachronism and in deference to Mr. "ElementTree" Lundh, I now invoke Godwin's Law (1990): Isn't *try/except* kinda sorta like the musty, old *come from* construct proposed for *fortran*? Here there be typos (abject apologies): o Clark, R. Lawrence. "A Linguistic Contribution to GOTO-less Programming." _Datamation_ Dec. 1973. 18 Aug. 2008 . -- .. Be Seeing You, .. Chuck Rhode, Sheboygan, WI, USA .. Weather: http://LacusVeris.com/WX .. 71? ? Wind W 9 mph From fabiofz at gmail.com Wed Aug 13 09:01:35 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 13 Aug 2008 10:01:35 -0300 Subject: Looking out a module for Subversion In-Reply-To: References: <48A14FB6.4020009@sellerengine.com> <27cbc0fa0808120250t5d41af68u1d72b66f46ad0995@mail.gmail.com> Message-ID: > > I've installed Ulipad and must say it is a small nice tool. Thanks > I also want to give eclipse a try. I referred eclispe web site for this and > it does not mention what basic things need installation before you use the > Dynamic Language Toolkit. So, my question is : what combination of > packages are required for using eclipse as an IDE for python? > > Download eclipse 3.3 from http://download.eclipse.org/eclipse/downloads/drops/R-3.3.2-200802211800/index.php(you can download only the "Platform Runtime Binary" in that link) and then follow the instructions to install Pydev at http://fabioz.com/pydev/manual_101_install.html Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Sun Aug 31 15:20:19 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 31 Aug 2008 15:20:19 -0400 Subject: (in memory) database In-Reply-To: Message-ID: <20080831192019.29191.788708876.divmod.quotient.20148@ohm> On Sun, 31 Aug 2008 18:05:08 +0000, Cameron Laird wrote: >In article , >Paul Boddie wrote: > [snip] > >Thanks for pursuing this, Paul. You have me curious now. > >Let's take a definite example: I have a convenient > Ubuntu 8.04.1 >The content of /etc/apt/sources.list is > deb http://us.archive.ubuntu.com/ubuntu hardy main restricted > deb http://us.archive.ubuntu.com/ubuntu hardy-updates main restricted > deb http://us.archive.ubuntu.com/ubuntu hardy universe multiverse > deb http://security.ubuntu.com/ubuntu hardy-security main restricted >I do > apt-get update > apt-get upgrade > apt-get install python2.5 >then > # python2.5 > Python 2.5 (r25:51908, Dec 11 2006, 21:09:56) > [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. It doesn't seem likely to me that this is the Python 2.5 packaged in Ubuntu 8.04. It's build timestamp is almost a year and a half before 8.04 was released. Here's the header on my installation: Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. This could be a bug in the upgrade from a previous version of Ubuntu installed on the host or perhaps you have a different Python 2.5 installed on the machine that's not from the Ubuntu package repository? Jean-Paul From rasheethkhn at gmail.com Tue Aug 12 07:46:51 2008 From: rasheethkhn at gmail.com (priya) Date: Tue, 12 Aug 2008 04:46:51 -0700 (PDT) Subject: EARN MONEY $1000-25000 PER MONTH TAKE Message-ID: <463d457a-1417-46bb-a740-40661000f67a@b2g2000prf.googlegroups.com> EARN MONEY $1000-25000 PER MONTH TAKE SIMPLE ONLINE SURVEYS CREATE FREE ACCOUNT OTHER DETAILS LOG ON TO *************************************************** http://romanticmoviess.com/ *************************************************** From metaperl at gmail.com Thu Aug 28 15:23:10 2008 From: metaperl at gmail.com (Terrence Brannon) Date: Thu, 28 Aug 2008 12:23:10 -0700 (PDT) Subject: re.compile versus r'' Message-ID: <0bf4b8de-e11e-451c-8d18-58c1a4138375@e53g2000hsa.googlegroups.com> Hello, I'm using a tool (PLY) which apparently expects the tokens to be created using r'' But because one token is a rather complex regular expression, I want to create the regular expression programmatically. How can I generate a string and then create something of the same type that the r'' function does? Concretely, in the program below, consonant is not the same type as t_NAME, but I assume that it needs to be for PLY to use it for tokenizing: import re t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*' guttural = 'kh?|gh?|\"n' palatal = '(?:chh?|jh?|\~n)' cerebral = '\.(?:th?|dh?|n)' dental = '(?:th?|dh?|n)' semivowel = '[yrlv]' sibilant = '[\"\.]?s' aspirant = 'h' consonant = re.compile('|'.join([guttural , palatal , cerebral , dental , semivowel , sibilant , aspirant])) print consonant print t_NAME From steve at REMOVE-THIS-cybersource.com.au Fri Aug 22 21:36:51 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 23 Aug 2008 01:36:51 GMT Subject: Early halt for iterating a_list and iter(a_list) References: <4cf5a96d-c70c-487d-82e3-1d5a1288ab86@n33g2000pri.googlegroups.com> Message-ID: <00bf6479$0$20312$c3e8da3@news.astraweb.com> On Fri, 22 Aug 2008 07:23:18 -0700, Lie wrote: [...] >> iterators are once-only objects. ?there's nothing left in "c" when you >> enter the inner loop the second time, so nothing is printed. >> >> > Ah, now I see. You have to "restart" the iterator if you want to use it > the second time (is it possible to do that?). In general, no, iterators can't be restarted. Think of it as squeezing toothpaste out of a tube. You can't generally reverse the process. [...] > I see, but if/when a function expects a sequence but then fed with an > iterator, it would be against duck-typing to check whether something is > a sequence or an iterator, but iterator is good for one iteration only > while sequence is good for multiple usage. So is there a clean way to > handle this? (i.e. a design pattern that allows sequence and iterator to > be treated with the same code) The only clean way to treat iterators and sequences identically is to limit yourself to behaviour that both use. That pretty much means a simple for loop: for item in iterator_or_sequence: do_something(item) Fortunately that's an incredibly useful pattern. I often find myself converting sequences to iterators, so I can handle both types identically: def treat_first_item_specially(iterator_or_sequence): it = iter(iterator_or_sequence) try: first_item(it.next) except StopIteration: pass else: for item in it: other_items(item) > If there is no such design pattern for that problem, should one be > available? I'm thinking of one: "all iterables would have > iterable.restart() method, which is defined as 'restarting the iterator > for iterator' or 'do nothing for sequences'." But not all iterators can be restarted. Here's a contrived example: def once_only_iterator(directory): """Return the name of files being deleted.""" for filename in os.list(directory): yield filename os.remove(filename) You can't restart that one, at least not with a *lot* of effort. In general, the only ways to restart an arbitrary iterator are: (1) make a copy of everything the iterator returns, then iterate over the copy; or (2) exploit idiosyncratic knowledge about the specific iterator in question. That in turn may mean: find the non-iterator data that your iterator uses, and use it again. e.g. data = {'a': 1, 'b': 2, 'c': 4, 'd': 8} def make_iterator(data): items = sorted(data.items()) for item in items: yield item it = make_iterator(data) for i in it: print i # Restart the iterator. it = make_iterator(data) That's not exactly what you were hoping for, but in the generic case of arbitrary iterators, that's the best you're going to get. Another example of exploiting specific knowledge about the iterator is that, starting from Python 2.5, generators become co-routines that can accept information as well as yield it. I suggest you read this: http://docs.python.org/whatsnew/pep-342.html but note carefully that you can't just call send() on any arbitrary iterator and expect it to do something sensible. Lastly, you can write your own iterator, and give it it's own restart() method. I recommend the exercise. Once you see how much specific knowledge of the iterator is required, you may understand why there can't possibly be a generic restart() method that works on arbitrary iterators. [...] > Wait a minute... I've got an idea, we could use itertools.tee to copy > the iterator and iterating on the copy, like this right?: > > for a_ in a: > b, b_copy = itertools.tee(b) > for b_ in b_copy: > c, c_copy = itertools.tee(c) > for c_ in c_copy: > print a_, b_, c_ > > That works with both "requirement": able to handle sequence and iterator > with the same code and the code for common cases where iterators are > used once only wouldn't need to be changed. Personally though, I don't > think it's a clean solution, looks a bit of hackery. itertools.tee() works by keeping a copy of the iterator's return values. If your iterator is so huge you can't make a copy of its data, then tee() will fail. -- Steven From george.sakkis at gmail.com Fri Aug 29 13:25:49 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 29 Aug 2008 10:25:49 -0700 (PDT) Subject: How to check is something is a list or a dictionary or a string? References: Message-ID: <68e5ea6d-08fd-4f7c-9780-df5d1fabfded@p25g2000hsf.googlegroups.com> On Aug 29, 12:16 pm, dudeja.ra... at gmail.com wrote: > Hi, > > How to check if something is a list or a dictionary or just a string? > Eg: > > for item in self.__libVerDict.itervalues(): > self.cbAnalysisLibVersion(END, item) > > where __libVerDict is a dictionary that holds values as strings or > lists. So now, when I iterate this dictionary I want to check whether > the item is a list or just a string? if isinstance(item,basestring): # it's a string ... else: # it should be a list # typically you don't have to check it explicitly; # even if it's not a list, it will raise an exception later anyway if you call a list-specific method HTH, George From ckumwaka at googlemail.com Thu Aug 14 01:27:43 2008 From: ckumwaka at googlemail.com (Cyprian Kumwaka) Date: Thu, 14 Aug 2008 08:27:43 +0300 Subject: Installing gasp Message-ID: <1ee11ba30808132227i11a6e20dqeb9f0cb1a8b3bbfa@mail.gmail.com> Find attached a screen capture of the message I get. Thanks.. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: gasp_error.GIF Type: image/gif Size: 10857 bytes Desc: not available URL: From zondo42 at googlemail.com Fri Aug 29 15:12:09 2008 From: zondo42 at googlemail.com (Glenn Hutchings) Date: Fri, 29 Aug 2008 20:12:09 +0100 Subject: Process "Killed" References: <48a554c6-eeb3-4605-bdf2-a4b7de17bca3@b1g2000hsg.googlegroups.com> Message-ID: dieter writes: > I'm doing some simple file manipulation work and the process gets > "Killed" everytime I run it. No traceback, no segfault... just the > word "Killed" in the bash shell and the process ends. The first few > batch runs would only succeed with one or two files being processed > (out of 60) before the process was "Killed". Now it makes no > successful progress at all. Just a little processing then "Killed". > > Any Ideas? Is there a buffer limitation? Do you think it could be the > filesystem? > Any suggestions appreciated.... Thanks. > > The code I'm running: > ================== > > from glob import glob > > def manipFiles(): > filePathList = glob('/data/ascii/*.dat') > for filePath in filePathList: > f = open(filePath, 'r') > lines = f.readlines()[2:] > f.close() > f = open(filePath, 'w') > f.writelines(lines) > f.close() > print file Have you checked memory usage while your program is running? Your lines = f.readlines()[2:] statement will need almost twice the memory of your largest file. This might be a problem, depending on your RAM and what else is running at the same time. If you want to reduce memory usage to almost zero, try reading lines from the file and writing all but the first two to a temporary file, then renaming the temp file to the original: import os infile = open(filePath, 'r') outfile = open(filePath + '.bak', 'w') for num, line in enumerate(infile): if num >= 2: outfile.write(line) infile.close() outfile.close() os.rename(filePath + '.bak', filePath) Glenn From alan.franzoni.xyz at gmail.com Sat Aug 30 21:04:48 2008 From: alan.franzoni.xyz at gmail.com (Alan Franzoni) Date: Sun, 31 Aug 2008 01:04:48 GMT Subject: starting gazpacho on windows References: <48b95d18$0$7014$426a34cc@news.free.fr> Message-ID: <1r9si1lttzo47.1i5snd6ismpdr$.dlg@40tude.net> nntpman68 was kind enough to say: [cut] I didn't check, but if c:\python25 is your python install dir, you'll very likely find it in c:\python2.5\bin or c:\python25\scripts. -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From ironfroggy at gmail.com Wed Aug 13 11:38:11 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Wed, 13 Aug 2008 11:38:11 -0400 Subject: Why nested scope rules do not apply to inner Class? In-Reply-To: <74583B8642AB8841B30447520659FCA92CC054B5@dnce01.ent.ti.com> References: <74583B8642AB8841B30447520659FCA92CBAED95@dnce01.ent.ti.com> <76fd5acf0808120651u259e5d8dt32a8d49bb5d77add@mail.gmail.com> <200808122240.22517.maric@aristote.info> <76fd5acf0808121415h41cc580bj85d96e648c54ab4b@mail.gmail.com> <74583B8642AB8841B30447520659FCA92CC054B5@dnce01.ent.ti.com> Message-ID: <76fd5acf0808130838h6a2723a4me6cdfc42a89ca45a@mail.gmail.com> On Wed, Aug 13, 2008 at 11:32 AM, Cousson, Benoit wrote: >> Defining it as a nested class saves you one line >> of code, but IMHO makes the result just a bit more cluttered, while >> reducing the elegance of reusing the metaclass. > > The whole point of nested class is to avoid polluting the namespace with classes that are only used locally. So the argument about the elegance of reusing is not very valid in that case. There is no point of nested classes because nested classes _are not_ supported by python. They are simply an artifact of not actively denying the syntax non-globally. I would fully support a change to the language to actively forbid a class definition that is not module-level. > I agree that they are other ways using module to avoid namespace pollution, but in some case it is easier to use nested class instead and keep everything in the same file. I don't consider it pollution. If you want it considered "private" to the module, name it with an underscore. > In my case, I'm trying to use a similar approach as XIST's one, meaning using Python class to model hierarchical data. So clearly nested class is a very nice and easy understandable way to do that. I don't find that this is clear in anyway. I can't imagine why you'd think a nested class is even useful here, rather than an instance with some understandable attributes. I've seen a lot of places nested classes are used and not one of them that should be been doing it. But, on that note, there is a point where a discussion is obviously not going to resolve with either side changing their minds. This is obviously such a case. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy From joshbloom at gmail.com Tue Aug 12 19:04:54 2008 From: joshbloom at gmail.com (Josh Bloom) Date: Tue, 12 Aug 2008 16:04:54 -0700 Subject: Python + Some sort of Propel + Creole In-Reply-To: <65c3648d0808121518l76cb70e4i98587c0762e75bde@mail.gmail.com> References: <65c3648d0808121518l76cb70e4i98587c0762e75bde@mail.gmail.com> Message-ID: http://sqlobject.org/ http://www.sqlalchemy.org/ Django's built in ORM is also quite good for web development tasks. -josh On Tue, Aug 12, 2008 at 3:18 PM, Samuel Morhaim wrote: > Hi, I come from an extensive background developing webapps with Symfony... > Symfony uses Propel/Creole a lot. > > Is there something similar to Propel/Creole for Python? > > I found a few DB abstraction layers (Creole) but I am not sure which one is > the best.. can somebody point me to a good one? Also can somebody point me > to a good > object relational mapper? (Like Doctrine or Propel for php.. ? ) > > I am really just interested in: > -Being able to talk to sqlite, mysql and mssql. > -Being able to easily create DB schemas (Like done with propel in which you > use a YAML or XML file to specify a schema) > > > Thanks. > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cgrebeld at gmail.com Mon Aug 25 17:00:25 2008 From: cgrebeld at gmail.com (chris) Date: Mon, 25 Aug 2008 14:00:25 -0700 (PDT) Subject: How to get PyTypeObject from PyObject? Message-ID: <11602cd4-f5ff-42f1-b3de-ff1afdc0c91f@j1g2000prb.googlegroups.com> I want to check the type of an object, right now I am doing strcmp( object->ob_type->tp_name, "MyClass") Which seems slow, is there a way I can find the pointer to the global PyTypeObject for MyClass, and then just call PyObject_TypeCheck? Thanks From cvrebert+clp at gmail.com Thu Aug 28 15:32:03 2008 From: cvrebert+clp at gmail.com (Chris Rebert) Date: Thu, 28 Aug 2008 12:32:03 -0700 Subject: re.compile versus r'' In-Reply-To: <0bf4b8de-e11e-451c-8d18-58c1a4138375@e53g2000hsa.googlegroups.com> References: <0bf4b8de-e11e-451c-8d18-58c1a4138375@e53g2000hsa.googlegroups.com> Message-ID: <47c890dc0808281232q1bede29coc8733a0775e14681@mail.gmail.com> On Thu, Aug 28, 2008 at 12:23 PM, Terrence Brannon wrote: > Hello, I'm using a tool (PLY) which apparently expects the tokens to > be created using r'' > > But because one token is a rather complex regular expression, I want > to create the regular expression programmatically. > > How can I generate a string and then create something of the same type > that the r'' function does? The "r" prefix isn't a function or a type, it's merely a special literal syntax for strings that's handy when you're writing regexes and therefore have to deal with another level of backslash escaping. See the second to last paragraph of http://docs.python.org/ref/strings.html for more info. Regards, Chris > > Concretely, in the program below, consonant is not the same type as > t_NAME, but I assume that it needs to be for PLY to use it for > tokenizing: > > import re > > t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*' > > guttural = 'kh?|gh?|\"n' > palatal = '(?:chh?|jh?|\~n)' > cerebral = '\.(?:th?|dh?|n)' > dental = '(?:th?|dh?|n)' > semivowel = '[yrlv]' > sibilant = '[\"\.]?s' > aspirant = 'h' > > consonant = re.compile('|'.join([guttural , palatal , cerebral , > dental , semivowel , sibilant , aspirant])) > > print consonant > print t_NAME > -- > http://mail.python.org/mailman/listinfo/python-list > From atulskulkarni at gmail.com Fri Aug 8 06:56:24 2008 From: atulskulkarni at gmail.com (Atul.) Date: Fri, 8 Aug 2008 03:56:24 -0700 (PDT) Subject: regular expressions. Message-ID: <23cd7bec-264e-4a1d-a285-4683b48bf99d@a21g2000prf.googlegroups.com> Hey All, I have been playing around with REs and could not get the following code to run. import re vowel = r'[aeiou]' re.findall(vowel, r"vowel") anything wrong I have done? Regards, Atul. From twic at urchin.earth.li Thu Aug 14 12:09:26 2008 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 14 Aug 2008 17:09:26 +0100 Subject: strptime and timezones In-Reply-To: References: Message-ID: On Wed, 13 Aug 2008, Christian Heimes wrote: > Tom Anderson wrote: > >> Secondly, do you really have to do this just to parse a date with a >> timezone? If so, that's ridiculous. > > No, you don't. :) Download the pytz package from the Python package > index. It's *the* tool for timezone handling in Python. The time zone > definition are not part of the Python standard library because they > change every few of months. Stupid politicians ... My problem has absolutely nothing to do with timezone definitions. In fact, it involves less timezone knowledge than the time package supplies! The wonderful thing about RFC 1123 timestamps is that they give the numeric value of their timezone, so you don't have to decode a symbolic one or anything like that. Knowing about timezones thus isn't necessary. The problem is simply that the standard time package doesn't think that way, and always assumes that a time is in your local timezone. That said, it does look like pytz might be able to parse RFC 1123 dates. Ill check it out. tom -- Come on thunder; come on thunder. From paul.hankin at gmail.com Sat Aug 2 16:46:23 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 2 Aug 2008 13:46:23 -0700 (PDT) Subject: why goes the time change after import statement ? References: <011a92b4-b911-4f63-9339-be46b48d5f76@v1g2000pra.googlegroups.com> Message-ID: <6ae5acd5-3d5d-4e81-af2f-a32a9c833122@y38g2000hsy.googlegroups.com> On Aug 2, 10:35?pm, binaryjesus wrote: > hi i am working on a S3 project and facing a really weird problem! > take a look at the following import statements and the time output > > >>> import time > >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) > > 'Sat, 02 Aug 2008 20:21:56 GMT' > > # OK > > >>> import pygtk > >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) > > 'Sat, 02 Aug 2008 20:22:04 GMT' > > # OK > > >>> import gtk > >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) > > 'Sat, 02 Aug 2008 08:22:11 PM GMT' > > # HOW THE HELL THIS HAPPEN ??? not DATE_RFC2822 format gmt time ! Reading the manual page for strftime -- http://docs.python.org/lib/module-time.html -- says that '%X' is the locale's appropriate time representation, so obviously gtk is adjusting your locale. Perhaps use a formatting string that doesn't depend on the locale: '%H:%M:%S' instead of '%X' seems to give your preferred format. -- Paul Hankin From paul at boddie.org.uk Sat Aug 2 15:31:16 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 2 Aug 2008 12:31:16 -0700 (PDT) Subject: interpreter vs. compiled References: <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <4rl294duo83eujnq6tjbk215mavpl87o9r@4ax.com> <43f519dd-6763-4cc0-a6d2-1e671da54c2c@d45g2000hsc.googlegroups.com> <92716c9e-b940-453f-a817-1c95c00727d1@26g2000hsk.googlegroups.com> Message-ID: <5a7f3ab7-c71b-466f-a477-dfbdda582e46@m73g2000hsh.googlegroups.com> On 2 Aug, 08:33, castironpi wrote: > On Aug 1, 5:24 am, Paul Boddie wrote: > > > a + b # in Python > > > > ...is not sufficiently represented by... > > > > ldr r1, a > > ldr r2, b > > add r3, r1, r2 > > > > ...in some assembly language (and the resulting machine code), mostly > > because the semantics of Python addition are more complicated. > > No, it is not sufficiently represented. Python runs checks before and > after, to check for overflows. It does more than this... > test safeinteger a > test safeinteger b > ldr r1, a > ldr r2, b > add r3, r1, r2 > test not overflow > > However, no implementation of Python can do better, given Python's > specification. In fact, as was probably mentioned before, it does something more like this: get method __add__ on a (if possible) or jump to (1) populate an invocation frame with a and b call the method test the result against the special NotImplemented value if result is not NotImplemented then jump to (3) (1) get method __radd__ on b (if possible) or jump to (2) populate an invocation frame with b and a call the method test the result against the special NotImplemented value if result is not NotImplemented then jump to (3) (2) raise a TypeError exception (3) provide the result to whatever gets evaluated next The instructions that you list, which is based on the really simple case which I mentioned, happens in the method that gets called (eg. __add__), and then only for integers. Note that seemingly trivial things like getting the methods can be quite a few instructions in any low-level code. [...] > Another factor, a and b are known to be and are always integers, in a > given C context. > > int a, b; > ... > a + b > > The C compilation process outputs: > > ldr r1, a > ldr r2, b > add r3, r1, r2 Right. That's why some people want to have type declarations in Python, and others want to be able to generate specialised code at run- time for such cases. > and you are correct. However, for: > > string a, b; > a + b > > performs a concatenation which is not that simple. The point is, C > compilation runs, and you actually have -ldr, ldr, add- lying around > in a file somewhere, which can run as three consecutive instructions > on a processor. It's already in the interpreter in Python, and you > have the -test, test, ldr, ldr, add, test- sequence somewhere in > Python.exe, specifically wherever the object code for ceval.c is > going. Right. The way to think about this is that due to the mechanics of working out what kind of operations should be performed (should it be an integer addition, a string concatentation, something else?), there's a lot of code executed which is really "dancing around" the actual work, and then for short bursts of instructions, the work actually gets done. It's like having to jet around the world, sampling drinks in different locations, rather than just lining the different drinks up at home. Paul From jonmosco at gmail.com Sat Aug 9 15:32:41 2008 From: jonmosco at gmail.com (hypermonkey2) Date: Sat, 9 Aug 2008 12:32:41 -0700 (PDT) Subject: "shelve" save object Message-ID: <46f0f2bd-4267-4dc8-ad8c-4a6c0b05878d@d45g2000hsc.googlegroups.com> Hi there! I am using the "shelve" module in a script to save information in between runtime sessions of the program. (its a sort of data collector, so its important to hold on to anything computed ). In any case, I shelve into a file "test.txt". I notice that when i try running the program on a different computer (by either emailing or transfering the file "test.txt" via USB key), the program is unable to load the shelve file. What can I do to fix this? It would be a great shame to see that after collecting all this information and shelving it that I cannot move to another computer or share the information through the "save.txt" file. Thanks in advance! Jon From aaron.hildebrandt at gmail.com Mon Aug 18 12:16:13 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Mon, 18 Aug 2008 09:16:13 -0700 (PDT) Subject: mod_python and updated files Message-ID: I have mod_python running on my server, but when I chance a Python file on the server, Apache needs to be restarted in order to have the changes take effect. I assume this is so mod_python can run persistently, but it's becoming quite a headache for development. Is there a way to turn off the persistence, or a way to force mod_python to compile and run the new version of the file? From peter.anderson at internode.on.net Fri Aug 8 01:58:57 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Fri, 08 Aug 2008 15:58:57 +1000 Subject: very newbie question Message-ID: <489BE0A1.8020202@internode.on.net> Try this: # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money import random print "\tWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 100." print "Try to guess it in as few attempts as possible.\n" # set the initial values the_number = random.randrange(100) + 1 tries = 0 def ask_number(): guess = int(raw_input("Take a guess: ")) tries = 1 while (guess != the_number): if (guess > the_number): print "Lower..." else: print "Higher..." tries += 1 guess = int(raw_input("Take a guess: ")) tries += 1 ask_number() print "You guessed it! The number was", the_number print "And it only took you", tries, "tries!\n" raw_input("\n\nPress the enter key to exit.") The variables "the_number" and "tries" were not available outside the "ask_number()" module. Alternatively drop the def function and lump it all into a simple script. -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From sjmachin at lexicon.net Wed Aug 20 06:43:08 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 20 Aug 2008 03:43:08 -0700 (PDT) Subject: Basic importing question References: Message-ID: On Aug 20, 8:08?pm, Hussein B wrote: > Hey, > Suppose I have a Python application consists of many modules (lets say > it is a Django application). > If all the modules files are importing sys module, how many times the > sys module will be compiled and executed? > Only once (the first time the PVM locates, compiles and executes the > sys module)? or once for each module importing sys? > Thanks. sys is a built-in module, so the answer is zero times. For a non-builtin module foo where there exists: (1) only a foo.py, it will be compiled into foo.pyc (2) only a foo.pyc, it will be used (3) both a foo.py and a foo.pyc, Python compiles the foo.py if the pyc is out of date or (so I believe [*]) was created by a different version of Python. Subsequent imports will use the in-memory copy (in sys.modules, IIRC [*]) ... [*] == Please save me the bother of checking this in the manual :-) HTH, John From exarkun at divmod.com Thu Aug 14 10:36:45 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 14 Aug 2008 10:36:45 -0400 Subject: Trying ZODB, background in Relational: mimic auto_increment? In-Reply-To: <6git1dFfta1fU1@mid.uni-berlin.de> Message-ID: <20080814143645.29191.298476970.divmod.quotient.14347@ohm> On Thu, 14 Aug 2008 16:15:11 +0200, "Diez B. Roggisch" wrote: >Jean-Paul Calderone wrote: > >> On Thu, 14 Aug 2008 05:22:35 -0700 (PDT), Phillip B Oldham >> wrote: >>> [snip] >>> >>>How would one assign a unique ID to the root at that point? >> >> Here's one way >> >> class Sequence(Persistence): >> def __init__(self): >> self.current = 0 >> >> def next(self): >> self.current += 1 >> return self.current >> >> ticketSequence = Sequence() >> >> class Ticket(Persistence): >> def __init__(self): >> self.id = ticketSequence.next() > >Be aware that this isn't working concurrently. Depending on your >application, this can be mitigated using a simple threading.Lock. > ZODB has transactions. That's probably the best way to make this code safe for concurrent use. A threading.Lock would make threaded use safe, but wouldn't give you multiprocess concurrency safety. Jean-Paul From smbaker at gmail.com Tue Aug 12 20:02:51 2008 From: smbaker at gmail.com (Scott) Date: Tue, 12 Aug 2008 17:02:51 -0700 (PDT) Subject: passing a variable argument list to a function Message-ID: I'm trying to write a function that accepts a variable number of arguments and passes those arguments to another function. Here is an example: def foo(*args): print "I'm going to call bar with the arguments", args bar(args) This doesn't do quite what I want. For example, if I call foo(1,2,3,4) then it calls bar((1,2,3,4)). It passes a tuple rather than expanding the argument list back out. I suspect there's a simple bit of syntax that I'm missing -- can anyone give me a hand? Thanks Scott From see.signature at no.spam Thu Aug 14 05:01:32 2008 From: see.signature at no.spam (Eric Brunel) Date: Thu, 14 Aug 2008 11:01:32 +0200 Subject: Tkinter updates - Easiest way to install/use Tile? References: Message-ID: On Wed, 13 Aug 2008 19:10:47 +0200, Mudcat wrote: [snip] > I was reading about Tile, and it sounds like I should be able to wrap > a style around my current code to give it a different look. However it > doesn't sound like it's quite ready for prime time yet. I downloaded > the latest stable version of Python 2.5 which apparently still uses > Tcl 8.4. So my options at this point appear to be: > > 1) Download beta version of Python 2.6 which has Tcl 8.5. > Tile is supposed to be included with Tcl 8.5, but there's not much > information on how to use it with older code. Do I still need wrapper > code, or if I install 2.6 will it be available already. Well, if you do it today and look in the Lib/lib-tk directory, you'll see that there is nothing specific to Tile/ttk in any of the module. So ATM, new wrappers are needed indeed. If I had to say which wrappers have the best chance to actually become "official", I'd bet on Guilherme Polo's ones here: http://gpolo.ath.cx:81/projects/ttk_to_tkinter/ These seem to be the most complete, and somebody's actually working on them. > 2) Install Tcl 8.5 to use with Python 2.5. > How do you do this? In other posts it mentions recompiling source tcl > code with Python. If that's the case it doesn't sound like something I > want to mess with. If I stray too far from default configurations I > start to have problems with py2exe. I guess it would probably be better to at least recompile the _tkinter.c module to get the new tcl/tk header files. I think I also read somewhere that there were API incompatibilities between tcl/tk 8.4 and 8.5. Don't know if it has any impact on Tkinter. > 3) Install Tile with Python 2.5 and Tcl 8.4 and use wrapper code to > make it work. > However all the posts concerning this approach assume that Tile is > already installed. I downloaded the code for the latest version of > Tile which was a .kit extension. This also may need to be compiled, > and if that's the case I again start to have problems with freezing my > application. This doesn't look like the way to go for me: you'll add the burden of having to install the Tile package at tcl/tk level while not gaining anything, since you'll still have to use wrappers that may or may not be official in the end. > What's the easiest way to do this? I really couldn't find a place that > gave instructions for any of the current release configurations. It > sounds if it's available already in Python 2.6 that it would be the > easiest way, but I couldn't find any threads talking about the > availability of it for that release yet. As I said above, if I had to choose today, I'd go Python 2.6 + tcl/tk 8.5 + Guilherme Polo's ttk wrappers. But if you can do it, I'd say: just wait. Things are moving fast: the latest Python 2.6 beta release is less than a month old, and Guilherme Polo has marked his ttk wrappers project as complete only 3 days ago. So maybe the next Python beta will actually include them... And BTW, the final release for Python 2.6 is planned at the beginning of October, so this is not that far away. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From __peter__ at web.de Fri Aug 15 05:35:32 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 15 Aug 2008 11:35:32 +0200 Subject: getattr nested attributes References: Message-ID: Gregor Horvath wrote: > Peter Otten schrieb: > >> make your own function that loops over the attributes, or spell it >> >>>>> reduce(getattr, "a.test".split("."), B) >> 'test' >> > > Thank's, but this does not work for this case: > > class A(object): > test = "test" > > class B(object): > a = [A(),] > > In [70]: reduce(getattr, "a[0].test".split("."), B) > --------------------------------------------------------------------------- > Traceback (most recent call > last) > > / in () > > : type object 'B' has no attribute > 'a[0]' Like the screwdriver doesn't work with a nail? > Seems that I have to use eval ? > I have a mapping text file (data) which contains such attributes strings > and those attributes should be read. When you pass data to eval() it becomes code. If you trust the source of that text file that would be the easiest approach. Otherwise google for 'safe eval'. Peter From byte8bits at gmail.com Wed Aug 27 14:38:55 2008 From: byte8bits at gmail.com (brad) Date: Wed, 27 Aug 2008 14:38:55 -0400 Subject: Python multimap In-Reply-To: <4d2f1ac5-c21c-42d9-977e-6493f0c23573@d77g2000hsb.googlegroups.com> References: <4d2f1ac5-c21c-42d9-977e-6493f0c23573@d77g2000hsb.googlegroups.com> Message-ID: castironpi wrote: > I don't understand what a multimap does that a map of lists doesn't do. It counts both keys individually as separate keys. The Python workaround does not... see examples... notice the key(s) that are '4' Python output (using the k = [] idea): Key: 4 Value: [[13, 'Visa'], [16, 'Visa']] Key: 51 Value: [16, 'MC'] Key: 65 Value: [16, 'Discover'] Key: 2131 Value: [15, 'JCB'] Key: 300 Value: [14, 'Diners CB'] Key: 301 Value: [14, 'Diners CB'] Key: 302 Value: [14, 'Diners CB'] Key: 303 Value: [14, 'Diners CB'] Key: 304 Value: [14, 'Diners CB'] Key: 305 Value: [14, 'Diners CB'] Key: 35 Value: [16, 'JCB'] Key: 34 Value: [15, 'Amex'] Key: 55 Value: [16, 'MC or Diners US and CA'] Key: 36 Value: [14, 'Diners Intl'] Key: 37 Value: [15, 'Amex'] Key: 1800 Value: [15, 'JCB'] Key: 54 Value: [16, 'MC'] Key: 6011 Value: [16, 'Discover'] Key: 52 Value: [16, 'MC'] Key: 53 Value: [16, 'MC'] Key: 385 Value: [14, 'Diners CB'] 21 is the size of the dict A C++ multimap Key: 1800 Value: JCB 15 Key: 2131 Value: JCB 15 Key: 300 Value: Diners_Club 14 Key: 301 Value: Diners_Club 14 Key: 302 Value: Diners_Club 14 Key: 303 Value: Diners_Club 14 Key: 304 Value: Diners_Club 14 Key: 305 Value: Diners_Club 14 Key: 34 Value: American_Express 15 Key: 35 Value: JCB 16 Key: 36 Value: Diners_Club 14 Key: 37 Value: American_Express 15 Key: 385 Value: Diners_Club 14 Key: 4 Value: Visa 16 Key: 4 Value: Visa 13 Key: 51 Value: MasterCard 16 Key: 52 Value: MasterCard 16 Key: 53 Value: MasterCard 16 Key: 54 Value: MasterCard 16 Key: 55 Value: MasterCard 16 Key: 6011 Value: Discover 16 Key: 65 Value: Discover 16 22 is the size of the multimap From benjamin.kaplan at case.edu Thu Aug 28 00:33:48 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 28 Aug 2008 00:33:48 -0400 Subject: [Q] How to ignore the first line of the text read from a file In-Reply-To: References: Message-ID: On Thu, Aug 28, 2008 at 12:11 AM, youngjin.michael at gmail.com < youngjin.michael at gmail.com> wrote: > Hello, > > I am new to Python and have one simple question to which I cannot find > a satisfactory solution. > I want to read text line-by-line from a text file, but want to ignore > only the first line. I know how to do it in Java (Java has been my > primary language for the last couple of years) and following is what I > have in Python, but I don't like it and want to learn the better way > of doing it. > > file = open(fileName, 'r') > lineNumber = 0 > for line in file: > if lineNumber == 0: > lineNumber = lineNumber + 1 > else: > lineNumber = lineNumber + 1 > print line > > Can anyone show me the better of doing this kind of task? > > Thanks in advance. > > -- Files are iterators, and iterators can only go through the object once. Just call next() before going in the for loop. Also, don't use "file" as a variable name. It covers up the built-in type. afile = open(file_name, 'r') afile.next() #just reads the first line and doesn't do anything with it for line in afile : print line > > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bhood2 at comcast.net Tue Aug 26 10:41:42 2008 From: bhood2 at comcast.net (bhood2 at comcast.net) Date: Tue, 26 Aug 2008 08:41:42 -0600 Subject: Need help with extension modules built in debug mode References: Message-ID: On Tue, 26 Aug 2008 08:20:44 +0200, Fredrik Lundh wrote: >bhood2 at comcast.net wrote: > >> I've come to the conclusion that posting about Embedded Python on the >> Python forums is a complete waste of time. I hope I can get some >> useful insights here. > >(just curious, but what are the "Python forums"? isn't the >newsgroup/mailing list *the* Python forum?) http://python-forum.org/pythonforum/index.php From ce at mail.net.sk Wed Aug 13 01:08:56 2008 From: ce at mail.net.sk (Mahdi) Date: Wed, 13 Aug 2008 13:08:56 +0800 Subject: Python web framework choice Message-ID: Guys! I need to develop a medium-sized database web application for my company. Given that: I don't know much about building web UI(s) but i have fair knowledge about HTML & My schedule is tight. a recommendation is v v v appreciated. thanks! From anishchapagain at gmail.com Mon Aug 4 09:27:51 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Mon, 4 Aug 2008 06:27:51 -0700 (PDT) Subject: Wrapping C API References: <24f5104e-b89a-4351-880b-7cdc7c04631c@z66g2000hsc.googlegroups.com> Message-ID: <29ee7157-bc9b-4dca-b1db-02cf67a996e9@79g2000hsk.googlegroups.com> On 4 Aug, 14:20, Ulrich Eckhardt wrote: > Anish Chapagain wrote: > > I'm new to python and have a task for Wrapping up an old program > > written in C(20.c files), to provide GUI and chart,graph feature in > > Python. I've tried using SWIG but am not getting well in windows > > system, wish to receive guidelines for initiating the task... > > Two ways come to mind: > 1. ctypes > 2. popen > > The former is basically an interface to the C language types which makes it > rather easy to load C DLLs and call functions therein. The latter is a way > to start a program with redirected input and output, something that can be > used to remote-control any commandline application. > > Uli > > -- > Sator Laser GmbH > Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 For, plotting chart and graph through C, dll in pyhton will ctype be more easy.. if there any example would like to see once.. thank's From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 19 07:38:09 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 19 Aug 2008 13:38:09 +0200 Subject: Handling Property and internal ('__') attribute inheritance and creation In-Reply-To: References: Message-ID: <48aab09b$0$6986$426a74cc@news.free.fr> Fredrik Lundh a ?crit : > Eric Brunel wrote: > >> To add to what others have already said, it is not only 'just extra >> work', it is also quite dangerous. See: >> >> class A(object): >> children = [] > > the OP is aware of that, of course: > > > I set anything that is constant but anything variable is set again in > > __init__() > > as long as if you're aware of the issues involved (which you should be > if you're using Python professionally), using class-level attributes is > a perfectly valid Python style. Using class attributes is perfectly valid Python style, indeed. But in this case - ie: using class attributes as a pseudo-declaration of instance attributes -, I would not call this good style : it's a waste of time, a violation of DRY, and a potential source of confusion for the class's users / maintainers. From castironpi at gmail.com Wed Aug 13 18:21:25 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 13 Aug 2008 15:21:25 -0700 (PDT) Subject: Inquisitive computing References: <41264be6-3dae-4ca3-ab6f-aba20130a0c1@l42g2000hsc.googlegroups.com> Message-ID: <14334770-fb04-485a-a701-2dba1fc1ea6a@m36g2000hse.googlegroups.com> On Aug 13, 4:29?pm, bearophileH... at lycos.com wrote: > David C. Ullrich: > > > If you look at the end of the article you see the author > > agrees (I don't quite follow his complaint about not feeling > > at home with the interactive mode, but it's funny to read about > > how he uses Lisp but realizes he's not going to talk people > > into that...) > > That well know author thinks Python is almost fit, but not quite (no > rationals, he seems to not like imports, and he wants optional types, > and native compilation performance too, etc), and I think he likes > Scheme a lot (not right CLisp). You may want to take a look at the > article to see if I am right. > > Bye, > bearophile He didn't mention a debugger, which Python does have. But in mentioning Python he didn't distinguish between the live interpreter console and executing a script. Also, the idea of language- independent editor isn't explored; they're too closely coupled. (Except maybe Bloodshed Dev, which has a Tools menu, you can customize to say \python\python %curfile%.) From gh at ghaering.de Mon Aug 18 07:33:48 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 18 Aug 2008 13:33:48 +0200 Subject: SQLite's default ON CONFLICT algorithm In-Reply-To: <20080818102428.GA6049@hccnet.nl> References: <20080818102428.GA6049@hccnet.nl> Message-ID: egbert wrote: > Yes, I know that this is off-topic, but I feel justified by sqlite3 > being a builtin. > > The default ON CONFLICT algorithm in SQLite is ABORT. > The SQLite documentation ("ON CONFLICT clause") says that when > a constraint violation occurs under ABORT, no rollback is executed, > so changes from prior commands within the same transaction are > preserved. > Isn't this a strange choice for a default ? No, it's just like every other database error - the command fails but the connection is left untouched. > After all, you expect that either all changes within a transaction > are preserved, or that nothing at all is preserved. Sure, the successful ones ;-) > The Python Library Reference on sqlite3 says in paragraph 13.13.5 > that I should not use the ROLLBACK conflict algorithm in my sql. > Instead I have to catch the IntegrityError and call the rollback method. FWIW, this restriction is not any longer true in Python 2.6 and 3.0 btw. You can now safely use "ON CONFLICT ROLBLACK" with the sqlite3 module. > Does that mean that I have to wrap all multi-command transactions > in a try-except if I don't like the default ABORT choice ? Well, you have to do that *always* anyways if you want your app to behave correctly. Typical usage of the DB-API looks like this: cur = con.cursor() try: cur.execute(...) cur.execute(...) cur.execute(...) con.commit() except .DatabaseError: con.rollback() With the sqlite3 module, there's a shortcut: from __future__ import with_statement with con: cur.execute(...) cur.execute(...) cur.execute(...) which does exactly the same as the code above. -- Gerhard From aahz at pythoncraft.com Wed Aug 13 11:11:05 2008 From: aahz at pythoncraft.com (Aahz) Date: 13 Aug 2008 08:11:05 -0700 Subject: dict.update() useful or not? References: <00b06f78$0$14351$c3e8da3@news.astraweb.com> Message-ID: In article <00b06f78$0$14351$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > >What do other people find? Do you find use for dict.update()? What other >idioms do you use for combining dictionaries? My company's code relies heavily on d.update() -- it's extremely handy in the context of a web form. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From rhamph at gmail.com Fri Aug 1 18:06:15 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Fri, 1 Aug 2008 15:06:15 -0700 (PDT) Subject: when does the GIL really block? References: Message-ID: <8894ad9e-cac5-43b2-80cc-7b605de6866a@v8g2000prm.googlegroups.com> On Jul 31, 7:27?pm, Craig Allen wrote: > I have followed the GIL debate in python for some time. ?I don't want > to get into the regular debate about if it should be gotten rid of > (though I am curious about the status of that for Python 3)... > personally I think I can do multi-threaded programming well, but I > also see the benefits of a multiprocess approach. I'm not so > egotistical that I don't realize perhaps my mt programming has not > been "right" (though it worked and was debuggable) or more likely that > doing it right I have avoided even trying some things people want mt > programming to do... i.e. to do mt programming right you start to use > queues a lot, inter-threadasynchronous, non-blocking, communication, > which is essentially the multi-process approach, using IPC (except > that thethreads can see the same memory when, in your special case, > you know that's ok. Given something like a reader-writer lock, this > can have benefits... but again, whatever. > > My question is that given this problem, years ago before I started > writing in python I wrote some short programs in python which could, > in fact, busy both my CPUs. ?In retrospect I assume I did not have > code in my run function that causes a GIL lock... so I have done this > again. > > I start twothreads... I use gkrellm to watch my processors (dual > processor machine). ?If I merely print a number... both CPUS are > getting 90% simultaneous loads. If I increment a counter and print it > too, the same, and if I create a small list and sort it, the same. I > did not expect this... I expected to see one processor pegged at > around 100%, which should sometimes switch to the other processor. > Granted, the same program in C/C++ would peg both processors at > 100%... but given that the overhead in the interpreter cannot explain > the extra usage, I assume the code in mythread's run functions is > actually executing non-serially. Try using sys.setcheckinterval(10000) (or even larger), overriding the default of 100. This will reduce the locking overhead, which might by why you see both CPUs as busy. > I assume this is because what I am doing does not require the GIL to > be locked for a significant part of the time my code is running... > what code could I put in my run function to see the behavior I > expected? ?What code could I put there to take advantage of the > possibility that really the GIL is not locked enough to cause actual > serialization of thethreads... ?anyone care to explain? The GIL is locked during *all* access to the python interpreter. There's nothing pure python code can do to avoid it - only a C extension that doesn't access python could. From harrrrpo at gmail.com Sat Aug 23 20:27:46 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Sun, 24 Aug 2008 03:27:46 +0300 Subject: Imports visibility in imported modules problem Message-ID: <538050a90808231727w63b78c48ueefaf37ec864e72e@mail.gmail.com> Hello , The problem I'm asking about is how can imported modules be aware of other imported modules so they don't have to re-import them (avoiding importing problems and Consicing code and imports ) Take Example :- in A.py :- import B print dir() # no problems we can see B which contain re module and C module B.C.W() # our problem here we get an empty list in B.py :- import re import C in C.py :- def W(): print dir() # when called from A we get [] though other imports has been made to re and others my goal is basically making W() aware of the re module when called from A ---- why am i doing this in the first place I'm in the process of a medium project where imports of modules start to make a jungle and i wanted all needed imports to be in a single file (namely __init__.py) and then all imports are made once and other modules feel it another reason to do this that my project is offering 2 interfaces (Console and GUI through Qt) and i needed a general state class ( whether i'm in Console or GUI mode) to be available for all , for determining state and some public functions ,and just injecting Imports everywhere seems a bad technique in many ways (debugging , modifying ...etc ) in PHP "Require" would do the trick neatly ... so is there is something I'm missing here or the whole technique is bad in which case what do you suggest ? Thanks, Regards, Mohamed Yousef From hv at tbz-pariv.de Thu Aug 14 10:41:57 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Thu, 14 Aug 2008 16:41:57 +0200 Subject: Trying ZODB, background in Relational: mimic auto_increment? In-Reply-To: References: Message-ID: <6giuhlFfvq3kU1@mid.individual.net> auto increment: > Here's one way > > class Sequence(Persistence): > def __init__(self): > self.current = 0 > > def next(self): > self.current += 1 > return self.current > > ticketSequence = Sequence() > > class Ticket(Persistence): > def __init__(self): > self.id = ticketSequence.next() > I am sorry, but this does not work if several threads or processes try to get a new id. Have a look at: http://www.zope.org/Documentation/Books/ZDG/current/Persistence.stx "Resolving Conflicts". BTW, that's one of the points why I switched from ZODB to Postgres. HTH, Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From vinay_sajip at yahoo.co.uk Wed Aug 27 09:30:25 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 27 Aug 2008 06:30:25 -0700 (PDT) Subject: logging exceptions References: <3c8c0b98-54ea-4112-8db9-e0040929e558@w1g2000prk.googlegroups.com> <200e9b4d-c062-4984-bcec-581666458071@79g2000hsk.googlegroups.com> <1868e033-8313-414c-a82a-35a8852ffb77@v57g2000hse.googlegroups.com> Message-ID: <6938d476-2eb7-4cfb-b3d4-b8f2f6cd45fc@w7g2000hsa.googlegroups.com> On Aug 27, 10:30 am, Rob Wolfe wrote: > Vinay Sajip napisa?(a): > > > > > On Aug 26, 10:36 am, Alexandru Mosoi wrote: > > > why doesn'tloggingthrow any exception when it should? how do I > > > configureloggingto throw exceptions? > > > > >>> try: > > > > ... logging.fatal('asdf %d', '123') > > > ... except: > > > ... print 'this line is never printed' > > > ... > > > Traceback (most recent call last): > > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > > python2.5/logging/__init__.py", line 744, in emit > > > msg = self.format(record) > > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > > python2.5/logging/__init__.py", line 630, in format > > > return fmt.format(record) > > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > > python2.5/logging/__init__.py", line 418, in format > > > record.message = record.getMessage() > > > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > > > python2.5/logging/__init__.py", line 288, in getMessage > > > msg = msg % self.args > > > TypeError: int argument required > > > Was your traceback from the snippet you posted? If it was, then the > > exception (a TypeError) *is* being raised fromlogging. So I don't > > understand your question "why doesn'tloggingthrow any exception when > > it should?", becauseloggingis raising an exception here. > > No, it isn't. > This traceback is *printed* in `Handler.handleError` method: > You're right - silly me. I wasn't paying attention :-( > > variable would normally be set to 0 in a production environment, where > > you don't wantlogging-related exceptions to bring an application > > down. > > Well, I think that it will not help. The exception will be printed > not raised. The only solution is to redefine `handleError` method > or maybe I've missed something? > No, you're right. To do custom handling of exceptions, handleError needs to be overridden. Regards, Vinay From rafesacks at gmail.com Fri Aug 15 11:40:31 2008 From: rafesacks at gmail.com (Rafe) Date: Fri, 15 Aug 2008 08:40:31 -0700 (PDT) Subject: Passing an object through COM which acts like str but isn't References: <3c632ccb-2fb0-436f-ae7f-b2c3ae5c803f@s1g2000pra.googlegroups.com> Message-ID: <7256565d-f8a1-4e47-91de-cd86ec5b31b5@v13g2000pro.googlegroups.com> On Aug 15, 10:27 pm, Wolfgang Grafen wrote: > Rafe schrieb: > > > Forgive me if I mangle any terminology here, but please correct me if > > I do... > > > I have an object which acts exactly like a string as long as I stay in > > Python land. However, I am using the object in Softimage|XSI, a 3D > > application on Windows. I'm getting variant erros when trying to use > > my instances as I would a string. > > > XSI was created while (briefly) owned by Microsoft, so knowledge of > > COM with excel, or anything else, should be applicable I should think. > > I should also say I am a COM novice and still learning the depths of > > Python. > > > Here is an example... > > > class StrLike(object): > > def __init__(self, s): self.__data = s > > def __repr__(self): return repr(self.__data) > > def __cmp__(self, string): return cmp(self.__data, string) > > def __contains__(self, char): return char in self.__data > > > __data = "" > > def __Set(self, value): self.__data = value > > def __Get(self): return self.__data > > data = property(fget = __Get, > > fset = __Set, > > fdel = None, > > doc = "string-like example") > > >>>> s = StrLike("test") > >>>> s > > 'test' > >>>> if s == "test": print "cmp works" > > cmp works > > > Now if I try to pass this as I would a string, roughly like so... > >>>> s = StrLike("test") > >>>> Application.AnObject.attribute = "test" # works fine > >>>> Application.AnObject.attribute = s > > ERROR : Traceback (most recent call last): > > File "