From steve at holdenweb.com Mon Jul 24 16:09:24 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 24 Jul 2006 21:09:24 +0100 Subject: Nested function scope problem In-Reply-To: <1153770716.448167.103980@b28g2000cwb.googlegroups.com> References: <1153526722.757378.144130@m73g2000cwd.googlegroups.com> <44c278d5$0$13474$636a55ce@news.free.fr> <1153677213.718927.315780@s13g2000cwa.googlegroups.com> <1153770716.448167.103980@b28g2000cwb.googlegroups.com> Message-ID: danielx wrote: > Gerhard Fiedler wrote: [...] >>Yes, but it is the line "tok = ''" that seems to cause tok to be now a >>variable of the inner function's scope (rather than the variable tok of >>breakLine). > > > OHH! Yes, that sounds like it could be it. Wow, to me, that behavior is > eXtremely unexpected (there's lisp popping up its ugly head again :P). > So you're saying that because an assignment to tok appears later within > the def for addTok, that the line if len(tok) won't try to look in > enclosing local scopes? (If such things even exist...) > > Gerhard's reply sounded not so confident. Can we have someone who > "really" knows weigh in on this? Thanks! > Would I do? If there's a binding to a name *anywhere* in the function's body then that name is treated as local to the function. This is a matter of static analysis, and is irrespective of where in the body the assignment is found. Of course, you could always test this yourself in interactive mode ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From pmartin at snakecard.com Sun Jul 30 18:48:01 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sun, 30 Jul 2006 17:48:01 -0500 Subject: BCD List to HEX List References: <5S8zg.1553$W93.658@dukeread05> <7xbqr6lp9e.fsf@ruckus.brouhaha.com> <7x8xmavhj3.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Philippe Martin writes: >> I'm just using Python to prototype, so I cannot use any of these great >> features of the language. > > I think when writing a prototype, you should use whatever features you > want, except maybe at the upper levels of program organization. The > idea of prototyping is to get something done quickly, that you can use > for integration and user testing earlier in the development cycle. So > you should use whatever Python features are available to make > prototyping faster. You shouldn't expect the prototype code to > closely match the final C code, if that slows you down. If you want > code that closely resembles C code, you might as well write in C > directly. Some truth in that. Thanks, Philippe From heuristic at gmail.com Mon Jul 3 08:41:24 2006 From: heuristic at gmail.com (Alex Biddle) Date: Mon, 3 Jul 2006 13:41:24 +0100 Subject: Out of the box database support Message-ID: <45e0ec7b0607030541r72730360u805041634101878e@mail.gmail.com> Hey there. I was wondering whether Python had any support out-of-the-box for database functionality, or database-like functionality. For instance a lot of shared hosts have Python installed, but not the MySQL extension, the flexible of these would install it, but most of the time they wouldn't bother. I was really looking for something like SQLite which ships bundled with PHP these days. Or any standard way of connecting to generic databases out of the box, i.e. MySQL. Thanks for reading. Alex Biddle. From mail at microcorp.co.za Fri Jul 28 02:40:24 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Fri, 28 Jul 2006 08:40:24 +0200 Subject: Threads vs Processes References: <1153970008.204968.325450@i3g2000cwc.googlegroups.com> Message-ID: <000301c6b213$84f04760$03000080@hendrik> "Dennis Lee Bieber" Wrote: | On Thu, 27 Jul 2006 09:17:56 -0700, "Carl J. Van Arsdall" | declaimed the following in comp.lang.python: | | > Ah, alright, I think I understand, so threading works well for sharing | > python objects. Would a scenario for this be something like a a job | > queue (say Queue.Queue) for example. This is a situation in which each | > process/thread needs access to the Queue to get the next task it must | > work on. Does that sound right? Would the same apply to multiple | > threads needed access to a dictionary? list? | > | Python's Queue module is only (to my knowledge) an internal | (thread-shared) communication channel; you'd need something else to work | IPC -- VMS mailboxes, for example (more general than UNIX pipes with | their single reader/writer concept) | | > "shared memory" mean something more low-level like some bits that don't | > necessarily mean anything to python but might mean something to your | > application? | > | Most OSs support creation and allocation of memory blocks with an | attached name; this allows multiple processes to map that block of | memory into their address space. The contents of said memory block is | totally up to application agreements (won't work well with Python native | objects). | | mmap() | | is one such system. By rough description, it maps a disk file into a | block of memory, so the OS handles loading the data (instead of, say, | file.seek(somewhere_long) followed by file.read(some_data_type) you | treat the mapped memory as an array and use x = mapped[somewhere_long]; | if somewhere_long is not yet in memory, the OS will page swap that part | of the file into place). The "file" can be shared, so different | processes can map the same file, and thereby, the same memory contents. | | This can be useful, for example, with multiple identical processes | feeding status telemetry. Each process is started with some ID, and the | ID determines which section of mapped memory it is to store its status | into. The controller program can just do a loop over all the mapped | memory, updating a display with whatever is current -- doesn't matter if | process_N manages to update a field twice while the monitor is | scanning... The display always shows the data that was current at the | time of the scan. | | Carried further -- special memory cards can (at least they were | where I work) be obtained. These cards have fiber-optic connections. In | a closely distributed system, each computer has one of these cards, and | the fiber-optics link them in a cycle. Each process (on each computer) | maps the memory of the card -- the cards then have logic to relay all | memory changes, via fiber, to the next card in the link... Thus, all the | closely linked computers "share" this block of memory. This is nice to share inputs from the real world - but there are some hairy issues if it is to be used for general purpose consumption - unless there are hardware restrictions to stop machines stomping on each other's memories - i.e. the machines have to be *polite* and *well behaved* - or you can easily have a major smash... A structure has to agreed on, and respected... - Hendrik From valpassing at gmail.com Mon Jul 3 05:57:53 2006 From: valpassing at gmail.com (valpa) Date: 3 Jul 2006 02:57:53 -0700 Subject: Can I do it using python?? about xterm and telnet In-Reply-To: <1151916458.336659.66960@75g2000cwc.googlegroups.com> References: <1151814697.201988.17140@b68g2000cwa.googlegroups.com> <12af5sncaj7m62d@corp.supernews.com> <1151843919.160078.263450@j8g2000cwa.googlegroups.com> <1151916458.336659.66960@75g2000cwc.googlegroups.com> Message-ID: <1151920673.305615.187210@m79g2000cwm.googlegroups.com> I don't care about security issue by now :), because every one in my compony know the username/password. It's a shared password. I just want to login into Unix boxes in an efficiently. so I needn't open a xterm console and type telent ..... usr/pwd for a unix box, and open another xterm, type telnet ...usr/pwd, and so on... Nicko wrote: > placid wrote: > > Jim Segrave wrote: > > > In article <1151814697.201988.17140 at b68g2000cwa.googlegroups.com>, > > > valpa wrote: > > > >I'm a net admin for about 20 unix servers, and I need to frequently > > > >telnet on to them and configure them. > > > >It is a tiring job to open a xterm and telnet, username, password to > > > >each server. > > > > > > Don't use telnet. it's clumsy and has security issues. > > > > if youre behind a firewall then it shouldnt matter. > > No, no, no! If you have 20 unix servers then this is likely not a tiny > company. Most security breaches (according to the FBI/CSI computer > crime survey) are perpetrated by insiders. If you log in using telnet, > and have to enter passwords that allow configurations to be changed, > then anyone on the local net can get those passwords. Use SSH instead. > Even SSH with passwords is hugely more secure than telnet. > > Nicko From rdjdvd at inwind.it Tue Jul 4 11:09:19 2006 From: rdjdvd at inwind.it (.) Date: 4 Jul 2006 08:09:19 -0700 Subject: For a fast implementation of Python In-Reply-To: References: <1151914453.568218.32920@j8g2000cwa.googlegroups.com> Message-ID: <1152025758.451448.69410@75g2000cwc.googlegroups.com> Hi Terry. I see: http://codespeak.net/pypy/dist/pypy/doc/news.html "...by translating RPython to Javascript..." It isn't an implementation. -- JavaScript implementation of Python http://groups.google.it/group/JSython/ Terry Hancock ha scritto: > . wrote: > > > What is the fast way for a fast implementation of Python? > > > > -- JavaScript implementation of Python > > http://groups.google.it/group/JSython/ > > Follow the PyPy link. The other replies were about increasing > execution speed, not ease of implementation. > > Implement the "RPython" part in Javascript, then use > the PyPy project to fill in the rest? That way, you don't > even have to maintain most of it. > > http://codespeak.net/pypy/dist/pypy/doc/news.html > > Cheers, > Terry > > > -- > Terry Hancock (hancock at AnansiSpaceworks.com) > Anansi Spaceworks http://www.AnansiSpaceworks.com From faisjobs at yahoo.co.in Mon Jul 3 09:12:37 2006 From: faisjobs at yahoo.co.in (faisjobs) Date: 3 Jul 2006 06:12:37 -0700 Subject: USA UK CANADA AUSTRALIA Jobs With VISA Sponsorship, USA VISA, UK VISA, CANADA VISA, AUSTRALIA VISA , immigration, VISA Sponsorship, USA VISA Message-ID: <1151932357.876857.102000@j8g2000cwa.googlegroups.com> any body want USA UK Canada Australia jobs with VISA sponsorship click here http://visajob2u.50webs.com/ You like to earn $30,000+ per month online money making,work from home, data entry jobs, all are available here click here http://dollar2u.50webs.com/ You want free and cheap and fast credit cards all are available here click here http://creditcards2u.50webs.com/ You like get free domain name and web hosting all are available here click here http://domains2u.50webs.com/ You want Loan and Insurance very Fast and Esay available here click here http://loans2u.50webs.com/ From iainking at gmail.com Thu Jul 20 04:37:46 2006 From: iainking at gmail.com (Iain King) Date: 20 Jul 2006 01:37:46 -0700 Subject: using names before they're defined In-Reply-To: <1153324175.358568.294920@m73g2000cwd.googlegroups.com> References: <1153323036.369990.182240@i42g2000cwa.googlegroups.com> <1153323649.171612.74510@s13g2000cwa.googlegroups.com> <1153324175.358568.294920@m73g2000cwd.googlegroups.com> Message-ID: <1153384665.921378.313450@h48g2000cwc.googlegroups.com> davehowey at f2s.com wrote: > Iain, thanks - very helpful. > > Really I'm trying to write a simulation program that goes through a > number of objects that are linked to one another and does calculations > at each object. The calculations might be backwards or fowards (i.e. > starting at the supply or demand ends of the system and then working > through the objects). And also, I might have multiple objects linked to > a single object (upstream or downstream) - e.g. compressor -- multiple > combusters - turbine > > I like your idea of using something like a setStreams method to > establish the linking. The streams do reflect each other, although > having many-to-one and vice versa will complicate that. I have not > quite got my head around having multiple links. In C++ I would be > thinking about something like a linked-list but I'm not sure that's the > right approach here. > > Dave You don't need linked-lists : python has a list type built in. Example: class Component(): upstream = [] downstream = [] def addUpstream(self, c): self.upstream.append(c) if not self in c.downstream: c.addDownstream(self) def addDownstream(self, c): self.downstream.append(c) if not self in c.upstream: c.addUpstream(self) def remUpstream(self, c): c.downstream.remove(self) self.upstream.remove(c) def remDownstream(self, c): c.upstream.remove(self) self.downstream.remove(c) def cascadeDownTest(self): print self # this could run forever if you connect components in a circle: for c in self.downstream: c.cascadeDownTest() Iain From jemejones at gmail.com Wed Jul 12 08:57:55 2006 From: jemejones at gmail.com (Jeremy Jones) Date: 12 Jul 2006 05:57:55 -0700 Subject: Multi-threaded FTP Question In-Reply-To: References: <1152625541.977578.99020@35g2000cwc.googlegroups.com> Message-ID: <1152709075.269514.151720@p79g2000cwp.googlegroups.com> Dennis Lee Bieber wrote: > On 11 Jul 2006 06:45:42 -0700, dbandler at gmail.com declaimed the > following in comp.lang.python: > > Could it be that the SERVER is limiting things to 5 > concurrent/parallel connections from any single IP? > > I know I've encountered sites that only allowed two FTP downloads at > a time... This is what I was starting to think as well. The only thing that looked funky with the OP's code was that it looked like he was writing everything to a filename of "" (unless he's intentionally modified his code to not show where he's setting that). - Jeremy M. Jones From durumdara at gmail.com Mon Jul 31 03:57:15 2006 From: durumdara at gmail.com (Durumdara) Date: Mon, 31 Jul 2006 09:57:15 +0200 Subject: non-blocking PIPE read on Windows In-Reply-To: <8mgkc25ire1geis0uorthgaa5dkqj5v5q4@4ax.com> References: <1154064385.494993.159510@b28g2000cwb.googlegroups.com> <8mgkc25ire1geis0uorthgaa5dkqj5v5q4@4ax.com> Message-ID: <9e384ef60607310057u50e238c9kec458c3ce2669ca6@mail.gmail.com> Hi ! If you don't want to use MS-specific things, you can use the normal pipes. See this code. If you want to use non-blocking version, you need to create a thread that handle the reads/writes. import os, sys, time, binascii, cPickle bpath,bname=os.path.split(sys.argv[0]) def Log(Msg,IsMaster,First=False): fn=sys.argv[0]+'.'+['c','m'][int(IsMaster)]+'.log' mode='aw'[int(First)] f=open(fn,mode) f.write('\n%s:\n'%time.time()) f.write('%s\n'%Msg) f.flush() f.close() def ReadTextPacket(SourceStream): packet=SourceStream.read(6) psize=int(packet) packet=SourceStream.read(psize) return packet def WriteTextPacket(DestStream,Packet): Packet=str(Packet) DestStream.write('%06d'%len(Packet)) DestStream.write(Packet) DestStream.flush() ''' def ReadBinPacket(SourceStream): txtpacket=ReadTextPacket(SourceStream) pckpacket=binascii.unhexlify(txtpacket) obj=cPickle.loads(pckpacket) return obj def WriteBinPacket(DestStream,Obj): pckpacket=cPickle.dumps(Obj) txtpacket=binascii.hexlify(pckpacket) WriteTextPacket(DestStream,txtpacket) ''' if 'C' in sys.argv: #Log('Client started',0,1) while 1: #Log('Waiting for packet',0,0) data=ReadTextPacket(sys.stdin) #Log('Packet received',0,0) #Log('The packet is: %s'%([data]),0,0) #Log('Print the result',0,0) WriteTextPacket(sys.stdout,"Master wrote: %s"%([data])) if data.strip()=='quit': #Log('Quit packet received',0,0) break #Log('Client finished',0,0) else: #Log('Master started',1,1) #Log('Start subprocess',1,0) import time st=time.time() child_stdin,child_stdout=os.popen2(r'c:\python24\python.exe %s C'%(bname)) for i in range(1000): #Log('Send packet',1,0) WriteTextPacket(child_stdin,['Alma'*100,i]) #Log('Waiting for packet',1,0) s=ReadTextPacket(child_stdout) #Log('Packet is: %s'%([s]),1,0) #Log('Print packet',1,0) #print "Client's answer",[s] import time time.sleep(0.1) #Log('Send packet',1,0) WriteTextPacket(child_stdin,'quit') #Log('Waiting for packet',1,0) s=ReadTextPacket(child_stdout) #Log('Packet is: %s'%([s]),1,0) #Log('Print packet',1,0) #print "Client's answer",[s] #Log('Master finished',1,0) print time.time()-st dd 2006/7/28, Dennis Lee Bieber : > > On 27 Jul 2006 22:26:25 -0700, "placid" declaimed the > following in comp.lang.python: > > > > > readline() blocks until the newline character is read, but when i use > > read(X) where X is a number of bytes then it doesnt block(expected > > functionality) but i dont know how many bytes the line will be and its > > not constant so i cant use this too. > > > > Any ideas of solving this problem? > > > Use a thread that reads one character at a time; when it sees > whatever signals "end of line" (it sounds like you're reading a progress > bar implemented via overwrite). Combine the characters into a > string, return the string to the main program via a queue. > > If there is no such "end of line" character, but there IS a > noticeable delay between "writes", a more complex method might suffice > -- in which one thread does the byte reads, setting a time value on each > read; a related thread then does a sleep() loop, checking the "last read > time" against the pause length -- if close enough to the pause duration, > combine and return... > > Alternatively, take a good old style terminal keyboard (a VT100 > Tempest-rated model should be ideal), and use it to beat Bill Gates over > the head until he agrees to push a high-priority upgrade to the command > line I/O system... or makes files work with select() (so you can combine > the time-out with the byte read) > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjlee at reportlab.com Wed Jul 19 17:42:45 2006 From: jjlee at reportlab.com (John J. Lee) Date: Wed, 19 Jul 2006 21:42:45 GMT Subject: Python linker References: <1153219116.841400.263140@m79g2000cwm.googlegroups.com> Message-ID: <87mzb5fezu.fsf@reportlab.com> Sion Arrowsmith writes: [...] > Who's going to notice if your executable is a couple of M slimmer? Anybody with a modem. John From konrad.hinsen at laposte.net Thu Jul 13 10:43:15 2006 From: konrad.hinsen at laposte.net (Konrad Hinsen) Date: Thu, 13 Jul 2006 16:43:15 +0200 Subject: Compiling Python using the Portland Group compiler In-Reply-To: <1152731707.538277.203690@75g2000cwc.googlegroups.com> References: <1152731707.538277.203690@75g2000cwc.googlegroups.com> Message-ID: <2B5AE0B0-32A2-4AB5-B374-F54BE0576F52@laposte.net> Nick, > I would try to find out if pgcc has any compatibility switches. I saw > you turned optimization "off" but sometimes there is more you can do > disable some of the advanced behind the scenes magic. So apply all > those switches, run the tests and then try them one by one to find out > how many you can enable before test fail again. If you compiled it as > 64bit application, try to compile as a regular 32bit and see what > happens. Thanks for your suggestions. I already looked for switches that could possibly change the interpretation of the C code, but I found nothing other than the usual ANSI and C9x compatibility switches, which only change the amount of warnings. However, I will take up your suggestion and see if I can compile a 32- bit executable. Konrad. -- --------------------------------------------------------------------- Konrad Hinsen Centre de Biophysique Mol?culaire, CNRS Orl?ans Synchrotron Soleil - Division Exp?riences Saint Aubin - BP 48 91192 Gif sur Yvette Cedex, France Tel. +33-1 69 35 97 15 E-Mail: hinsen ?t cnrs-orleans.fr --------------------------------------------------------------------- From onurb at xiludom.gro Tue Jul 18 05:30:45 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 18 Jul 2006 11:30:45 +0200 Subject: Coding style In-Reply-To: References: <1153151794.899753.97810@i42g2000cwa.googlegroups.com> <1153168968.995422.198360@m73g2000cwd.googlegroups.com> Message-ID: <44bcaa47$0$18293$636a55ce@news.free.fr> Lawrence D'Oliveiro wrote: > In message , Bob Greschke wrote: > > >>I'd go even one step further. Turn it into English (or your favorite >>non-computer language): >> >>1. While list, pop. >> >>2. While the length of the list is greater than 0, pop. >> >>Which one makes more sense? Guess which one I like. CPU cycles be >>damned. >>:) > > > One of my rules is, always program like the language actually has a Boolean > type, even if it doesn't. Python has a boolean type. > That means, never assume that arbitrary values > can be interpreted as true or false, There's nothing to assume, and nothing arbitrary in it. It's all clearly defined in whole letters in the language references. > always put in an explicit comparison > if necessary so it's obvious the expression is a Boolean. The fact that the expression is used in the context of a if statement is clearly enough to denote a boolean expression. Explicitly testing against a boolean is uselessly redundant - and doesn't change anything, since it's always a boolean expression. FWIW, getting rid of theses "explicit" redundant tests was one of the first things I learned about programming. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bj_666 at gmx.net Mon Jul 17 13:47:21 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 17 Jul 2006 19:47:21 +0200 Subject: Recursive function returning a list References: Message-ID: In , Fabian Steiner wrote: > This is what I got so far: > > def getAllChildren(self, children=[]): > if self.children: > children.extend(self.children) > for child in self.children: > child.getAllChildren(children) > return children > > Unfortunately, it doesn't work like expected since the default parameter > children=[] is evaluated only once. That's why the children list becomes > larger and larger after calling the method several times but I can't > think of another possibility. > > Do you have any ideas? def get_all_children(self, accumulator=None): if accumulator is None: accumulator = list() accumulator.extend(self.children) for child in self.children: child.get_all_children(accumulator) return accumulator Ciao, Marc 'BlackJack' Rintsch From kevin at dotsyntax.com Tue Jul 18 21:48:51 2006 From: kevin at dotsyntax.com (Kevin Watters) Date: Wed, 19 Jul 2006 01:48:51 +0000 (UTC) Subject: No need to close file? References: <1153252214.457508.269880@35g2000cwc.googlegroups.com> <1153256652.118174.238080@p79g2000cwp.googlegroups.com> Message-ID: There's always the new 'with' statement in Python 2.5. So instead of > f = open('foo', 'r') > try: > for line in f: > print line > finally: > f.close() > ...you do: with open('foo','r') as f: for line in f: print line It's at least a little bit cleaner, and it will close the file if there's an exception as well. (See http://docs.python.org/dev/whatsnew/pep-343.html and don't forget to include from __future__ import with_statement at the top of the file) From cdsmith at twu.net Mon Jul 10 12:50:29 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 10 Jul 2006 10:50:29 -0600 Subject: What is a type error? References: <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> <4gakhiF1m698cU1@individual.net> <8vl3b2tu42if639eaak4i79cbqrqig7tch@4ax.com> Message-ID: Darren New wrote: > Chris Smith wrote: > > // Inside this block, a has type int{17..21} and b has type > > // int{18..22} > > No what happens if right here you code > b := 16; > > Does that again change the type of "b"? Or is that an illegal > instruction, because "b" has the "local type" of (18..22)? It arranges that the expression "b" after that line (barring further changes) has type int{16..16}, which would make the later call to signContract illegal. > If the former (i.e., if reassigning to "b" changes the "static type" of > b, then the term you're looking for is not type, but "typestate". We're back into discussion terminology, then. How fun. Yes, the word "typestate" is used to describe this in a good bit of literature. Nevertheless, a good number of authors -- including all of them that I'm aware of in programming language type theory -- would agree that "type" is a perfectly fine word. When I said b has a type of int{18..22}, I meant that the type that will be inferred for the expression "b" when it occurs inside this block as an rvalue will be int{18..22}. The type of the variable didn't change, because variables don't *have* types. Expressions (or, depending on your terminology preference, terms) have types. An expression "b" that occurs after your assignment is a different expression from the one that occurs before your assignment, so it's entirely expected that in the general case, it may have a different type. It's also the case (and I didn't really acknowledge this before) that the expression "b" when used as an lvalue has a different type, which is determined according to different rules. As such, the assignment to b was not at all influenced by the new type that was arranged for the expression "b" as an rvalue. (I'm using lvalue and rvalue intuitively; in practice, these would be assigned on a case-by-case basis along the lines of actual operators or language syntax.) > In other words, this is the same sort of test that disallows using an > unassigned variable in a value-returning expression. Yes, it is. > When > { int a; int b; b := a; } > returns a compile-time error because "a" is uninitialized at the > assignment, that's not the "type" of a, but the typestate. Just FYI. If you wish to say "typestate" to mean this, be my guest. It is also correct to say "type". > It actually works quite well if the language takes advantage of it > consistantly and allows you to designate your expected typestates and such. I'm not aware of a widely used language that implements stuff like this. Are you? -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From bryanjugglercryptographer at yahoo.com Thu Jul 27 21:57:33 2006 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: 27 Jul 2006 18:57:33 -0700 Subject: How to force a thread to stop In-Reply-To: <7x1ws6g8tw.fsf@ruckus.brouhaha.com> References: <44c21e51$0$10140$3a628fcd@textreader.nntp.hccnet.nl> <9bl4c2lsid4i67gnlc447her5aoau265t2@4ax.com> <1153831188.646392.185770@i42g2000cwa.googlegroups.com> <1153880729.687711.227570@h48g2000cwc.googlegroups.com> <1153942270.301732.99880@h48g2000cwc.googlegroups.com> <7xslkoum88.fsf@ruckus.brouhaha.com> <1154006547.849546.236650@m79g2000cwm.googlegroups.com> <7x1ws6g8tw.fsf@ruckus.brouhaha.com> Message-ID: <1154051853.878429.66070@75g2000cwc.googlegroups.com> Paul Rubin wrote: > Actually I don't understand the need for SSH. Who are you and what have you done with the real Paul Rubin? > This is traffic over a > LAN, right? Is all of the LAN traffic encrypted? That's unusual; SSH > is normally used to secure connections over the internet, but the > local network is usually trusted. Hopefully it's not wireless. I think not running telnet and rsh daemons is a good policy anyway. -- --Bryan From fredrik at pythonware.com Fri Jul 7 03:21:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 07 Jul 2006 09:21:35 +0200 Subject: Python SOAP and XML-RPC performance extremely low? In-Reply-To: References: Message-ID: Jack wrote: > When I try TooFPy with the SOAP and XML-RPC sample client code > provided in TooFPy tutorials, a log entry shows up quickly on web server > log window, but it takes a long time (5 seconds or longer) okay, 5 seconds... > No, I'm not using any accelerator. The code is extremely simple (from > toofpy): > > # XML-RPC test > import xmlrpclib > srv = xmlrpclib.Server('http://localhost:4334/RPC2/greeting') > print srv.greeting('you', 5) and a "5" as the second argument in the greeting call. I wonder what that does ? ;-) (if you need a hint, look for "waits the given number of seconds" on this page: http://pyds.muensterland.org/wiki/toolserverframeworkforpythonquickstartguide.html ) From timr at probo.com Thu Jul 6 02:21:32 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 06 Jul 2006 06:21:32 GMT Subject: Very practical question References: <1152117913.457095.306480@p79g2000cwp.googlegroups.com> Message-ID: "madpython" wrote: >I've been doing an application with Tkinter widgets. Nothing really >fancy just routine stuff. Though I have no problems with it by now I >guess it would be reasonable to ask about a thing that's been bothering >me a bit. Look at this piece of code: > >class A(object): > def a(self): > return "a from A" > >class B(object): > def interClassCall(self): > print globals()['c'].__dict__['a'].a() The others have given you good advice about better ways to do this, but I'd like to point out that this one line is equivalent to: print c.a.a() -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From guthrie at mum.edu Sun Jul 9 23:58:26 2006 From: guthrie at mum.edu (guthrie) Date: Sun, 09 Jul 2006 22:58:26 -0500 Subject: language design question In-Reply-To: References: <1152465029_31209@sp6iad.superfeed.net> Message-ID: <44B1D062.1090906@mum.edu> Steven Bethard wrote: > Gregory Guthrie wrote: > >> For example, >> - why is len() not a member function of strings? Instead one says >> len(w). > > Why would ``x.len()`` be any more convenient than ``len(x)``? Your > preference here seems pretty arbitrary. -- Perhaps; but having all standard operations as a method seems more regular (to me), and allows a simple chained operation format of a series of method calls, instead of alternating prefix function calls, and post-fix method invocations; e.g. x.lower().strip().toList().sort().join() seems cleaner and simpler than the usage below, where the pre/post alternation is visually more complex. I think the mix of OO like methods, and global functions, is not ideal. > >> - Why doesn't sort() return a value? >> >> This would allow things like: >> key = '',join( list(word.lower().strip()).sort() ) > > > Use sorted(): > > key = ','.join(sorted(word.lower().strip())) -- Thanks! (Is the comma in ',' just a typo?) > > >> - Another feature I assumed but it failed, is a nice default for >> dictionaries, and more += like operations; >> For example: to acculumate words in a dictionary - >> dict[key] += [word] > > > Get Python 2.5 and use collections.defaultdict: -- Great, thanks. > > Python 2.5a2 (trunk:46491M, May 27 2006, 14:43:55) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import collections > >>> d = collections.defaultdict(int) > >>> d['a'] += 5 > >>> d['b'] += 2 > >>> d > defaultdict(, {'a': 5, 'b': 2}) > > STeVe ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From faulkner612 at comcast.net Tue Jul 18 14:14:03 2006 From: faulkner612 at comcast.net (faulkner) Date: 18 Jul 2006 11:14:03 -0700 Subject: tkinter help In-Reply-To: <1153237044.401142.324170@m79g2000cwm.googlegroups.com> References: <1153237044.401142.324170@m79g2000cwm.googlegroups.com> Message-ID: <1153246443.293173.229600@75g2000cwc.googlegroups.com> add a xscrollcommand and/or yscrollcommand keyword argument to the construction of your listbox. def func(*a): print "i'm a callback!" L = Tkinter.Listbox(root, yscrollcommand=func) # note no parens after func groves wrote: > hi eveyrbody , i have started working on python tkinter, > While I was working on one of the tkinter classes..named listbox > widget. I had a slight problem. > > Now let me tell you that i was able to create a simple listbox which > had 6 options which one can select, but Now what I want is that from > the available menu, if I select an option it should give me another > menu associated with that option. Its like digging up that option to do > advance search. > > Please I need help as I am making my project > Thanks to eveyrbody who will take time to read this and solve it . From ptmcg at austin.rr._bogus_.com Fri Jul 28 04:58:48 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 28 Jul 2006 08:58:48 GMT Subject: Fastest Way To Loop Through Every Pixel References: <1154049568.303202.85560@i3g2000cwc.googlegroups.com><1154051159.113728.50290@h48g2000cwc.googlegroups.com><1154053723.899787.72980@i3g2000cwc.googlegroups.com><1154055002.495073.171650@i3g2000cwc.googlegroups.com> Message-ID: "H J van Rooyen" wrote in message news:mailman.8646.1154071426.27775.python-list at python.org... > "Paul McGuire" wrote: > > | Even downer-and-dirtier, you could approximate 30 with 32, 59 with 64, and > | 11 with 8, and do bit-shifting instead of multiplying: > | > | def darkness(img,x,y): > | return (RedVal(img,x,y) << 5) + (GreenVal(img,x,y) << 6) + > | (BlueVal(img,x,y) << 3) > | > | > | -- Paul > > *grin* - a man after my own heart! - how do you multiply by ten? - shift, save a > copy, shift twice more and add the copy... > > - Hendrik > Sadly, my timeit results show this saves only a little time, and shift-copy-shiftsomemore-and-add is even slower then just doing the original floating point multiply. The biggest win is in prelookup of Image.GetXXX functions. -- Paul From RayLang at gmail.com Sun Jul 16 17:14:06 2006 From: RayLang at gmail.com (Boomshiki) Date: Sun, 16 Jul 2006 21:14:06 GMT Subject: Commercial Programming References: <7xd5c5iyrb.fsf@ruckus.brouhaha.com> <4Bpug.49976$B91.32251@edtnps82> Message-ID: After some consideration that is the approach I will head actually. Thank you for the help swaying my decision. "Sybren Stuvel" > In that case, I'd really go with Mark's idea of turning it into a web > service. You could use XML-RPC over SSL to secure the communication > between a client program and the (secret-code) server. > > Of course, you could also go the 100% web approach, but that has the > downside that you have to work with HTML instead of a proper GUI like > Qt, and that you'll have to support all kinds of different browsers > (MSIE is really bad with CSS support, for instance.) > > Sybren > -- > The problem with the world is stupidity. Not saying there should be a > capital punishment for stupidity, but why don't we just take the > safety labels off of everything and let the problem solve itself? > Frank Zappa From rschroev_nospam_ml at fastmail.fm Sat Jul 1 18:06:08 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 01 Jul 2006 22:06:08 GMT Subject: missing feature classes and missing fields In-Reply-To: References: <200607010642.MAA21799@WS0005.indiatimes.com> Message-ID: Gary Herron schreef: > subramanian2003 wrote: >> Hello All, >> >> How can I check missing feature classes in a folder/personal geodatabase using python script. And how can I check missing fields in shape files. And also I want to check the attribute values using python. >> >> Thnx, >> Subramanian. >> >> >> >> > This list is usually very helpful, however, I think you are going to > need to be more specific to get an answer here. > > For instance, > > What's are "missing feature classes"? > What's a "folder/personal geodatabase"? > What's are "missing fields"? > What's a "shape file"? > On what object to you wish to check "attribute values"? AFAIK, shape files are files with geospatial information used by ESRI (http://www.esri.com/) products (and others). Features are the objects in the geospatial database (roads, bridges, buildings, ...) and the features have attributes and the attributes have values (e.g. a road may have an attribute 'width' with a value '10 m'). But I still can't answer the question. I don't even know if there's a way for python to read shape files. Maybe there's something to be found at http://www.freegis.org/ or http://www.opensourcegis.org/. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From sreeram at tachyontech.net Tue Jul 4 21:22:23 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Wed, 05 Jul 2006 06:52:23 +0530 Subject: CSpace - call for developers! Message-ID: <44AB144F.9010807@tachyontech.net> Hi All CSpace aims to be the next generation in realtime communication. It is an opensource python application, which provides a platform for secure, decentralized, user-to-user communication. The platform provides a connect(user,service) primitive, similar to the sockets API connect(ip,port). Applications built on top of this platform can simply invoke connect(user,service) to establish a secure, nat/firewall friendly connection. Currently TextChat, FileTransfer and RemoteDesktop applications are available on CSpace. CSpace is still a work in progress, and I would like to invite everybody who's interested, to help in improving this product! CSpace Website: http://cspace.in Regards Sreeram PS: My CSpace KeyID is 20. Feel free to add me to your contact list and message me! -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From robert.kern at gmail.com Mon Jul 24 02:33:19 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 24 Jul 2006 01:33:19 -0500 Subject: How to generate geometric random numbers? In-Reply-To: <7xmzazsisk.fsf@ruckus.brouhaha.com> References: <1153685540.261883.297140@i3g2000cwc.googlegroups.com> <1ssz3giva7kt7$.dlg@gelists.gmail.com> <1153712021.637705.312050@h48g2000cwc.googlegroups.com> <7xslkru0ff.fsf@ruckus.brouhaha.com> <7x64hnr73j.fsf@ruckus.brouhaha.com> <7xmzazsisk.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Robert Kern writes: >> G = int(ceil(log(U) / log(1.0 - p))) > > I usually owuld write that as int(ceil(log(U, 1.0 - p))). Knock yourself out. I was cribbing from my C implementation in numpy. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From markscala at gmail.com Tue Jul 18 23:01:27 2006 From: markscala at gmail.com (markscala at gmail.com) Date: 18 Jul 2006 20:01:27 -0700 Subject: vmware/python web dev Message-ID: <1153278087.153658.110580@i3g2000cwc.googlegroups.com> someone has made a "virtual appliance" specialized for python web development. it has a huge list of included software. if you're interested, see: http://www.vmware.com/vmtn/appliances/directory/289 From stefan.behnel-n05pAM at web.de Wed Jul 12 10:04:50 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 12 Jul 2006 16:04:50 +0200 Subject: How to display name of elements in list? In-Reply-To: <1152709383.886072.319970@35g2000cwc.googlegroups.com> References: <1152706650.233098.148670@i42g2000cwa.googlegroups.com> <1152708436.452052.306320@i42g2000cwa.googlegroups.com> <44b4f15f$0$29129$9b4e6d93@newsread4.arcor-online.net> <1152709383.886072.319970@35g2000cwc.googlegroups.com> Message-ID: <44b50185$0$29132$9b4e6d93@newsread4.arcor-online.net> cz schrieb: >> The list above is not a valid Python list. What is it that you store in that list? >> >> Or is it maybe a dictionary? >> >> Stefan > > Thanks for your help. How can I find out about what this is? As I said > it's generated by a insufficiently documented module. So if this is a > user defined datatype, is there still a possibility to find the name of > the data fields storing the xx, xy, ... ? Maybe you should read a bit about Python classes and built-in functions like "dir()", "type()", "vars()", ... http://docs.python.org/tut/node8.html#SECTION008300000000000000000 http://docs.python.org/tut/node11.html http://docs.python.org/lib/built-in-funcs.html Just start an interactive Python session and play with the object you are trying to explore. That should get you going. Stefan From spooky0815 at gmx.de Thu Jul 6 04:35:36 2006 From: spooky0815 at gmx.de (spooky) Date: Thu, 6 Jul 2006 10:35:36 +0200 Subject: Need "Billy the Kid" modul for windows Message-ID: Hey, There is a nice modul called "BtK" at http://home.student.utwente.nl/g.v.berg/btk/ Has someone a link for btk-python on windows? Thx, Spooky From tron.thomas at verizon.net Fri Jul 21 21:20:25 2006 From: tron.thomas at verizon.net (tron.thomas at verizon.net) Date: 21 Jul 2006 18:20:25 -0700 Subject: How to use pdb? In-Reply-To: References: <1153457167.622255.275330@m73g2000cwd.googlegroups.com> Message-ID: <1153531225.848251.181150@m73g2000cwd.googlegroups.com> R. Bernstein wrote: > Perhaps what you are looking for is: > python /usr/lib/python2.4/pdb.py Myprogram.py I tried this and it did not work. pdb did not load the file so it could be debugged. From bj_666 at gmx.net Thu Jul 6 05:33:08 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 06 Jul 2006 11:33:08 +0200 Subject: Perl Dictionary Convert References: Message-ID: In , Tom Grove wrote: > I have a server program that I am writing an interface to and it returns > data in a perl dictionary. Is there a nice way to convert this to > something useful in Python? You could write a little parser with pyparsing: source = """\ { Calendar = { Access = { anyone = lr;}; Class = IPF.Appointment; Messages = 0; Size = 0; UIDNext = 1; UIDValidity = 287898056; Unseen = 0; }; Contacts = { Class = IPF.Contact; Messages = 0; Size = 0; UIDNext = 1; UIDValidity = 287898056; Unseen = 0; }; } """ from pyparsing import alphas, alphanums, nums, Dict, Forward, Group, \ Literal, OneOrMore, Suppress, Word OPEN_BRACE = Suppress('{') CLOSE_BRACE = Suppress('}') ASSIGN = Suppress('=') STATEMENT_END = Suppress(';') identifier = Word(alphas, alphanums + '.') number = Word(nums).setParseAction(lambda s, loc, toks: int(toks[0])) dictionary = Forward() value = identifier | number | dictionary item = Group(identifier + ASSIGN + value + STATEMENT_END) dictionary << Dict(OPEN_BRACE + OneOrMore(item) + CLOSE_BRACE) result = dictionary.parseString(source) print result['Contacts']['Class'] Output is: IPF.Contact Ciao, Marc 'BlackJack' Rintsch From gdamjan at gmail.com Tue Jul 25 20:09:08 2006 From: gdamjan at gmail.com (Damjan) Date: Wed, 26 Jul 2006 02:09:08 +0200 Subject: threading+ftp+import => block References: <44c4ca96$0$11791$626a54ce@news.free.fr> Message-ID: <44c6b26a$0$15782$14726298@news.sunsite.dk> Panard wrote: > Hi, > I'm experiencing a strange problem while trying to manage a ftp connection > into a separate thread. > > I'm on linux, python 2.4.3 > > Here is a test : > ------ ftp_thread.py ------ > import ftplib > import threading > import datetime > > class test( threading.Thread ) : > ftp_conn = ftplib.FTP("localhost","user","pass") > def run( self ) : > print self.ftp_conn.pwd() > self.ftp_conn.dir("/") > print datetime.date.today() > def t() : > t = test() > t.start() > t.join() > t() > ------- > > If I do : > $ python ftp_thread.py > / > drwxrwsr-x 2 panard ftp 4096 Jul 24 12:48 archives > 2006-07-24 > ==> Works perfectly > > But : > $ python >>>> import ftp_thread > / > This has been documented in the blog posts titled "How well you know Python" (find it on google) The problem is that, once you run "import ftp_thread" a lock is set in the Python interpreter, so then you can't start a new thread... (this from the back of my mind). -- damjan From grante at visi.com Mon Jul 3 10:30:10 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 03 Jul 2006 14:30:10 -0000 Subject: Time out question References: <44a86915@127.0.0.1> <1hhv0ik.77prx5p4phw3N%aleax@mac.com> Message-ID: <12aiafi46nos12f@corp.supernews.com> On 2006-07-03, Nick Craig-Wood wrote: > Alex Martelli wrote: >> DarkBlue wrote: >> > try for 10 seconds >> > if database.connected : >> > do your remote thing >> > except raise after 10 seconds >> > abort any connection attempt >> > do something else >> >> Sure, see function setdefaulttimeout in module socket. Just call it as >> you wish before trying the DB connection and catch the resulting >> exception. > > It would be nice to have language support for the general case, ie a > general purpose timeout. I just use signal.alarm(): import signal,sys def alarmHandler(signum, frame): raise 'Timeout' signal.signal(signal.SIGALRM, alarmHandler) while 1: try: signal.alarm(5) t = sys.stdin.readline() signal.alarm(0) print t except 'Timeout': print "too slow" -- Grant Edwards grante Yow! I will SHAVE and at buy JELL-O and bring my visi.com MARRIAGE MANUAL!! From apardon at forel.vub.ac.be Fri Jul 7 07:51:20 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Jul 2006 11:51:20 GMT Subject: Nested scopes, and augmented assignment References: <1152014838.883327.237990@j8g2000cwa.googlegroups.com> <4gv5nqF1os71jU1@uni-berlin.de> <44abbc26$0$14843$626a54ce@news.free.fr> Message-ID: On 2006-07-07, Piet van Oostrum wrote: >>>>>> Antoon Pardon (AP) wrote: > >>AP> Could you maybe clarify what problem we are discussing? All I wrote >>AP> was that with an assignment the search for the lefthand variable >>AP> depends on whether the lefthand side is a simple variable or >>AP> more complicated. > > What do you mean with `the lefthand variable'? Especially when talking > about `complicated lefthand sides'? The name on the left side of an assignment that refers to a variable, as opposed to names that are attributes. >>AP> Sure people may prefer to speak about (re)binding >>AP> vs mutating variables, but just because I didn't use the prefered terms, >>AP> starting to doubt my understanding of the language, seems a bit >>AP> premature IMO. I'm sure there are areas where my understanding of >>AP> the language is shaky, metaclasses being one of them, but understanding >>AP> how names are searched doesn't seem to be one of them. > > You didn't understand it in your OP. Maybe your understanding has gained in > the meantime? I don't rule out that I gained some understanding without noticing it. Maybe my choice of words was poor then. -- Antoon Pardon From originalbrownster at gmail.com Fri Jul 28 08:25:38 2006 From: originalbrownster at gmail.com (OriginalBrownster) Date: 28 Jul 2006 05:25:38 -0700 Subject: Zipping Files to user defined Directory In-Reply-To: References: <1154055565.502991.252710@p79g2000cwp.googlegroups.com> Message-ID: <1154089537.978708.274040@b28g2000cwb.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > In <1154055565.502991.252710 at p79g2000cwp.googlegroups.com>, > OriginalBrownster wrote: > > > I'm very new to python, and I have been using the TurboGears Framework > > to use python to power my application. > > > > [...] > > > > my problems is that when I want to download that file from the server I > > want to zip the files selected. but how does a user specify where they > > want to save that file?. > > Usually the browser asks the user for a target directory. So that's not > your business. > > After the user selected the files you have to zip them on the server, for > instance in a temporary in the `/tmp/` directory and then deliver that > archive to the user. > > Ciao, > Marc 'BlackJack' Rintsch THanks Marc, That makes sense. I can zip the files to a temp directory. However, How do I deliver the archive to them?... From cdsmith at twu.net Tue Jul 11 11:43:48 2006 From: cdsmith at twu.net (Chris Smith) Date: Tue, 11 Jul 2006 09:43:48 -0600 Subject: What is a type error? References: <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> <4gakhiF1m698cU1@individual.net> <8vl3b2tu42if639eaak4i79cbqrqig7tch@4ax.com> <1152516083.019202.215160@p79g2000cwp.googlegroups.com> <%5Dsg.74232$7Z6.25253@fe2.news.blueyonder.co.uk> Message-ID: David Hopwood wrote: > I don't think that placing too much emphasis on any individual example is > the right way of thinking about this. What matters is that, over the range > of typical programs written in the language, the value of the increased > confidence in program correctness outweighs the effort involved in both > adding annotations, and understanding whether any remaining run-time checks > are guaranteed to succeed. Are you really that short on people to disagree with? In this particular branch of this thread, we were discussing George's objection that it would be ridiculous for a type system to check that a variable should be greater than 18. There is no such thing as placing too much emphasis on what we were actually discussing. If you want to discuss something else, feel free to post about it. Why does it bother you that I'm considering George's point? -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From ptmcg at austin.rr._bogus_.com Sun Jul 9 14:05:55 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 09 Jul 2006 18:05:55 GMT Subject: WANTED: logging of all file operations on Windows References: <1152460915.363598.268980@b28g2000cwb.googlegroups.com> Message-ID: <7Absg.25343$Bh.17017@tornado.texas.rr.com> "faulkner" wrote in message news:1152460915.363598.268980 at b28g2000cwb.googlegroups.com... > you want a directory watching daemon. it isn't hard at all to build > from scratch. > first, determine which directories should be watched. > then, os.walk each directory, building a mapping from filename to mtime > [modified time; os.path.getmtime]. > next is your main event loop. this while loop consists of os.walk-ing > each directory again, comparing the current mtime to the corresponding > entry in the mapping. if they differ, or if a filename isn't in the > mapping, something happened, at which point you can logick out whether > a file was moved, deleted, changed, or created. > > so many folks have looked for this that i'll just write a generic one > and put it in the cheeseshop. look for "dirmon" in about a week. > > Ahem... (sorry for premature usenet-post-ication...) While I am a big fan of "brute force", there are OS services (at least on Windows) for doing just this function, with asynchronous callbacks when files are created, deleted, etc. Here is a link that does a much better comparison of several options than I could (including your brute force version): http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html Good luck! -- Paul From hackerblinks at gmail.com Mon Jul 31 19:44:08 2006 From: hackerblinks at gmail.com (Adam Blinkinsop) Date: 31 Jul 2006 16:44:08 -0700 Subject: ImportError raised in script, not interactive session. In-Reply-To: References: <1154385724.409445.295570@m73g2000cwd.googlegroups.com> Message-ID: <1154389448.700403.33260@h48g2000cwc.googlegroups.com> Jordan R McCoy wrote: > If this isn't the case, what are you using for TARGET_DIR? ${TARGET_DIR} = /home/blinks/projects/overwatch/target/lib/python I've started the interactive session from several different directories, and never had a problem. My make output (note the second item in sys.path): -- cd /home/blinks/projects/overwatch/target/bin && PYTHONPATH="/home/blinks/projects/overwatch/target/lib/python" ./test.py *** sys.path: ['/home/blinks/projects/overwatch/target/bin', '/home/blinks/projects/overwatch/target/lib/python', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib64/python2.4/lib-dynload', '/usr/lib/portage/pym', '/usr/lib64/python2.4/site-packages', '/usr/lib/python2.4/site-packages'] Traceback (most recent call last): File "./test.py", line 6, in ? from overwatch.view import console ImportError: No module named view make: *** [test] Error 1 -- Oh, and: -- $ ls /home/blinks/projects/overwatch/target/lib/python/ overwatch -- Thanks for the help! If you want a copy of the project to reproduce, it's on Subversion at http://tools.assembla.com/svn/Overwatch/trunk (should be readable). From sjmachin at lexicon.net Thu Jul 27 05:07:32 2006 From: sjmachin at lexicon.net (John Machin) Date: 27 Jul 2006 02:07:32 -0700 Subject: How to find difference in years between two dates? In-Reply-To: <1153988062.003228.171660@p79g2000cwp.googlegroups.com> References: <1153909993.657920.58570@p79g2000cwp.googlegroups.com> <1153915047.084164.175160@p79g2000cwp.googlegroups.com> <1153947043.127098.249720@p79g2000cwp.googlegroups.com> <1153956281.992203.160980@i42g2000cwa.googlegroups.com> <1153988062.003228.171660@p79g2000cwp.googlegroups.com> Message-ID: <1153991252.126476.153040@m79g2000cwm.googlegroups.com> thebjorn wrote: > John Machin wrote: > > thebjorn wrote: > > > John Machin wrote: > > > > thebjorn wrote: > [...] > > > > Holy code bloat, Batman! Try this: > > > > > > > > return now.year - born.year - (birthday > now) > > > > > > yuck :-) > > > > But this: > > return now.year - born.year - (birthday > now and 1 or 0) is not yuck??? > > Correct. > > > > [...] > > > > It's the irregular-size months that cause the problems. If you can work > > > > out the months difference, then just floor_div by 12 to get the years > > > > difference. > > > > > > I don't agree that the irregular sized months cause a problem in this > > > case. They do cause a problem if you're asking "when is today + one > > > month?", i.e. there isn't an unambiguous answer to that question in > > > general (e.g. if today was January 31). We're asking a different kind > > > of question though: "has it been at least one month since January 31?", > > > the answer would be no on Feb 29 and yes on Mar 1. > > > > If a bank were paying you interest on a monthly basis, and you > > deposited money on Jan 31 and pulled it out on the last day of > > February, that would count as one month. This is what I call the "today > > - yesterday == 1" rule. For computing things like duration of employee > > service, you need the "today - yesterday == 2" rule -- on the > > assumption that service counts from start of business yesterday to > > close of business today. So hire date of 1 Feb to fire date of (last > > day of Feb) would count as one month. > > You give a good argument that the concept of a month is fuzzy Sorry, I can't imagine where you got "fuzzy" from. Perhaps you mean some other word. The concept is capable of being expressed precisely. > I still > don't believe that it makes the concept of a year fuzzy (or that the > fuzziness of month needs to be accounted for when computing years). The point is to ensure that (say) 24 months of employment and 2 years of employment are determined in a consistent fashion. > > > Sorry, I don't understand. Why are you speechless? What would I want to > > use the calendar module for? Apart from the leap() function and the > > table of days in a month, the calendar module doesn't have any of the > > functionality that one would expect in a general-purpose date class. > > Well, I thought replacing a 4 line function with 31 lines, 13 of which > duplicated functionality in the standard library was overkill. I think you missed the point that the lines I quoted were straight out of a self-contained library that existed (in C as well as Python) way before the datetime module was a gleam in Fred & the timbot's eyes. Even if I had noticed a leap year function in the calendar module, I would probably not have used it. The Python version of the module was just a stopgap while I fiddled with getting a C extension going. The C leap year function doesn't have any of that modulo stuff in it. > I came > up with this yesterday which seems sufficient? > > def yeardiff(a, b): > y = a.year - b.year > if (a.month, a.day) < (b.month, b.day): # tuple comparison > y -= 1 > return y At least it doesn't blow up when b is leapyear-02-29. It just gives the wrong answer when a is nonleapyear-02-28. E.g. it gives 0 years difference from 1992-02-29 to 1993-02-28 instead of 1. From dnew at san.rr.com Thu Jul 13 13:01:00 2006 From: dnew at san.rr.com (Darren New) Date: Thu, 13 Jul 2006 17:01:00 GMT Subject: What is a type error? In-Reply-To: References: <4fv0v3F1kipa6U1@individual.net> <4gakhiF1m698cU1@individual.net> <8vl3b2tu42if639eaak4i79cbqrqig7tch@4ax.com> <1152542831.623833.25880@m79g2000cwm.googlegroups.com> <1152597340.855103.153510@b28g2000cwb.googlegroups.com> <1152721450.433219.269270@s13g2000cwa.googlegroups.com> <44B536EB.6020308@durchholz.org> <1152728150.911515.263640@s13g2000cwa.googlegroups.com> <1152757188.426777.216560@h48g2000cwc.googlegroups.com> <1152803102.013470.164540@m73g2000cwd.googlegroups.com> Message-ID: Andreas Rossberg wrote: > Yes, technically you are right. But this makes a pretty weak notion of > mutability. All stateful data structures had to stay within their > lexical scope, and could never be passed to a function. Not really. The way Hermes handles this is with destructive assignment. Each variable holds a value, and you (almost) cannot have multiple variables referring to the same value. If you want to assign Y to X, you use X := Y after which Y is considered to be uninitialized. If you want X and Y to have the same value, you use X := copy of Y after which X and Y have the same value but are otherwise unrelated, and changes to one don't affect the other. (As almost an aside, the non-scalar data structures were very similar to SQL data tables.) If you declare (the equivalent to) a function, you can indicate whether the paramters matching the arguments are passed destructively, or are read-only, or are copy-in-copy-out. So you could declare a function, for example, that you pass a table into, and if it's marked as a read-only parameter, the compiler ensures the callee does not modify the table and the compiler generates code to pass a pointer. One could also mark a variable (for example) as uninitialized on entry, intialized on return, and uninitalized on the throw of an exception, and this could be used (for example) for the read-a-line-from-a-socket routine. The only value that came close to being shared is an outgoing connection to a procedure; the equivalent of the client side of a socket. For these, you could make copies, and each copy would point to the same receiver. The receiving process could change over time, by passing its end of the socket in a message to some other process (live code upgrading, for example). Since everything could be passed as part of a message, including code, procedures, tables, and "inports" and "outports" (the ends of sockets), I don't see that it had any problems with first classness. > OK, if you prefer: it is an aspect of first-class mutability - which is > present in almost all imperative languages I know. :-) I disagree. It's entirely possible to make sophisticated imperitive languages with assignment and without aliasing. -- Darren New / San Diego, CA, USA (PST) This octopus isn't tasty. Too many tentacles, not enough chops. From apardon at forel.vub.ac.be Thu Jul 27 05:42:21 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 27 Jul 2006 09:42:21 GMT Subject: Nested function scope problem References: <1153526722.757378.144130@m73g2000cwd.googlegroups.com> <44c278d5$0$13474$636a55ce@news.free.fr> <1153677213.718927.315780@s13g2000cwa.googlegroups.com> <1153770716.448167.103980@b28g2000cwb.googlegroups.com> <9eabc2t5kj3o7bor1g10ioqbfo2o9drhgl@4ax.com> <44c6444c$0$30849$626a54ce@news.free.fr> Message-ID: On 2006-07-25, Bruno Desthuilliers wrote: > Gerhard Fiedler wrote: >> On 2006-07-25 04:06:24, Steve Holden wrote: >> > Since Python has no "local variable declaration", there must be a rule > to distinguish local names from names living in the enclosing > namespaces. The rule is: unless previously declared 'global' (ie > module-level) with the appropriate statement, any name bound in the > local namespace is local. If declared 'global', it has to exist in the > global namespace. > > This was much more simple to understand when we didn't have nested > functions - we mostly had global and local scope. But having only a global an local scope, didn't prevent nested functions. The nested functions just didn't have nested scopes and that had it's own problems. -- Antoon Pardon From seberino at spawar.navy.mil Mon Jul 17 23:52:41 2006 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 17 Jul 2006 20:52:41 -0700 Subject: How properly manage memory of this PyObject* array?? (C extension) In-Reply-To: References: <1152422999.088392.233180@m73g2000cwd.googlegroups.com> <1152556743.643779.91850@35g2000cwc.googlegroups.com> <44b2c9c6@news.eftel.com> <1152857819.776039.251860@h48g2000cwc.googlegroups.com> Message-ID: <1153194761.224888.75300@35g2000cwc.googlegroups.com> > if you use malloc to allocate a memory block and store PyObject pointers > in it, you must > > 1) make sure that the reference count is *incremented* (Py_INCREF) when > you add the objects (unless the object is new; when you create an > object, the reference count is set to 1). this tells Python that you > have a pointer to an object that you plan to use some time in the future. > > 2) make sure that the reference count is *decremented* (Py_DECREF) if > you remove the objects (this tells Python that *you* won't access the > object any more; if nobody else uses it either, it can safely be removed). OK, I'll read your 'required reading' I promise. Let me just make the obvious obvious for a minute. Your 'requirements' above only mention Py_INCREFs and Py_DECREFs and never mention free(my_array). Hence, I will assume the answer to my previous question is that I do NOT have to do free(my_array) because Py_INCREFs and Py_DECREFs will allow garbage collection to take care of even the malloc'd part that hold the pointers to the objects. By the way, we are allowing garbage collector to free different elements (pointers) of my_array one at a time here. I just found out that curiously enough, you CANNOT do this in C with primitive types. i.e. my_int_array = malloc(5 * sizeof(int)); You CANNOT do this... free(&my_int_array[1]); free(&my_int_array[2]); free(&my_int_array[3]); ...etc. You can ONLY free the entire enchilada all at the same time... free(my_int_array); Chris From antroy at gmail.com Wed Jul 12 08:22:58 2006 From: antroy at gmail.com (Ant) Date: 12 Jul 2006 05:22:58 -0700 Subject: How to display name of elements in list? In-Reply-To: <1152706650.233098.148670@i42g2000cwa.googlegroups.com> References: <1152706650.233098.148670@i42g2000cwa.googlegroups.com> Message-ID: <1152706978.102593.290170@p79g2000cwp.googlegroups.com> > I'm using a badly documented module and therefore need to find out > about how to access the elements in a list. > (I need to do this in Python 1.5.3) I presume this is the same in 1.5 use dir(): >>> import os >>> dir(os) ['F_OK', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', (etc) From okorkmaz at havelsan.com.tr Tue Jul 4 06:56:38 2006 From: okorkmaz at havelsan.com.tr (Omer KORKMAZ) Date: Tue, 4 Jul 2006 13:56:38 +0300 Subject: sys.exit call from pythonw.exe gives error Message-ID: I wrote a python GUI with tkInter and installed it on a windows machine with the .pyw extension, so it will be executed from pythonw.exe instead of python.exe, since I didn't want the console window to appear. My application exits with a call to sys.exit. However, when this call is executed under pythonw.exe I get an error popup window with the following messeage: ---- start quote ---- Microsoft Visual C++ Runtime Library Runtime Error! Program: C:\Python24\pythonw.exe This application has requested the Runtime to terminate in an unusual way. Please contact the application support team for more information ---- end quote ---- Did you find a solution for this problem? Best Regards, Omer Korkmaz Ext: 3138 Dikkat: Bu elektronik posta mesaji kisisel ve ozeldir. Eger size gonderilmediyse lutfen gondericiyi bilgilendirip mesaji siliniz.Firmamiza gelen ve giden mesajlar virus taramasindan gecirilmekte, guvenlik nedeni ile kontrol edilerek saklanmaktadir.Mesajdaki gorusler gondericiye ait olup HAVELSAN A.S. resmi gorusu olmak zorunda degildir. Attention: This e-mail message is private and privileged.If you are not the recipient for whom this e-mail message is intended, please notify the sender immediately and delete this e-mail message from your system.All sent and received e-mail messages go through a virus scan in our company, and because of security reasons, they are stored after being controlled.Any opinions presented in this e-mail message are solely those of the author and do not necessarily represent HAVELSAN A.S.'s formal and authorized views. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sreeram at tachyontech.net Thu Jul 20 02:24:33 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Thu, 20 Jul 2006 11:54:33 +0530 Subject: restricted environment In-Reply-To: <1153352773.212473.22590@h48g2000cwc.googlegroups.com> References: <1153350361.200346.193090@s13g2000cwa.googlegroups.com> <7xslkxmavx.fsf@ruckus.brouhaha.com> <1153352773.212473.22590@h48g2000cwc.googlegroups.com> Message-ID: <44BF21A1.9080502@tachyontech.net> Gabriele *darkbard* Farina wrote: > The first attempt to reach my goal was to override the __import__ > function to limit it working on modules that can be used and on custom > import directories that can be accessed. Then I executed the scripts > using exec. There is any security problem related to this solution ? This won't work. Creating a secure restricted execution environment is very hard. FYI, there is an ongoing discussion on python-dev about a new attempt at something like rexec for python 2.6+. [sreeram;] -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From jjlee at reportlab.com Sun Jul 9 11:00:15 2006 From: jjlee at reportlab.com (John J. Lee) Date: Sun, 09 Jul 2006 15:00:15 GMT Subject: xpath question... References: Message-ID: <871wsuq0w0.fsf@reportlab.com> "bruce" writes: > i have the following section of test code where i'm trying to get the > attribute of a frame > > > i'm trying to print/get the src value. the xpath query that i have displays > the "src" attribute in the Xpather/Firefox plugin. however, i can't quite > figure out how to get the underlying value in my test app... > > sxpath = "/html/frameset/frame[2]/attribute::src" > # s contains HTML not XML text > d = libxml2dom.parseString(s, html=1) > > #get the tr list > tr1 = d.xpath(sxpath) > > url = tr1[0] > > #get the url/link >>semester page > #link = br.find_link(nr=1) > > #url = link.url > print "link = ",url > sys.exit() > > err output > link = > > -------------------------------------- > > i'm not sure what i need to add to the line > url = tr1 > to resolve the issue/error... It *looks* like "err output" is just a string you typed into your message? If so, that's not "an error" in the usual sense (there's no traceback): rather, it's just output you didn't expect. When somebody what you wrote, though, they must go through the following laborious thought process: Is that string part of the literal text output by your program, or are you indicating that you saw a traceback that contains the following line ("link = ...")? Or is it something you just typed in to your message to indicate that the result is unexpected to you? If there's a traceback, post the full traceback. If that is the literal output, you should say so explicitly, or make it clear through copy/paste of a shell session: """ $ my-test-prog.py err output link = $ """ Back to your problem: The output is not unexpected, though (though I don't know libxml2dom). First, if you're bent on using XPath, you may be better off with module lxml, which I think is a more recent and friendlier wrapper of libxml2 / libxslt. Second, you're almost there: you're just getting back an object representing the attribute, rather than the string you're looking for. You simply need to ask the object for its string representation. How that's done depends on the module, but it looks like you have to call a method explicitly in this case (I can't find the libxml2dom docs easily). John From johnjsal at NOSPAMgmail.com Thu Jul 13 10:15:24 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 13 Jul 2006 14:15:24 GMT Subject: running python from a memory stick? In-Reply-To: References: Message-ID: <0Astg.2470$No6.49969@news.tufts.edu> Simon Brunning wrote: > On 7/13/06, John Salerno wrote: >> Is there a way to 'install' and use Python on a memory stick, just as >> you would on any computer? I use Windows, and I know the installation >> does things with the registry, so probably I couldn't use the executable >> file to install it. But is it possible to do it some other way, such as >> how you might build it yourself on Linux (although I don't know how to >> do that yet) and then just write and run scripts normally straight from >> your memory stick? > > Google for Movable Python. > Eh, call me uptight but I like using the "authentic" version of Python, not any kinds of special versions with extra add-ons, especially ones I'd have to pay for. From steve at holdenweb.com Mon Jul 24 10:21:04 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 24 Jul 2006 15:21:04 +0100 Subject: _mssql on Python 2.5 Beta 2 In-Reply-To: <1153749662.564489.132420@s13g2000cwa.googlegroups.com> References: <1153748064.876893.262590@i3g2000cwc.googlegroups.com> <1153749662.564489.132420@s13g2000cwa.googlegroups.com> Message-ID: mattjohnthomson at googlemail.com wrote: > Steve Holden wrote: > >>You aren't using the same library you used with 2.4, by any chance? >>Compiled extensions are specific to a particular major version of >>Python, so (for example) 2.3 extension modules won't run under 2.4. >>Though normally, IIRC, that would give you problems on import, so this >>may be no help at all (in which case, sorry!) > > > Steve, > I recompiled the library for the 2.5 version. If it makes a > difference, I used the altinstall option for python, so it's installed > as python2.5. > Nope, sounds like you've done everything right. Sorry ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From bedouglas at earthlink.net Mon Jul 10 01:12:42 2006 From: bedouglas at earthlink.net (bruce) Date: Sun, 9 Jul 2006 22:12:42 -0700 Subject: possible issue with mechanize/python parsing In-Reply-To: Message-ID: <05aa01c6a3df$7a9f42d0$0301a8c0@Mesa.com> hi... it appears that i'm running into a possible problem with mechanize/browser/python rgarding the "select_form" method. i've tried the following and get the error listed: br.select_form(nr = 1) br.select_form(name="foo") br.select_form(name=foo) br.select_form(name="foo") here's a short test app, as well as the html to be placed in a test data file.... everything is straight forward... any thoughts/comments/ideas would be helpful. i have the latest mechanize from the svn repos. thanks -bruce the error i get is: Traceback (most recent call last): File "./axess.py", line 127, in ? br.select_form(name = "main") File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 354, in select_form mechanize._mechanize.BrowserStateError: not viewing HTML test code ------------------------------- #! /usr/bin/env python #test python script import re import libxml2dom import urllib import urllib2 import sys, string #import numarray import httplib from mechanize import Browser import mechanize ######################## # # Parsing App Information ######################## # datafile tfile = open("stanford.dat", 'wr+') cj = mechanize.CookieJar() br = Browser() if __name__ == "__main__": # main app #---------------------------- # start trying to get the stanford pages cj = mechanize.CookieJar() br = Browser() fh = open('axess.dat') s = fh.read() fh.close() br.open("file:///home/test/axess.dat") print "foo" # particular cookiejar) br.set_cookiejar(cj) # Log information about HTTP redirects and Refreshes. ##br.set_debug_redirects(True) # Log HTTP response bodies (ie. the HTML, most of the time). #WARNING!!!!!! using this will apparently #kill the Browser instance!!! #br.set_debug_responses(True) # Print HTTP headers. # br.set_debug_http(True) # br.set_handle_redirect(True) # br.set_handle_referer(True) response = br.response() # this is a copy of response #get the option/semester name snamepath = "/html/body[@class='PSPAGE']/form[2]/table/tr[7]/td[3]/select/@name" #get the form name fnamepath = "/html/body[@class='PSPAGE']/form[2]/attribute::name" s = response.read() print response.read() print s #we now have the semester page... d = libxml2dom.parseString(s, html=1) #get option name sem_optname = d.xpath(snamepath) sem_optname = sem_optname[0].nodeValue print "sem = ",sem_optname ff = d.xpath(fnamepath) fname = ff[0].nodeValue print "fname = ",fname br.select_form(name = "main") print "ssssss" sys.exit() data file ------------------------------- View Schedule of Classes
Help

 
Select the term you wish to search, and then click Basic Search,
Advanced Search, or Independent Study Search to continue.
From phil_nospam_schmidt at yahoo.com Tue Jul 11 11:05:54 2006 From: phil_nospam_schmidt at yahoo.com (Phil Schmidt) Date: 11 Jul 2006 08:05:54 -0700 Subject: os.access() problem Message-ID: <1152630354.206058.11920@s13g2000cwa.googlegroups.com> I just got a new PC with Windows XP, and I want to run Leo on it. Leo uses the os.access() function to check for read-only files. For some reason, os.access(, os.W_OK) always returns false. I wrote a 2-liner Python script to just test os.access on any file. I have tried this with Python 2.4 and 2.5b1. I have uninstalled and re-installed Python and Leo. I have fiddled with file permissions on the target files as well as on the Python installation itself. I have used cacls to check the access control lists (and although I'm not exactly certain what to do with this information, it appears to be ok - I think). None of the above has helped me to identify or fix the problem. A scan of the Python newsgroup suggests that os.access() may not be the best way to check for read-only, but the discussion is a bit deeper than my understanding, so I'm not sure there's anything to it in this case. I realize this must be a Windows permissions thing, but I just can't figure it out. I'm no expert in Windows security beyond basic permissions, so I could be missing something simple. Can anyone offer any suggestions? Thanks, Phil From webraviteja at gmail.com Sat Jul 1 16:11:24 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 1 Jul 2006 13:11:24 -0700 Subject: I have 100 servers which need a new backup server added to a text file, and then the backup agent restarted. In-Reply-To: <1151779451.154552.268710@p79g2000cwp.googlegroups.com> References: <1151750046.245198.61860@d56g2000cwd.googlegroups.com> <1151759041.237922.292710@v61g2000cwv.googlegroups.com> <1151779451.154552.268710@p79g2000cwp.googlegroups.com> Message-ID: <1151784684.655279.192040@m73g2000cwd.googlegroups.com> gavino wrote: > list of servers L.txt > #cat L.txt > config file is /var/bkupexec/agent.cfg need to add "tell epobackup" to > bottom of file > # cat "tell epobackup" >> /var/bkupexec/agent.cfg > agent is /etc/init.d/agent.ini stop (and then start) > # /etc/init.d/agent.init stop > # /etc/init.d/agent.init start > os=redhat ent 4ES > I intend to use root password which is same for all 100 servers. > #now I'm stuck Read L.txt from (not your shell as you seem to be doing) Python and connect to each one from pxssh, and send the commands you listed. I am afraid, you will have to readup and experiment on a smaller scale. The sample I pointed you to is a rather simple one and you don't seem to have even tried it. From grante at visi.com Tue Jul 18 00:13:05 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 18 Jul 2006 04:13:05 -0000 Subject: range() is not the best way to check range? References: <1153190471.753499.40630@i42g2000cwa.googlegroups.com> Message-ID: <12bonuhgbvfd16f@corp.supernews.com> On 2006-07-18, Summercoolness at gmail.com wrote: > it seems that range() can be really slow: > > the following program will run, and the last line shows how long it ran > for: > > import time > > startTime = time.time() > > a = 1.0 > for i in range(0, 30000): > if i in range (0, 10000): > a += 1 > if not i % 1000: print i > > print a, " ", round(time.time() - startTime, 1), "seconds" > or is there an alternative use of range() or something similar that can > be as fast? Creating and then searching a 10,000 element list to see if a number is between two other numbers is insane. Using xrange as somebody else suggested is also insane. If you want to know if a number is between two other numders, for pete's sake use the comparison operator like god intended. if 0 <= i <= 10000: -- Grant Edwards grante Yow! ANN JILLIAN'S HAIR at makes LONI ANDERSON'S visi.com HAIR look like RICARDO MONTALBAN'S HAIR! From subramanian2003 at indiatimes.com Sat Jul 1 03:47:15 2006 From: subramanian2003 at indiatimes.com (subramanian2003) Date: Sat, 01 Jul 2006 07:47:15 -0000 Subject: missing feature classes and missing fields Message-ID: <200607010642.MAA21799@WS0005.indiatimes.com> Hello All, How can I check missing feature classes in a folder/personal geodatabase using python script. And how can I check missing fields in shape files. And also I want to check the attribute values using python. Thnx, Subramanian. From kenneth.m.mcdonald at sbcglobal.net Fri Jul 7 14:26:42 2006 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Fri, 07 Jul 2006 13:26:42 -0500 Subject: Idea/request for new python mailing list/newsgroup. Message-ID: <44AEA762.4040808@sbcglobal.net> Would a mailing list and newsgroup for "python contributions" be of interest? I currently have a module which is built on top of, and is intended to semantically replace, the 're' module. I use it constantly to great advantage, but have not made it public for the following reasons: * The API should probably be cleaned up in places. * Documentation is reasonable, but should be more organized and put into D'Oxygen format. It also needs to be slightly updated. * A few more unit tests should be added. * A few features of regular expressions are not yet available. * Some capabilities go well beyond those of the re module, and there is the potential for much more. I'd very much likes a ML/newsgroup wherein potential python contributors could * Post alphas/betas and seek feedback. * Request volunteer help to finish a project. * Discuss details of implementation (API, useful vs. nonuseful functionality, etc.) * etc. etc. etc. For example, my library is extremely useful as is, but I currently don't have much time to do the things (API cleanup, doc organization, potential additional features) that I'd like to see before a public release. I also don't have the time or knowledge to set it up as an online project. On the other hand, I'd certainly be willing to share my experiences and knowledge of the current codebase. An appropriate mailing list or newsgroup could give feedback for when I do have time and, if my library is interesting enough, possibly even provide some help. One thing to emphasize is that this should not be a list/newsgroup where people post requests or ideas. Requests or ideas for additional functionality are a dime a dozen. The sole intent of this group would be to provide a forum for discussion and coordination for work which is well under way, but needs input or further help. Cheers, Ken From uval at rz.uni-karlsruhe.de Tue Jul 25 14:08:32 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Tue, 25 Jul 2006 20:08:32 +0200 Subject: self question In-Reply-To: <1153849559.477348.197160@h48g2000cwc.googlegroups.com> References: <1153849559.477348.197160@h48g2000cwc.googlegroups.com> Message-ID: dan.gass at gmail.com schrieb: >> cnt = 1 >> def foo(): >> global cnt >> cnt += 1 >> return cnt >> >> def bar(x=foo()): >> print x >> >> bar() # 2 >> bar() # 2 >> bar() # 2 > > Looks to me like you want to use the following programming pattern to > get dynamic default arguments: > > cnt = 1 > def foo(): > global cnt > cnt += 1 > return cnt > > def bar(x=None): > if x is None: > x = foo() > print x > > bar() # 2 > bar() # 3 > bar() # 4 yes, I haven't thought of that nowI changed my class to class Graph: settings = { "NumNodes" : 10, "MinNodes" : 2, "MaxNodes" : 5 } def randomizeEdges(self, lowhigh = (settings["MinNodes"], settings["MaxNodes"])): low, high = lowhigh for node in self.nodes: x = random.randint(low, high) # link the nodes maybe the only minor point is that no relationship can be expressed settings = { "NumNode" : 10, "MinNode" : settings["NumNode"] / 2, "MaxNode" : settings["NumNode"] } but I think the solution is nevertheless ok Regards, Daniel From fredrik at pythonware.com Tue Jul 4 03:16:53 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 4 Jul 2006 09:16:53 +0200 Subject: converting file formats to txt References: <1151995347.533312.99390@m73g2000cwd.googlegroups.com> Message-ID: Marc 'BlackJack' Rintsch wrote: > What do you mean by 'fileformats'? A script that automagically converts > *anything* to text? What about pictures? that's a one-and-a-half-liner: import Image, sys; print list(Image.open(sys.argv[1]).getdata()) From chris at kateandchris.net Wed Jul 19 11:30:24 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Wed, 19 Jul 2006 11:30:24 -0400 Subject: WSDL and SOAP? In-Reply-To: <44B8073A.50304@tobiah.org> References: <44B8073A.50304@tobiah.org> Message-ID: <20060719153024.GA12761@kateandchris.net> If you want to do it in python, pywebsvcs is the place for both SOAPpy and ZSI, two SOAP frameworks. The WSDL defines the service's API. Both SOAPpy and ZSI allow you to use that to construct SOAP messages and handle the conversion from basic python types (int, string, etc) to SOAP encoding of those types. -Chris On Fri, Jul 14, 2006 at 02:06:02PM -0700, tobiah wrote: > I need to link an event registration site to > a housing site. From what I can gather, I > make a call to some url that ends in WSDL, and > get some XML back from the housing site. Now I'm > supposed to make this into an object and call it > here and there through SOAP? Is that how it works? > > Is this the best place to start?: > > http://pywebsvcs.sourceforge.net/ > > > Thanks, > > Toby > -- > http://mail.python.org/mailman/listinfo/python-list From claird at lairds.us Tue Jul 18 10:00:33 2006 From: claird at lairds.us (Cameron Laird) Date: Tue, 18 Jul 2006 14:00:33 +0000 Subject: execute a shell script from a python script References: <1153167113.519051.150740@s13g2000cwa.googlegroups.com> <1153169302.675321.90640@p79g2000cwp.googlegroups.com> <1153180786.930224.310500@s13g2000cwa.googlegroups.com> <1153187926.407414.201530@m73g2000cwd.googlegroups.com> Message-ID: <156vo3-ub3.ln1@lairds.us> In article <1153187926.407414.201530 at m73g2000cwd.googlegroups.com>, Simon Forman wrote: >spec wrote: >> Thanks, actually there are no args, is there something even simpler? >> >> Thanks >> Frank > >you could try os.system() > >>From the docs: > >system(command) . [more detail] . . I'm concerned the follow-ups in this thread have been too subtle. Here is what you need to know: use system(). A model such as import os os.system("my_script") fulfills exactly the requirements the original poster described. From jonsmirl at gmail.com Mon Jul 31 20:37:51 2006 From: jonsmirl at gmail.com (Jon Smirl) Date: Mon, 31 Jul 2006 20:37:51 -0400 Subject: Help with arrays of strings Message-ID: I only have a passing acquaintance with Python and I need to modify some existing code. This code is going to get called with 10GB of data so it needs to be fairly fast. http://cvs2svn.tigris.org/ is code for converting a CVS repository to Subversion. I'm working on changing it to convert from CVS to git. The existing Python RCS parser provides me with the CVS deltas as strings.I need to get these deltas into an array of lines so that I can apply the diff commands that add/delete lines (like 10 d20, etc). What is the most most efficient way to do this? The data structure needs to be able to apply the diffs efficently too. The strings have embedded @'s doubled as an escape sequence, is there an efficient way to convert these back to single @'s? After each diff is applied I need to convert the array of lines back into a string, generate a sha-1 over it and then compress it with zlib and finally write it to disk. The 10GB of data is Mozilla CVS when fully expanded. Thanks for any tips on how to do this. Jon Smirl jonsmirl at gmail.com From jo at durchholz.org Mon Jul 17 06:23:01 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Mon, 17 Jul 2006 12:23:01 +0200 Subject: What is a type error? In-Reply-To: References: <1153091295.520674.287230@i42g2000cwa.googlegroups.com> Message-ID: Rob Warnock schrieb: > Joachim Durchholz wrote: > +--------------- > | INSERT cannot be expressed in terms of assignment. INSERT creates a new > | record; there's no way that assignment in a language like C can create a > | new data structure! The same goes for DELETE. > +--------------- > > Well, what about "malloc()" & "free()"? These do exactly what assignment cannot do. The correspondence between SQL and C would be: INSERT - malloc() (create a new data structure) DELETE - free() (destroy a data structure) UPDATE - assignment (change data within a data structure) Regards, Jo From claird at lairds.us Sat Jul 8 21:52:47 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 9 Jul 2006 01:52:47 +0000 Subject: first book about python References: <1152405704.389754@athnrd02> Message-ID: In article <1152405704.389754 at athnrd02>, IOANNIS MANOLOUDIS wrote: >I want to learn python. >I plan to buy a book. I always find printed material more convenient than >reading on-line tutorials. >I don't know PERL or any other scripting language. I only know some BASH >programming. I am looking for a book which will help me get started and >should contain the foundations. I am not looking for the Python bible. >Any recommendations? >Ioannis > http://groups.google.com/group/comp.lang.python/msg/3539b0fbd9c04db8 http://groups.google.com/groups?as_q=book+beginner&num=10&scoring=d&hl=en&as_ugroup=comp.lang.python* http://diveintopython.org/ From fkaslan at yahoo.com Thu Jul 20 10:40:47 2006 From: fkaslan at yahoo.com (Kilicaslan Fatih) Date: Thu, 20 Jul 2006 07:40:47 -0700 (PDT) Subject: Help Needed. Removing a Folder Problem In-Reply-To: <44BF8B0D.6070605@websafe.com> Message-ID: <20060720144048.41877.qmail@web53103.mail.yahoo.com> --- Larry Bates wrote: > Note the error is permission denied. I would guess > that > either the file has read-only flag set or perhaps > the > 'cccc' program is still running and has the file > open > in a separate thread so you can't delete the > directory > until it has completed. You should take a look at > the > subprocess module and use something like (not > tested): > > retcode = call([r'cccc C:\copiedfiles\*.*', > cmd_out]) > > This will wait for execution of cccc to complete > prior > to returning. > > -Larry Bates > > > Kilicaslan Fatih wrote: > > When I push a button to trigger the code: > > > > def runCCCC(self, event): > > cmd_out = self.A_com() > > if App.runF != "": > > os.mkdir('C:\copiedFiles') > > > > > for item in App.runF: > > App.beCopied = str(item) > > shutil.copy(App.beCopied, > > > 'C:\copiedFiles') > > cmd = 'cccc C:\copiedFiles\*.*' + > cmd_out > > os.system(cmd) > > shutil.rmtree('C:\copiedFiles') > > else: > > tkMessageBox.showinfo("Window Text", > > "Please Firstly Browse and Insert A File") > > > > > > I encountered this error: > > > > Traceback (most recent call last): > > File "C:\Python24\lib\lib-tk\Tkinter.py", line > 1345, > > in __call__ > > return self.func(*args) > > File "C:\Python24\TkScripts\RCFolder.py", line > 61, > > in runCCCC > > shutil.rmtree('C:\copiedFiles', > > ignore_errors=False)# OLMADI!!! > > File "C:\Python24\lib\shutil.py", line 168, in > > rmtree > > onerror(os.remove, fullname, sys.exc_info()) > > File "C:\Python24\lib\shutil.py", line 166, in > > rmtree > > os.remove(fullname) > > OSError: [Errno 13] Permission denied: > > 'C:\\copiedFiles\\Analog.c' > > > > 1. What I want to do is to get the list of files I > > inserted to a Listbox, > > 2. Creating a folder,(C:\copiedFiles) > > 3. Copying all of these files to this folder with > the > > same names, > > 4. Running CCCC for all of the files in this > folder, > > 5. Than removing this folder. > > > > Can anyone enlighten me on this Error I have got > and > > how to solve it? > > > > Regards > > > > > > __________________________________________________ > > Do You Yahoo!? > > Tired of spam? Yahoo! Mail has the best spam > protection around > > http://mail.yahoo.com Thank you very much for your reply, during my wait for an answer I changed the code. 1. First created the folder 2. Then copied all the files in the listbox to the folder 3. Run CCCC 3. changed the files' permissions in the folder 4. Then try to remove the folder def runCCCC(self, event): cmd_out = self.A_com() if App.runF != "": print len(App.runF) os.mkdir('C:\copiedFiles') for item in App.runF: shutil.copy(item, 'C:\copiedFiles') cmd = 'cccc C:\copiedFiles\*.*' + cmd_out os.system(cmd) for root,dir,files in os.walk("C:\copiedFiles"): print len(files) for j in files: fille = os.path.join(root,j) os.chmod(fille, 0700) shutil.rmtree('C:\copiedFiles') else: tkMessageBox.showinfo("Window Text", "Please Firstly Browse and Insert A File") I got another error this time: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "C:\Python24\TkScripts\RCFolder.py", line 56, in runCCCC shutil.copy(item, 'C:\copiedFiles') File "C:\Python24\lib\shutil.py", line 81, in copy copyfile(src, dst) File "C:\Python24\lib\shutil.py", line 48, in copyfile fdst = open(dst, 'wb') IOError: [Errno 13] Permission denied: 'C:\\copiedFiles\\Generic_IO.h' I have more than 200 files in the folder. I will have nearly 1000 files in each execution. I don't know why I encountered this error. I am still searching the reason, and I will check the subprocess module in anyway. Regards __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From jdhunter at ace.bsd.uchicago.edu Sun Jul 9 15:43:43 2006 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 09 Jul 2006 14:43:43 -0500 Subject: tk filesave dialog triggers unexpected destroy event Message-ID: <87ejwu4l8w.fsf@peds-pc311.bsd.uchicago.edu> The following behavior surprised me. I have a Tk window and launch a file save dialog from it. When the filesave dialog is finished, it calls callbacks bound to the destroy event on the main window. Is this expected, and can I avoid this? To expose the problem, run this script and click the mouse button over the application window. When the file save dialog is through, the function "callback" is called, which I did not expect because I bound this callback to the window destroy event. Thanks for any advice. Using Tk 1.177 JDH import Tkinter as Tk from tkFileDialog import asksaveasfilename def button(event): fname = asksaveasfilename( title='Save the figure' ) window = Tk.Tk() frame = Tk.Frame(window, width=500,height=500) frame.bind('', button) frame.pack() def callback(*args): print 'called callback' window.bind("", callback) window.mainloop() From chan.neo at gmail.com Tue Jul 4 02:48:19 2006 From: chan.neo at gmail.com (Netkiller) Date: 3 Jul 2006 23:48:19 -0700 Subject: my newsgroup base database. (test) In-Reply-To: <1151995580.254033.47140@a14g2000cwb.googlegroups.com> References: <1151995456.169775.106990@m73g2000cwd.googlegroups.com> <1151995580.254033.47140@a14g2000cwb.googlegroups.com> Message-ID: <1151995699.545871.41530@j8g2000cwa.googlegroups.com> Netkiller ??? > Netkiller ??? > > > #!/usr/bin/python > > # -*- coding: utf-8 -*- > > """ > > Project: Network News Transport Protocol Server Program > > Description: > > ????????????BBS????NNTP??????? > > Database SQL Script follow: -- phpMyAdmin SQL Dump -- version 2.7.0-rc1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jul 04, 2006 at 02:47 PM -- Server version: 4.1.18 -- PHP Version: 5.0.5 -- -- Database: `usenet` -- -- -------------------------------------------------------- -- -- Table structure for table `article` -- DROP TABLE IF EXISTS `article`; CREATE TABLE IF NOT EXISTS `article` ( `Number` int(10) unsigned NOT NULL auto_increment, `MessageID` varchar(255) NOT NULL default '', `body` text NOT NULL, `Date` datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (`Number`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=40 ; -- -- Dumping data for table `article` -- INSERT INTO `article` VALUES (25, '', 'From: "NEO" \r\nNewsgroups: cn.test\r\nSubject: test\r\nDate: Fri, 30 Jun 2006 17:14:17 +0800\r\nLines: 3\r\nX-Priority: 3\r\nX-MSMail-Priority: Normal\r\nX-Newsreader: Microsoft Outlook Express 6.00.2900.2180\r\nX-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.2180\r\nX-RFC2646: Format=Flowed; Original\r\n\r\ntest ! \r\n\r\n\r\n', '2006-06-30 17:14:17'); INSERT INTO `article` VALUES (26, '', 'Date: Tue, 04 Jul 2006 11:34:54 +0800\r\nFrom: My Usenet \r\nUser-Agent: Thunderbird 1.5.0.4 (Windows/20060516)\r\nMIME-Version: 1.0\r\nNewsgroups: cn.test\r\nSubject: Re: aaaaaa\r\nContent-Type: text/plain; charset=ISO-8859-1; format=flowed\r\nContent-Transfer-Encoding: 7bit\r\n\r\n wrote:\r\n> test ! \r\n> \r\n> \r\n-------------\r\n', '2006-07-04 11:34:54'); INSERT INTO `article` VALUES (27, '', 'Date: Tue, 04 Jul 2006 13:57:07 +0800\r\nFrom: My Usenet \r\nUser-Agent: Thunderbird 1.5.0.4 (Windows/20060516)\r\nMIME-Version: 1.0\r\nNewsgroups: cn.test\r\nSubject: bbbbbb\r\nContent-Type: text/plain; charset=ISO-8859-1; format=flowed\r\nContent-Transfer-Encoding: 7bit\r\n\r\nbbbbbbbbbbb\r\n', '2006-07-04 13:57:07'); INSERT INTO `article` VALUES (28, '', 'Date: Tue, 04 Jul 2006 13:58:17 +0800\r\nFrom: My Usenet \r\nUser-Agent: Thunderbird 1.5.0.4 (Windows/20060516)\r\nMIME-Version: 1.0\r\nNewsgroups: cn.test\r\nSubject: Re: bbbbbb\r\nContent-Type: text/plain; charset=ISO-8859-1; format=flowed\r\nContent-Transfer-Encoding: 7bit\r\n\r\nMy Usenet wrote:\r\n> bbbbbbbbbbb\r\n', '2006-07-04 13:58:17'); INSERT INTO `article` VALUES (29, '', 'Date: Tue, 04 Jul 2006 14:28:00 +0800\r\nFrom: My Usenet \r\nUser-Agent: Thunderbird 1.5.0.4 (Windows/20060516)\r\nMIME-Version: 1.0\r\nNewsgroups: cn.test\r\nSubject: cccccc\r\nContent-Type: text/plain; charset=ISO-8859-1; format=flowed\r\nContent-Transfer-Encoding: 7bit\r\n\r\ncccccc\r\n', '2006-07-04 14:28:00'); INSERT INTO `article` VALUES (30, '', 'Date: Tue, 04 Jul 2006 14:29:02 +0800\r\nFrom: My Usenet \r\nUser-Agent: Thunderbird 1.5.0.4 (Windows/20060516)\r\nMIME-Version: 1.0\r\nNewsgroups: cn.test\r\nSubject: Re: cccccc My Usenet \r\nContent-Type: text/plain; charset=ISO-8859-1; format=flowed\r\nContent-Transfer-Encoding: 7bit\r\n\r\nTue wrote:\r\n> cccccc\r\n', '2006-07-04 14:29:02'); INSERT INTO `article` VALUES (31, '', 'Date: Tue, 04 Jul 2006 14:29:22 +0800\r\nFrom: My Usenet \r\nUser-Agent: Thunderbird 1.5.0.4 (Windows/20060516)\r\nMIME-Version: 1.0\r\nNewsgroups: cn.test\r\nSubject: Re: cccccc My Usenet\r\nContent-Type: text/plain; charset=ISO-8859-1; format=flowed\r\nContent-Transfer-Encoding: 7bit\r\n\r\nTue wrote:\r\n> Tue wrote:\r\n>> cccccc\r\n', '2006-07-04 14:29:22'); INSERT INTO `article` VALUES (32, '', 'Date: Tue, 04 Jul 2006 14:29:55 +0800\r\nFrom: My Usenet \r\nUser-Agent: Thunderbird 1.5.0.4 (Windows/20060516)\r\nMIME-Version: 1.0\r\nNewsgroups: cn.test\r\nSubject: ddddd\r\nContent-Type: text/plain; charset=ISO-8859-1; format=flowed\r\nContent-Transfer-Encoding: 7bit\r\n\r\nddddd\r\n', '2006-07-04 14:29:55'); INSERT INTO `article` VALUES (33, '', 'Date: Tue, 04 Jul 2006 14:31:32 +0800\r\nFrom: My Usenet \r\nUser-Agent: Thunderbird 1.5.0.4 (Windows/20060516)\r\nMIME-Version: 1.0\r\nNewsgroups: cn.test\r\nSubject: Re: dddddMy Usenet \r\nContent-Type: text/plain; charset=ISO-8859-1; format=flowed\r\nContent-Transfer-Encoding: 7bit\r\n\r\nTue wrote:\r\n> ddddd\r\n', '2006-07-04 14:31:32'); INSERT INTO `article` VALUES (34, '', 'Date: Tue, 04 Jul 2006 14:31:45 +0800\r\nFrom: My Usenet \r\nUser-Agent: Thunderbird 1.5.0.4 (Windows/20060516)\r\nMIME-Version: 1.0\r\nNewsgroups: cn.test\r\nSubject: Re: bbbbbb\r\nContent-Type: text/plain; charset=ISO-8859-1; format=flowed\r\nContent-Transfer-Encoding: 7bit\r\n\r\nMy Usenet wrote:\r\n> bbbbbbbbbbb\r\n', '2006-07-04 14:31:45'); INSERT INTO `article` VALUES (35, '', 'Date: Tue, 04 Jul 2006 14:32:04 +0800\r\nFrom: My Usenet \r\nUser-Agent: Thunderbird 1.5.0.4 (Windows/20060516)\r\nMIME-Version: 1.0\r\nNewsgroups: cn.test\r\nSubject: cccccc\r\nContent-Type: text/plain; charset=ISO-8859-1; format=flowed\r\nContent-Transfer-Encoding: 7bit\r\n\r\ncccccc\r\n', '2006-07-04 14:32:04'); INSERT INTO `article` VALUES (36, '', 'Date: Tue, 04 Jul 2006 14:32:15 +0800\r\nFrom: My Usenet \r\nUser-Agent: Thunderbird 1.5.0.4 (Windows/20060516)\r\nMIME-Version: 1.0\r\nNewsgroups: cn.test\r\nSubject: Re: cccccc\r\nContent-Type: text/plain; charset=ISO-8859-1; format=flowed\r\nContent-Transfer-Encoding: 7bit\r\n\r\nMy Usenet wrote:\r\n> cccccc\r\n', '2006-07-04 14:32:15'); INSERT INTO `article` VALUES (37, '', 'Date: Tue, 04 Jul 2006 14:32:18 +0800\r\nFrom: My Usenet \r\nUser-Agent: Thunderbird 1.5.0.4 (Windows/20060516)\r\nMIME-Version: 1.0\r\nNewsgroups: cn.test\r\nSubject: Re: cccccc\r\nContent-Type: text/plain; charset=ISO-8859-1; format=flowed\r\nContent-Transfer-Encoding: 7bit\r\n\r\nMy Usenet wrote:\r\n> cccccc\r\n', '2006-07-04 14:32:18'); INSERT INTO `article` VALUES (38, '', 'Date: Tue, 04 Jul 2006 14:32:26 +0800\r\nFrom: My Usenet \r\nUser-Agent: Thunderbird 1.5.0.4 (Windows/20060516)\r\nMIME-Version: 1.0\r\nNewsgroups: cn.test\r\nSubject: Re: cccccc\r\nContent-Type: text/plain; charset=ISO-8859-1; format=flowed\r\nContent-Transfer-Encoding: 7bit\r\n\r\nMy Usenet wrote:\r\n> cccccc\r\n', '2006-07-04 14:32:26'); INSERT INTO `article` VALUES (39, '', 'Date: Tue, 04 Jul 2006 14:32:32 +0800\r\nFrom: My Usenet \r\nUser-Agent: Thunderbird 1.5.0.4 (Windows/20060516)\r\nMIME-Version: 1.0\r\nNewsgroups: cn.test\r\nSubject: Re: cccccc\r\nContent-Type: text/plain; charset=ISO-8859-1; format=flowed\r\nContent-Transfer-Encoding: 7bit\r\n\r\nMy Usenet wrote:\r\n> cccccc\r\n', '2006-07-04 14:32:32'); -- -------------------------------------------------------- -- -- Table structure for table `list` -- DROP TABLE IF EXISTS `list`; CREATE TABLE IF NOT EXISTS `list` ( `id` int(10) unsigned NOT NULL auto_increment, `group` varchar(255) NOT NULL default '', `last` varchar(10) NOT NULL default '', `first` varchar(10) NOT NULL default '', `p` char(1) default 'y', `date` datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='RFC977 3.6.1. LIST' AUTO_INCREMENT=3 ; -- -- Dumping data for table `list` -- INSERT INTO `list` VALUES (1, 'cn.test', '10', '5', 'y', '0000-00-00 00:00:00'); INSERT INTO `list` VALUES (2, 'cn.comp.os', '10', '5', 'y', '2006-06-27 00:00:00'); From jjlee at reportlab.com Sun Jul 9 10:33:55 2006 From: jjlee at reportlab.com (John J. Lee) Date: Sun, 09 Jul 2006 14:33:55 GMT Subject: python/xpath question... References: Message-ID: <87ac7iq23w.fsf@reportlab.com> (Damn gmane's authorizor, I think I lost four postings because the auth messages went to my work email address (and I thought the authorization was supposed to be one-time only per group anyway??). I deleted them as spam since I hadn't posted from there for days :-( Grrr. At least I could reconstruct this one...) "bruce" writes: > for guys with python/xpath expertise.. > > i'm playing with xpath.. and i'm trying to solve an issue... > > i have the following kind of situation where i'm trying to get certain data. > > i have a bunch of tr/td... > > i can create an xpath, that gets me all of the tr.. i only want to get the > sibling tr up until i hit a 'tr' that has a 'th' anybody have an idea as to > how this query might be created?.. [...] ((//tr/th)[2]/../following-sibling::tr/td/..)[count(.|((//tr/th)[3]/../preceding-sibling::*))=count((//tr/th)[3]/../preceding-sibling::*)] which makes use of the following idiom for writing an intersection: $set1[count(.|$set2)=count($set2)] and gets the second group in the sequence you describe. IMHO, this illustrates what happens when XPath is pushed too far ;-) I don't see an easier way, but perhaps I missed one. Example code: (Note that the expression used here doesn't get any trailing group of tr elements if there's no terminating tr/th -- that fits your specification, but may not be what you really wanted. To fix that, meditate on the above expression for an hour or two <0.8 wink>.) #--------------------------------------------------------- def xpath(path, source): import StringIO import pprint from lxml import etree f = StringIO.StringIO(source) tree = etree.parse(f) r = tree.xpath(path) #return "\n".join(etree.tostring(el) for el in r) return pprint.pformat([etree.tostring(el) for el in r]) simple = """\ A B C D E F G H I """ for i in range(3): expr = '((//tr/th)[%s]/../following-sibling::tr/td/..)[count(.|((//tr/th)[%s]/../preceding-sibling::*))=count((//tr/th)[%s]/../preceding-sibling::*)]' % (i+1, i+2, i+2) print "---------------------" print xpath(expr, simple) #--------------------------------------------------------- john[0]$ tst.py --------------------- ['B\n', 'C\n'] --------------------- ['E\n', 'F\n'] --------------------- [] Knowing what you're doing, though, you'd probably be better off with BeautifulSoup than XPath. Also note that mechanize (which I know you're using) only supports BeautifulSoup 2 at present. You can't use BeautifulSoup 3 yet (I hope to fix that 'RSN'). John From paul at boddie.org.uk Mon Jul 17 05:12:49 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 17 Jul 2006 02:12:49 -0700 Subject: Augument assignment versus regular assignment References: <1152328454.430620.59050@m79g2000cwm.googlegroups.com> <1152424924.533353.323280@75g2000cwc.googlegroups.com> <12b4i7c75nits85@corp.supernews.com> Message-ID: <1153127569.117917.73090@p79g2000cwp.googlegroups.com> Antoon Pardon wrote: > > What the language reference should have said IMO is that in case x > is an attribute reference, index or slicing, the primary expression > will be evaluated only once, as will be the index or slice in the > two latter cases. I think the difficulty here for the author of this particular section of the reference is in describing the mechanisms at work whilst keeping the description at a conceptual level which can be directly connected to the source text in a program. However, apart from providing a vague intuition about how augmented assignment must work, the description doesn't answer all questions effectively, particularly in cases where the actual assignments are not simple local/global name binding operations. One way to consider augmented assignment is as a statement formulated in the following way: setvalue(namespace, name, op(getvalue(namespace, name), expr)) Consider an augmented assignment on a local name: a += b This could be phrased as follows: setname(locals, "a", add(getname(locals, "a"), b)) Or really: setname(locals, "a", add(getname(locals, "a"), getname(locals, "b"))) Consider an augmented assignment on an attribute: a.b += c This could also be phrased similarly: setattr(a, "b", add(getattr(a, "b"), c)) And consider an augmented assignment on an item: a[b] += c This too is phrased similarly: setitem(a, b, add(getitem(a, b), c)) So, as long as you're willing to accept that the setvalue class of operations (setname, setattr, setitem) aren't really evaluating the target of the assignment - strictly, the thing being replaced in the assignment - then only the getvalue class of operations (getname, getattr, getitem) are causing the evaluation of the target. And since setname is just a normal name binding assignment which we know doesn't cause the target to be evaluated, we can assume that the other operations in that class behave similarly. Now, one aspect of evaluation has been skipped in the above explanation: what if we have a "complicated" expression on the left hand side? Consider this: a.f().x += y We could naively write this as follows: setattr(a.f(), "x", add(getattr(a.f(), "x"), y)) However, it looks like we are evaluating at least part of the left hand side twice. Thus, we need to be a bit clearer about what really happens: namespace = a.f() setattr(namespace, "x", add(getattr(namespace, "x"), y)) In order to avoid double evaluation, we first obtain the target namespace (or itemspace, I suppose). Then, we perform the operations as stated above. So, to conclude, augmented assignment involves the evaluation of any expression which gives the target namespace (trivial in the case of local/global name binding, non-trivial otherwise), then a compound operation of the form given above involving two classes of operations, each providing operations to act on names, attributes and items. I doubt that this explanation is simple, clear or efficient enough for the language reference, but then any explanation shouldn't be constrained in terms of complexity in a way that, for example, a tutorial explanation should be. Despite cries of "you must get it now!" from various quarters, I think this thread has been informative, and I'd like to thank you for bringing this matter to the group's attention, Antoon. Paul From larry.bates at websafe.com Thu Jul 20 09:54:21 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 20 Jul 2006 08:54:21 -0500 Subject: Help Needed. Removing a Folder Problem In-Reply-To: References: Message-ID: <44BF8B0D.6070605@websafe.com> Note the error is permission denied. I would guess that either the file has read-only flag set or perhaps the 'cccc' program is still running and has the file open in a separate thread so you can't delete the directory until it has completed. You should take a look at the subprocess module and use something like (not tested): retcode = call([r'cccc C:\copiedfiles\*.*', cmd_out]) This will wait for execution of cccc to complete prior to returning. -Larry Bates Kilicaslan Fatih wrote: > When I push a button to trigger the code: > > def runCCCC(self, event): > cmd_out = self.A_com() > if App.runF != "": > os.mkdir('C:\copiedFiles') > > for item in App.runF: > App.beCopied = str(item) > shutil.copy(App.beCopied, > 'C:\copiedFiles') > cmd = 'cccc C:\copiedFiles\*.*' + cmd_out > os.system(cmd) > shutil.rmtree('C:\copiedFiles') > else: > tkMessageBox.showinfo("Window Text", > "Please Firstly Browse and Insert A File") > > > I encountered this error: > > Traceback (most recent call last): > File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, > in __call__ > return self.func(*args) > File "C:\Python24\TkScripts\RCFolder.py", line 61, > in runCCCC > shutil.rmtree('C:\copiedFiles', > ignore_errors=False)# OLMADI!!! > File "C:\Python24\lib\shutil.py", line 168, in > rmtree > onerror(os.remove, fullname, sys.exc_info()) > File "C:\Python24\lib\shutil.py", line 166, in > rmtree > os.remove(fullname) > OSError: [Errno 13] Permission denied: > 'C:\\copiedFiles\\Analog.c' > > 1. What I want to do is to get the list of files I > inserted to a Listbox, > 2. Creating a folder,(C:\copiedFiles) > 3. Copying all of these files to this folder with the > same names, > 4. Running CCCC for all of the files in this folder, > 5. Than removing this folder. > > Can anyone enlighten me on this Error I have got and > how to solve it? > > Regards > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com From pavlovevidence at gmail.com Tue Jul 18 22:35:23 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 18 Jul 2006 19:35:23 -0700 Subject: Coding style In-Reply-To: <878xmqs6j2.fsf@gmail.com> References: <1153151794.899753.97810@i42g2000cwa.googlegroups.com> <1153168968.995422.198360@m73g2000cwd.googlegroups.com> <1153175690.052746.241850@s13g2000cwa.googlegroups.com> <44bca710$0$27036$626a54ce@news.free.fr> <44bd65b7$0$18293$636a55ce@news.free.fr> <1153265252.445710.194090@75g2000cwc.googlegroups.com> <44bd817f$0$17267$626a54ce@news.free.fr> <1153273211.925635.8980@i42g2000cwa.googlegroups.com> <878xmqs6j2.fsf@gmail.com> Message-ID: <1153276523.346307.156620@p79g2000cwp.googlegroups.com> Jorge Godoy wrote: > "Carl Banks" writes: > > > Well, I certainly can agree with that, except for the last point. :) I > > certainly wouldn't want to keep that unfortunate behavior around just I > > have something to use as an argument using len to test emptiness. > > On the other hand, having this behavior makes it so simple to deal with some > algorithms because on doesn't need to know if the given object does or does > not support len()... First of all, the unfortunate behavior I was referring to was the fact that iterables that have unknown length are true in a boolean context, even if they happen to be empty. Bruno and I had a disagreement over whether this should also be a wart for lists and such, but I think we agree that it would be better generators and other iterators raised an exception in a boolean context. Getting back to your reply--can you give an example of a useful function that needs to do what you want? (Let's disregard iterators and arrays for now, and focus on older Python types like lists, tuples, strings, integers, floats, None, etc.) Can you give me an example of a useful function that needs to test the truth value of an object, but that can't rely on it having a length? The only example I can think of here is a function that does nothing with an object except pass it to other functions. Almost anything else you do with an object pigeonholes it as a sequence or atomic type: you've already assumed whether it has a length or not. Carl Banks From okorkmaz at havelsan.com.tr Tue Jul 4 07:02:05 2006 From: okorkmaz at havelsan.com.tr (Omer KORKMAZ) Date: Tue, 4 Jul 2006 14:02:05 +0300 Subject: sys.exit call from pythonw.exe gives error Message-ID: I wrote a python GUI with tkInter and installed it on a windows machine with the .pyw extension, so it will be executed from pythonw.exe instead of python.exe, since I didn't want the console window to appear. My application exits with a call to sys.exit. However, when this call is executed under pythonw.exe I get an error popup window with the following messeage: ---- start quote ---- Microsoft Visual C++ Runtime Library Runtime Error! Program: C:\Python24\pythonw.exe This application has requested the Runtime to terminate in an unusual way. Please contact the application support team for more information ---- end quote ---- Did you find a solution for this problem? Best Regards, Omer Korkmaz Ext: 3138 Dikkat: Bu elektronik posta mesaji kisisel ve ozeldir. Eger size gonderilmediyse lutfen gondericiyi bilgilendirip mesaji siliniz.Firmamiza gelen ve giden mesajlar virus taramasindan gecirilmekte, guvenlik nedeni ile kontrol edilerek saklanmaktadir.Mesajdaki gorusler gondericiye ait olup HAVELSAN A.S. resmi gorusu olmak zorunda degildir. Attention: This e-mail message is private and privileged.If you are not the recipient for whom this e-mail message is intended, please notify the sender immediately and delete this e-mail message from your system.All sent and received e-mail messages go through a virus scan in our company, and because of security reasons, they are stored after being controlled.Any opinions presented in this e-mail message are solely those of the author and do not necessarily represent HAVELSAN A.S.'s formal and authorized views. -------------- next part -------------- An HTML attachment was scrubbed... URL: From shibaji.bannerjee at gmail.com Sat Jul 8 12:58:13 2006 From: shibaji.bannerjee at gmail.com (shibaji.bannerjee at gmail.com) Date: 8 Jul 2006 09:58:13 -0700 Subject: wx Browser-objekt for python on Linux In-Reply-To: References: Message-ID: <1152377893.184757.165790@35g2000cwc.googlegroups.com> The wx demos contain an embedded browser (integrates an IE window) example. spooky wrote: > Hey, > > For windows there is a object wx.lib.iewin to integrate a browserwindow > into a python-wx-application. > I need a similar object, that runs under linux. > > Need help!!! > > Thx, > > Spooky From cliff at develix.com Mon Jul 31 16:54:45 2006 From: cliff at develix.com (Cliff Wells) Date: Mon, 31 Jul 2006 13:54:45 -0700 Subject: Static Variables in Python? In-Reply-To: <001101c6b4d6$82db9ef0$0d7d12ac@kearfott.com> References: <001101c6b4d6$82db9ef0$0d7d12ac@kearfott.com> Message-ID: <1154379285.20290.51.camel@devilbox> On Mon, 2006-07-31 at 15:21 -0400, Michael Yanowitz wrote: > Is it possible to have a static variable in Python - > a local variable in a function that retains its value. > > For example, suppose I have: > > def set_bit (bit_index, bit_value): > static bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] > bits [bit_index] = bit_value > > print "\tBit Array:" > int i > while (i < len(bits): > print bits[i], > print '\n' > > > I realize this can be implemented by making bits global, but can > this be done by making it private only internal to set_bit()? I don't > want bits to be reinitialized each time. It must retain the set values > for the next time it is called. BTW, I'm assuming this example was contrived. In real life, I wonder why you'd ever want to use anything besides: bits = [ 0 ] * 16 bits [ 4 ] = 1 print "Bit Array:" print ' '.join ( bits ) Having a "set_bit" function seems redundant when the language syntax directly supports what you are trying to do. Regards, Cliff -- From vatamane at gmail.com Fri Jul 14 12:05:33 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 14 Jul 2006 09:05:33 -0700 Subject: {} for set notation References: <1152107919.947872.202190@j8g2000cwa.googlegroups.com> Message-ID: <1152893133.357692.310670@m73g2000cwd.googlegroups.com> I really like the set notation idea. Now that sets are first class "citizens" along with dicts, lists and tuples I think they should be used when it makes sense to use them A keyset of a dictionary should be viewed as a set not a list because it is a key_set_ after all. Also sets should get back their traditional notation of '{' and '}', which dictionaries have been in 'borrowing' for all this time in Python. When defining a non-empty set it could be unambiguous to share the notation. So : {1,2,3} is set([1,2,3]) while {1:'a', 2:'b', 3:'c'} could still be the a dictionary. Of course then {1, 2, 3:'b'} would be undefined and would raise an exception or alternatively be equivalent to {1:None, 2:None, 3:'b'} - a dictionary. As far as the set and dictionary notation being "confusing" it seems that a common notation is actually a _benefit_, after all sets and dictionaries are not that different! A dictionary is a mapping (surgective explicit function?) from a _set_ of keys to a set (actually a bad or multiset in Python) of values. At the same time a set can also be regarded as a degenerate dictionary as in {1:None, 2:None, 3:None}. A similarity of notation does make sense to me. Of course the empty set is the problem since {} could be interpreted ambiguously as both a set or a dictionary. I think it makes sense to give the '{}' notation to the empty _set_ as this will make more sense as far as common sense goes. If the proposal is to have {x} be the a set([x]) then it only makes sense for {} be a set([]). This will break compatibility with old code and that is why it should be in Python 3000 not in 2.x.x The empty dictionary is probably best represented as {:}, it is actually more clear this way as it shows that there is a key and a value separated by ':' and in this case they are both missing so it is an empty dictionary. Also the frozenset, although not used as often, could still probably get its own notation too. For example: 1. ({1,2,3}) - a symmetry with tuples, which are also immutable. The problem of a one element tuple i.e. (10,) not (10) will also be present here. So just as there is a need to use a comma to make (10,)=tuple([10]) one would have to use a comma to specify that a tuple is needed and not a a frozenset() but at the same time the ({1,2,3}) could then never be reduced to {1,2,3}. In other words: ({1,2,3},) is tuple({1,2,3}) ({1,2,3}) is a frozenset([1,2,3]) and never just {1,2,3}. This notation would make the parser go 'nuts'. I think the next idea might be better: 2. _{1,2,3}_ - the underscores '_' intuitively could mean that the braces are fixed blocks and will not "move" to accomodate addition or removal of elements i.e. the fact that the frozenset is immutable. Or perhaps a more verbose _{_1,2,3_}_ would be better, not sure... 3. {|1,2,3|} or maybe |{1,2,3}| - same aesthetic rationale as above, '|'s look like 'fences' that will not allow the braces to 'move', but this would look to much like Ruby's blocks so 1 and 2 might be better. In general a 'set' are a fundamental data structure. It has always been secondary in traditional programming languages. For simplicity in implementation arrays and lists have been used to mimic a set. Now that Python has a built in set it only makes sense to give it its own notation and maybe Python 3000 is just the right time for it. - Nick Vatamaniuc bearophileHUGS at lycos.com wrote: > >From this interesting blog entry by Lawrence Oluyede: > http://www.oluyede.org/blog/2006/07/05/europython-day-2/ > and the Py3.0 PEPs, I think the people working on Py3.0 are doing a > good job, I am not expert enough (so I don't post this on the Py3.0 > mailing list), but I agree with most of the things they are agreeing > to. Few notes: > > - input() vanishes and raw_input() becomes sys.stdin.readline(). I > think a child that is learning to program with Python can enjoy > something simpler: input() meaning what raw_input() means today. > > > - dict.keys() and items() returns a set view > > This is being discussed here too a lot, I agree that they will just > become equivalent to iterkeys() and iteritems(). > > > - dict.values() a bag (multiset) view > > I think this isn't a good idea, I think bags can be useful but in this > situation they make things too much complex. > > > http://www.python.org/dev/peps/pep-3100/#core-language : > - Set literals and comprehensions: {x} means set([x]); {x, y} means > set([x, y]). {F(x) for x in S if P(x)} means set(F(x) for x in S if > P(x)). NB. {range(x)} means set([range(x)]), NOT set(range(x)). There's > no literal for an empty set; use set() (or {1}&{2} :-). There's no > frozenset literal; they are too rarely needed. > > I like the idea of set literals, but using {1:2} for dicts and {1, 2} > for sets may look a bit confusing. > And using {} for the empty dict is confusing even more, newbies will > use it a lot for empty sets. Maybe the {:} for the empty dict and {} > for the empty set are a bit better. > Maybe a better syntax can be use a different denotator, to distinguis > the two structures better. Some possibilities are nice looking but not > easy to type: > ?1, 2? > Other may be confused with bitwise operators: > |1, 2| > Others are bad looking and not easy to type (some nationalized > keyboards don't have the `): > ?1, 2? > `1, 2` > Some of them are too much long: > <<<1, ,2>>> > Maybe using two nested like this is better (you can't put a dict or set > in a set, so there are no ambiguities): > {{1, 2}} > > I don't have a definitive good solution, but I think that adopting a > bad solution is worse than using set(...). Set literals are cute but > not necessary. Choosing things that increase the probability of bugs > isn't good. > > --------------------- > > In the past I have suggested other possibilities for Py3.0, nothing > really important, but few things can be interesting. > > - cmp() (or comp(), comp4(), etc) returns 4 values (<, ==, >, not > comparable). > - do - while. > - NOT OR AND XOR as bitwise operators syntax. > - Better syntax for octals and hex numbers. > - obj.copy() and obj.deepcopy() methods for all objects. > - Simplification and unification of string formatting (I have seen they > are working on this already). > - Intersection and subtraction among dicts. > > Less important things: > - More human syntax for REs > - Optional auto stripping of newlines during an iteration on a file. > - String split that accepts a sequence of separators too. > - a function in the math library to test for approximate FP equality. > - something in cmath to do a better conversion of polar<->cartesian > complex number conversion > - xpermutations and xcombinations generators in the standard library. > > Bye, > bearophile From cdsmith at twu.net Mon Jul 10 12:35:38 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 10 Jul 2006 10:35:38 -0600 Subject: What is a type error? References: <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> <4gakhiF1m698cU1@individual.net> <8vl3b2tu42if639eaak4i79cbqrqig7tch@4ax.com> <1152516083.019202.215160@p79g2000cwp.googlegroups.com> <1152543751.186771.113230@h48g2000cwc.googlegroups.com> Message-ID: Marshall wrote: > It's never been a strong point. Made worse now that my daughter > is one of those up-at-the-crack-of-dawn types, and not old enough > to understand why it's not nice to jump on mommy and daddy's > bed while they're still asleep. But aren't you actually a time zone > or two east of me? Yes, I confess I'm one time zone to your east, and I was posting later than you. So perhaps it wasn't really past your bedtime. > The fields of an object/struct/what have you are often hidden behind > a method-based interface (sometimes callled "encapsulated") only > because we can't control their values otherwise. I believe there are actually two kinds of encapsulation. The kind of encapsulation that best fits your statement there is the getter/setter sort, which says: "logically, I want an object with some set of fields, but I can't make them fields because I lose control over their values". That part can definitely be replaced, in a suitably powerful language, with static constraints. The other half of encapsulation, though, is of the sort that I mentioned in my post. I am intentionally choosing to encapsulate something because I don't actually know how it should end up being implemented yet, or because it changes often, or something like that. I may encapsulate the implementation of current tax code specifically because I know that tax code changes on a year-to-year basis, and I want to ensure that the rest of my program works no matter how the tax code is modified. There may be huge structural changes in the tax code, and I only want to commit to leaving a minimal interface. In practice, the two purposes are not cleanly separated from each other. Most people, if asked why they write getters and setters, would respond not only that they want to validate against assignments to the field, but also that it helps isolate changes should they change the internal representation of the class. A publicly visible static constraint language that allows the programmer to change the internal representation of a class obviously can't make reference to any field, since it may cease to exist with a change in representation. > However for a function, the "fields" are the in and out parameters. > The specific values in the relation that the function is aren't known > until runtime either, (and then only the subset for which we actually > perform computation.) > > Did that make sense? I didn't understand that last bit. > There are certainly syntactic issues, but I believe these are amenable > to the usual approaches. The runtime/compile time question, and > decidability seem bigger issues to me. Well, the point of static typing is to do what's possible without reaching the point of undecidability. Runtime support for checking the correctness of type ascriptions certainly comes in handy when you run into those limits. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From spacelabstudio at gmail.com Fri Jul 14 11:30:16 2006 From: spacelabstudio at gmail.com (spacelabstudio at gmail.com) Date: 14 Jul 2006 08:30:16 -0700 Subject: Weird platform dependent error: Using pty.fork() Message-ID: <1152891016.642604.290480@s13g2000cwa.googlegroups.com> Hi, I'm observing some weird behavior and have written the following test program to demonstrate. This works under cygwin/WinXP but not Gentoo(kernel 2.6): huh.py ------------------------------------------- import pty,os,sys # Fork ( pid, fd ) = pty.fork() if pid == 0: # Child thread print 'Have a happy day!' print 'Forza Azzurri!' else: # Controlling process # read stdout from child process # and send to stderr stream = os.fdopen( fd ) line = stream.readline() while len( line ) > 0: sys.stderr.write(line) line = stream.readline() stream.close() ------------------------------------------- This program runs perfectly under cygwin on Windows XP using python 2.4.3: ======================================================================== crossi at 6M0D481 ~/proj/plum $ python huh.py Have a happy day! Forza Azzurri! crossi at 6M0D481 ~/proj/plum $ python huh.py 2>/dev/null crossi at 6M0D481 ~/proj/plum $ python Python 2.4.3 (#1, May 18 2006, 07:40:45) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> crossi at 6M0D481 ~/proj/plum $ ======================================================================== But on Gentoo (2.6 kernel) with Python 2.4.3 it dies with an I/O error when it hits the end of the stream: ======================================================================== chris at jupiter ~/proj/plum $ python huh.py Have a happy day! Forza Azzurri! Traceback (most recent call last): File "huh.py", line 19, in ? line = stream.readline() IOError: [Errno 5] Input/output error chris at jupiter ~/proj/plum $ python huh.py 2>/dev/null chris at jupiter ~/proj/plum $ python Python 2.4.3 (#1, Jul 13 2006, 23:02:30) [GCC 3.3.6 (Gentoo 3.3.6, ssp-3.3.6-1.0, pie-8.7.8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ======================================================================== Anybody have any idea what's going on here? Is there a better way to fork and capture the output of the child process? Thanks, Chris From deusfaber at gmail.com Mon Jul 3 18:28:19 2006 From: deusfaber at gmail.com (dfaber) Date: 3 Jul 2006 15:28:19 -0700 Subject: starting and stopping a program from inside a python script Message-ID: <1151965699.491050.137660@75g2000cwc.googlegroups.com> Aloha! I want to terminate a process/program from within a python script. For example, if I have a program say foo.sh that starts running, then I can run it from within a python script using os.popen('foo.sh') which starts a program/process say 'bar' At some point later, I want to kill 'bar'. Currently, I start off the process and then when the python script exits, the process 'bar' is still running and I have to issue ps -ef | grep 'bar' and then kill it. Is there any better way of doing this? From deets at nospam.web.de Thu Jul 20 08:03:43 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 20 Jul 2006 14:03:43 +0200 Subject: Accessors in Python (getters and setters) In-Reply-To: <44bf5f97$0$18895$626a54ce@news.free.fr> References: <44b38b7e$0$14341$626a54ce@news.free.fr> <1152695847.706091.115340@b28g2000cwb.googlegroups.com> <44b4d9d6$0$14332$626a54ce@news.free.fr> <1152780657.174836.263530@h48g2000cwc.googlegroups.com> <44b61d94$0$23082$626a54ce@news.free.fr> <1152789577.742527.201570@75g2000cwc.googlegroups.com> <44b641e5$0$18110$636a55ce@news.free.fr> <1152801514.683329.252080@75g2000cwc.googlegroups.com> <44b66c67$0$31799$626a54ce@news.free.fr> <1152957314.252038.29290@m79g2000cwm.googlegroups.com> <1152975860.267475.166030@i42g2000cwa.googlegroups.com> <44bb8a7c$0$21801$626a54ce@news.free.fr> <1153213630.721413.95290@i42g2000cwa.googlegroups.com> <44bcea80$0$23108$626a54ce@news.free.fr> <1153244682.923384.71370@75g2000cwc.googlegroups.com> <44be63e0$0$14345$626a54ce@news.free.fr> <1153371049.561672.233550@h48g2000cwc.googlegroups.com> <44bf5f97$0$18895$626a54ce@news.free.fr> Message-ID: <4i99ovF2p7i7U1@uni-berlin.de> > Lol. I actually did *un*learn the hard way. > > Mystilleef, I've started programing 17 years ago, and have done it > professionnaly for almost 10 years now. I do not pretend to be a good > programmer, but please believe that I do know my job. I've read the Book > too, I've tried applying it blindly, then I used my brain. Once you > understand the real reasons behind a "rule", you also understand when > and how to apply or not apply it. To second that: """ A Foolish Consistency is the Hobgoblin of Little Minds """ http://www.python.org/dev/peps/pep-0008/ Diez From apardon at forel.vub.ac.be Sun Jul 9 11:37:08 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 Jul 2006 15:37:08 GMT Subject: Nested scopes, and augmented assignment References: <1152014838.883327.237990@j8g2000cwa.googlegroups.com> <4gv5nqF1os71jU1@uni-berlin.de> <44abbc26$0$14843$626a54ce@news.free.fr> Message-ID: On 2006-07-09, Piet van Oostrum wrote: >>>>>> Antoon Pardon (AP) wrote: > >>AP> It is conceptually different. In the line 'a = b' you don't need to >>AP> search for the scope of a. You know it is the current scope, if you > > Except when it has been declared global. Yes, I ignored that possibilitym because as far as I understood we were discussing variables in intermediate scopes. >>AP> want to know the scope of b on the other hand, you need to search >>AP> for statement where it is assigned to. > >>AP> Sure you can set things up in the interpreter so that the same search >>AP> routine is used, but that is IMO an implementation detail. > >>>> Well, it is not. But I can understand the >>>> confusion. Namely, `a = b' introduces a binding for `a' in the local scope, >>>> unless `a' was declared global. So the search will find `a' in the local >>>> scope and it stops there. On the other hand `a.b = c' will not introduce a >>>> binding for `a'. So the search for `a' may stop in the local space (if >>>> there was another binding for `a' in the local scope) or it may need to >>>> continue to outer scopes. The difference, however is not the >>>> complicatedness of the lefthand side but whether the local scope contains a >>>> binding for the variable. > >>AP> The complicatedness of the lefthand side, decided on whether the >>AP> variable was introduced in the local scope or not during startup >>AP> time. So that complicatedness decided whether the search was >>AP> to stop at the local level or not. > No, it doesn't. There could be another binding in the same scope. Indeed there could be. But I hoped you would understand I was just keeping things simple, with a simple example. > The > complicatedness of this particular assignment doesn't decide anything about > how to search for 'a', but rather the presence or absence of a binding > anywhere in the scope. I'll word it differently. If the compiler encounters a line like 'a = b' then you know from that line alone that the search space for a will be limited to the local scope. If you encounter a line like 'a.c = b' then you have no such knowledge. A line like 'a = b' will cause the compilor that at call time variable a will be added to the local scope, a line like 'a.c = b' will not have that effect. So a line like 'a = b' has an influence on what the search space is for variable a, while a line like 'a.c = b' doesn't. So the complicatedness on the leftside decides whether or not the compilor will take certain actions with regards to the search space of the variable on the left side. And yes I'm again ignoring global. -- Antoon Pardon From pupeno at pupeno.com Thu Jul 27 04:46:40 2006 From: pupeno at pupeno.com (Pupeno) Date: Thu, 27 Jul 2006 08:46:40 +0000 Subject: Worarrounding hardcoded Option class in optparse in Python 2.3 References: <44c7e381$0$22015$9b4e6d93@newsread2.arcor-online.net> Message-ID: <44c87d62$0$24899$9b4e6d93@newsread4.arcor-online.net> For the record, the copy and paste fix seems to have worked, so far. Pupeno wrote: > Hello, > I am doing some extreme use of optparse, that is, extending it as > explained on > http://docs.python.org/lib/optparse-other-reasons-to-extend-optparse.html > I have subclassed OptionParser and Option. MyOptionParser uses MyOption as > option_class and in Python 2.4 it works. But I have to target Python 2.3. > In Python 2.3 the help and version options seem to be created before even > a parser is created and they are created using a hardcoded call to Option. > So, they are not using MyOption. I am creating MyOption specifically for > the help and version Option so I need the to be MyOption. > I check out the documentation of this module for Python 2.3 and it > recommends the same procedure: > http://www.python.org/doc/2.3/lib/optparse-extending-other-reasons.html > Is this a bug in Python 2.3 that was solved in 2.4 and nobody cared to > backport ? > At any rate, what are my options (no pun intended) ? > I could copy and paste the fix[1] from Python 2.4 into MyOptionParser; I > checked it carefull and it seems it would work, but I am not sure, does > anybody know ? > Should I override the hardcoded module variables of optparse in 2.3 ? > (that seems like a bad, bad idea). > I am open to suggestions. > Thanks. -- Pupeno (http://pupeno.com) From onurb at xiludom.gro Tue Jul 18 04:38:00 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 18 Jul 2006 10:38:00 +0200 Subject: function v. method In-Reply-To: <1153199618.435747.162950@i42g2000cwa.googlegroups.com> References: <1153199618.435747.162950@i42g2000cwa.googlegroups.com> Message-ID: <44bc9de9$0$24602$626a54ce@news.free.fr> danielx wrote: > At first I was going to post the following: > > > (snip) > > > > but then I tried this: > > >>>>res = Foo.__dict__['func'] >>>>res is dan > > True > > And it all started to make sense. The surprising thing turned out to be > not so surprising: When the expression Foo.func gets evaluated, we get > a method which is just a wrapper around dan. Therefore, f is not dan! > This is still a little bit of magic, FWIW, the function class implements the descriptor protocol... Here's the "magic". > which gets me thinking again about > the stuff I self-censored. Since the dot syntax does something special > and unexpected in my case, "unexpected" ? Did you ever wondered how the instance or class was passed as first arg when doing method calls ? > why not use some more dot-magic to implement > privates? What for ? What makes you think we need language-inforced access restriction ? (snip) > BTW, I am aware of Python's name mangling feature. Name mangling is mainly here to protect from accidental overridding. The convention for implementation attributes is single-leading-underscore. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sjmachin at lexicon.net Sat Jul 1 17:30:48 2006 From: sjmachin at lexicon.net (John Machin) Date: Sun, 02 Jul 2006 07:30:48 +1000 Subject: Dictionary .keys() and .values() should return a set [with Python 3000 in mind] In-Reply-To: <1151784117.119515.310100@75g2000cwc.googlegroups.com> References: <1151784117.119515.310100@75g2000cwc.googlegroups.com> Message-ID: <44a6e985$1@news.eftel.com> On 2/07/2006 6:01 AM, vatamane at gmail.com wrote: > This has been bothering me for a while. [snip] Summary of OP's post: d.keys() and d.values() should return sets in Python 3.0. Observations: (1) My code [some of which dates back to Python 1.5.1] uses about 12 x d.items() and 11 x d.keys() for each 1 x d.values() (2) Most cases of d.X() don't need/want the untrammelled list and could be replaced by d.iterX(). Example: max_frequency = max(tally.values()) Opinion: d.X() could be deprecated, but I'd rather see a consciousness-raising for the d.iterX() methods, and for the construct for key in d: Cheers, John From crankycoder at gmail.com Fri Jul 28 14:55:46 2006 From: crankycoder at gmail.com (Victor Ng) Date: Fri, 28 Jul 2006 14:55:46 -0400 Subject: build problems with Python 2.4.3 under Solaris 10 Message-ID: How do I enable readline support for Python under Solaris 10? I've got CSWreadline installed in /opt/csw from blastwave, but I'm not having any luck getting the readline.so module compiled. I'm using: CPPFLAGS="-I/opt/csw/include" LDFLAGS="-L/opt/csw/lib" ./configure --prefix=/opt/python/2.4.3 --enable-shared --disable-tkinter --enable-readline --libdir=/opt/csw/lib --includedir=/opt/csw/include --enable-rpath --enable-curses >From the SciPy page, I've modified the pyconfig.h file after configure is run so that matplotlib will compile: http://www.scipy.org/Cookbook/Matplotlib/CompilingMatPlotLibOnSolaris10 2 after extracting it and running ./configure, edit the generated pyconfig.h as follows: - i) if _XOPEN_SOURCE is defined to be 600 (i.e., if the line "#define _XOPEN_SOURCE 600" appears in the file), redefine it to 500 ii) if _XOPEN_SOURCE_EXTENDED is defined at all (i.e. if the line "#define _XOPEN_SOURCE_EXTENDED 1" appears in the file), comment out its definition But other than that - I haven't done anything special. What am I doing wrong? vic -------------- next part -------------- An HTML attachment was scrubbed... URL: From moqtar at gmail.com Thu Jul 13 02:34:20 2006 From: moqtar at gmail.com (Kirt) Date: 12 Jul 2006 23:34:20 -0700 Subject: Problem with "&" charater in xml. In-Reply-To: <44b5e4b8$0$6693$9b4e6d93@newsread4.arcor-online.net> References: <1152769937.699100.223620@s13g2000cwa.googlegroups.com> <44b5e4b8$0$6693$9b4e6d93@newsread4.arcor-online.net> Message-ID: <1152772460.221208.205490@h48g2000cwc.googlegroups.com> How do i append characters to a string? actually my entire handler code is class oldHandler(ContentHandler): def __init__(self): self.fn = 0 self.dn = 0 self.i=[] self.x="" self.y="" self.z="" self.t=0 self.xx='' def startElement(self, name, attrs): if name=='dirname': self.dn=1 if name=='name': self.fn=1 if name=='time': self.t=1 def characters(self,str): if self.dn: self.x=str if self.fn: self.y=str if self.t: self.z=str ss= self.x+'/'+self.y+','+self.z+ '\r \n' self.i.append(ss) def endElement(self, name): if name == 'dirname': self.dn=0 if name=='name': self.fn=0 if name=='time': self.t=0 def endDocument(self): f=open('old.txt', 'w') self.i.sort f.writelines(self.i) f.close so my old.txt now looks like this y+def.txt,200607130417 C:\Documents and Settings\Administrator\Desktop\1\hii wx\abc.txt,200607130415 But i wont the output as C:\Documents and Settings\Administrator\Desktop\1\bye w&y\def.txt,200607130417 C:\Documents and Settings\Administrator\Desktop\1\hii wx\abc.txt,200607130415 Stefan Behnel wrote: > Kirt wrote: > > i have walked a directory and have written the foll xml document. > > one of the folder had "&" character so i replaced it by "&" > > #------------------test1.xml > > > > C:\Documents and Settings\Administrator\Desktop\1\bye > > w&y > > > > def.txt > > > > > > > > > > C:\Documents and Settings\Administrator\Desktop\1\hii > > wx > > > > abc.txt > > > > > > > > > now in my python code i want to parse this doc and print the directory > > name. > > ###----------handler------------filename---handler.py > > from xml.sax.handler import ContentHandler > > class oldHandler(ContentHandler): > > def __init__(self): > > self.dn = 0 > > def startElement(self, name, attrs): > > if name=='dirname': > > self.dn=1 > > > > def characters(self,str): > > if self.dn: > > print str > > > The problem is here. "print" adds a newline. Don't use print, just append the > characters (to a string or list) until the endElement callback is called. > > > > def endElement(self, name): > > if name == 'dirname': > > self.dn=0 > > > > > > #--------------------------------------------------------------------- > > #main code--- fname----art.py > > import sys > > from xml.sax import make_parser > > from handlers import oldHandler > > > > ch = oldHandler() > > saxparser = make_parser() > > > > saxparser.setContentHandler(ch) > > saxparser.parse(sys.argv[1]) > > #----------------------------------------------------------------------------- > > i run the code as: $python art.py test1.xml > > > > i am getting output as: > > > > C:\Documents and Settings\Administrator\Desktop\1\bye w > > & > > y > > C:\Documents and Settings\Administrator\Desktop\1\hii wx > > > > where as i need an output which should look like this. > > C:\Documents and Settings\Administrator\Desktop\1\bye w&y > > > > C:\Documents and Settings\Administrator\Desktop\1\hii wx > > > > Can someone tell me the solution for this. > > From timothy at open-networks.net Fri Jul 28 23:59:02 2006 From: timothy at open-networks.net (Timothy Smith) Date: Sat, 29 Jul 2006 13:59:02 +1000 Subject: sending bytes to parallel port In-Reply-To: <12clhmj6af2kh07@corp.supernews.com> References: <12clhmj6af2kh07@corp.supernews.com> Message-ID: <44CADD06.4040908@open-networks.net> Grant Edwards wrote: > On 2006-07-28, Timothy Smith wrote: > > >> i've been trying to send an 8 byte string to my parallel port >> under freebsd. the purpose is it to control a relay board. the >> board simply responds to the output byte coming from the port. >> eg. 00000001 will set pin 1 high and flick the relay open. >> todate i've attempted this with merely open() on /dev/ppi0 and >> numpy for the byte array, but i just can't seem to get it >> working. i know the parallel port works and i know the relay >> board works (tested it with it's own windows ultility) so it's >> just my crappy programming keeping me from success. >> > > I'm guessing there's an implied request for help there > somewhere. This would be a good start: > > http://www.google.com/search?q=python+parallel+port > > I'd particularly recommend taking a look at the pyparallel > module found here: > > http://pyserial.sourceforge.net/ > > I've not used pyparallel, but based on my experience with > pyserial and some of Chris Liechti's other work, I'd bet > dollars to doughnuts it's your best option. > > yes, i did try pyparallel however it will not install on freebsd, setup.py errors. and yes i've done quite a bit of googling, i never expected it to be this difficult. i've done work with serial ports before. never parallel but. From bignose+hates-spam at benfinney.id.au Sun Jul 16 09:21:03 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 16 Jul 2006 23:21:03 +1000 Subject: Commercial Programming References: <7xd5c5iyrb.fsf@ruckus.brouhaha.com> <4Bpug.49976$B91.32251@edtnps82> Message-ID: <878xmt7kjk.fsf@benfinney.id.au> "Boomshiki" writes: > I am aware that someone can recreate what we have done, but for them > to cut, paste, sell is kind of a rip off. Unless you factor that into your business model, and create compelling value that doesn't depend on the secrecy of something you place under the customer's control. -- \ "Try to learn something about everything and everything about | `\ something." -- T.H. Huxley | _o__) | Ben Finney From ldo at geek-central.gen.new_zealand Thu Jul 20 03:42:34 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 20 Jul 2006 19:42:34 +1200 Subject: mysqldb problem References: <1153317137.705813.227380@p79g2000cwp.googlegroups.com> Message-ID: In message <1153317137.705813.227380 at p79g2000cwp.googlegroups.com>, liupei wrote: > when I set mysql some fields collate utf8_bin, and then fetch these > fields is array.array,not the string I expected Can you post some example code? From saad82 at gmail.com Sun Jul 30 22:43:15 2006 From: saad82 at gmail.com (saad82 at gmail.com) Date: 30 Jul 2006 19:43:15 -0700 Subject: replacing single line of text In-Reply-To: <1154134941.169611.297490@i3g2000cwc.googlegroups.com> References: <1154126809.954642.193860@i3g2000cwc.googlegroups.com> <1154134941.169611.297490@i3g2000cwc.googlegroups.com> Message-ID: <1154313795.889842.85740@i42g2000cwa.googlegroups.com> Simon & Tim, very valuable responses. Thank you much! Simon Forman wrote: > saad82 at gmail.com wrote: > > I want to be able to replace a single line in a large text file > > (several hundred MB). Using the cookbook's method (below) works but I > > think the replace fxn chokes on such a large chunk of text. For now, I > > simply want to replace the 1st line (CSV header) in the file but I'd > > also like to know a more general solution for any line in the file. > > There's got a be quick and dirty (and cheap) way to do this... any > > help? > > > > Cookbook's method: > > output_file.write(input_file.read().replace(stext, rtext)) > > > > Thanks, > > Pythonner > > The read() method of a file will "read all data until EOF is reached" > if you don't pass it a size argument. If your file is "several hundred > MB" and your RAM is not, you may have some trouble with this. > > I don't know how well the replace() method works on tenths-of-a-GB > strings. > > The file object supports line-by-line reads through both the readline() > and readlines() methods, but be aware that the readlines() method will > also try to read ALL the data into memory at once unless you pass it a > size argument. > > You can also iterate through the lines in an open file object like so: > > for line in input_file: > # Do something with the line here. > > so, if you know that you want to replace a whole actual line, you could > do this like so: > > for line in input_file: > if line == stext: > output_file.write(rtext) > else: > output_file.write(line) > > > Check out the docs on the file object for more info: > http://docs.python.org/lib/bltin-file-objects.html > > > HTH, > ~Simon From iainking at gmail.com Wed Jul 5 04:10:59 2006 From: iainking at gmail.com (Iain King) Date: 5 Jul 2006 01:10:59 -0700 Subject: List Manipulation In-Reply-To: <1152025419.990647.220160@p79g2000cwp.googlegroups.com> References: <1152021715.243605.58500@75g2000cwc.googlegroups.com> <1152022647.498673.149620@b68g2000cwa.googlegroups.com> <1152024428.818882.284070@75g2000cwc.googlegroups.com> <1152025419.990647.220160@p79g2000cwp.googlegroups.com> Message-ID: <1152087059.154779.255730@v61g2000cwv.googlegroups.com> Mike Kent wrote: > Roman wrote: > > Thanks for your help > > > > My intention is to create matrix based on parsed csv file. So, I would > > like to have a list of columns (which are also lists). > > > > I have made the following changes and it still doesn't work. > > > > > > cnt = 0 > > p=[[], [], [], [], [], [], [], [], [], [], []] > > reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel", > > quotechar="'", delimiter='\t') > > for line in reader: > > if cnt > 6: > > break > > j = 0 > > for col in line: > > p[j].append(col) > > j=j+1 > > cnt = cnt + 1 > > > > print p > > p[j] does not give you a reference to an element inside p. It gives > you a new sublist containing one element from p. You then append a > column to that sublist. Then, since you do nothing more with that > sublist, YOU THROW IT AWAY. > > Try doing: > > p[j] = p[j].append(col) > No, this doesn't work. append is an in-place operation, and you'll end up setting p[j] to it's return, which is None. Iain From diffuser78 at gmail.com Thu Jul 27 14:15:51 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 27 Jul 2006 11:15:51 -0700 Subject: import question on wx ? In-Reply-To: References: <1154014411.758125.289350@i3g2000cwc.googlegroups.com> Message-ID: <1154024151.218887.231970@m79g2000cwm.googlegroups.com> That right..on my console it shows python 2.4.2 and on SPE it shows 2.4.3. The wxPython is working fine in SPE i.e with Python 2.4.3. How can I make sure that when I type python on console I get the 2.4.3 ? Every help is greatly appreciated. Thanks John Salerno wrote: > diffuser78 at gmail.com wrote: > > I have installed wx and everything looks fine. I have written a small > > app that uses wx. > > > > When I run my program from the console like > > ubuntu $ python PROGRAM_NAME.py > > > > it gives error > > Traceback (most recent call last): > > File "Project.py", line 6, in ? > > import wx > > ImportError: No module named wx > > > > > > But if I run the program from SPE (Stani's Python Editor) it just runs > > fine. > > It could be that the Python version you are using to launch the app from > the console is the preinstalled version on your system and therefore > wxPython wasn't installed into that version. Do you have multiple > versions of Python installed? Probably SPE is using the other version > which *does* have wxPython in it. From josef.cihal at siemens.com Mon Jul 3 03:53:00 2006 From: josef.cihal at siemens.com (Cihal Josef) Date: Mon, 3 Jul 2006 09:53:00 +0200 Subject: connect not possible to Oracle Datenbank as sysdba? Message-ID: <94CEBD2AC72A3D478BC8381A196FD7CCA008CD@vie012.at.sat-automation.com> Hi, how can I connect to oracle database as SYSDBA as usually: "sqlplus anc/psw as sysdba" It is a parsing problem? (blanks,etc.?) or it is not implmented in DCOracle2? >DCOracle.Connect('user/psw as sysdba') -> NOK normal (without sysdba clause) -> DCOracle.Connect('user/psw') -> OK thanks for every idea Josef -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan.behnel-n05pAM at web.de Thu Jul 6 13:49:34 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 06 Jul 2006 19:49:34 +0200 Subject: lxml and SimpleXMLWriter In-Reply-To: <1151764246.070975.39580@v61g2000cwv.googlegroups.com> References: <1151764246.070975.39580@v61g2000cwv.googlegroups.com> Message-ID: <44ad4d34$0$26265$9b4e6d93@newsread2.arcor-online.net> Srijit Kumar Bhadra wrote: > I am new to lxml. I am interested to know the equivalent code using > lxml (http://cheeseshop.python.org/pypi/lxml/1.1alpha). The code is > taken from http://effbot.org/zone/xml-writer.htm > > from elementtree.SimpleXMLWriter import XMLWriter > import sys > > w = XMLWriter(sys.stdout) > > html = w.start("html") [snip] Note that the SimpleXMLWriter is in no way related to the ElementTree implementation. Feel free to copy the module from the elementtree package and use it with lxml. Stefan From apardon at forel.vub.ac.be Thu Jul 6 03:13:05 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 Jul 2006 07:13:05 GMT Subject: Nested scopes, and augmented assignment References: <1152014838.883327.237990@j8g2000cwa.googlegroups.com> <4gv5nqF1os71jU1@uni-berlin.de> <44abbc26$0$14843$626a54ce@news.free.fr> Message-ID: On 2006-07-05, Fredrik Lundh wrote: > Antoon Pardon wrote: > >> Python could have chosen an approach with a "nested" keyword > > sure, and Python could also have been invented by aliens, powered by > space potatoes, and been illegal to inhale in Belgium. At one time one could have reacted the same when people suggested python could use a ternary operator. In the mean time a ternary operator is in the pipeline. If you don't want to discuss how python could be different with me, that is fine, but I do no harm discussing such things with others. > have any of your "my mental model of how Python works is more important > than how it actually works" ever had a point ? Be free to correct me. But just suggesting that I'm wrong doesn't help me in changing my mental model. -- Antoon Pardon From vatamane at gmail.com Fri Jul 28 12:36:57 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 28 Jul 2006 09:36:57 -0700 Subject: Newbie..Needs Help References: <44ca0e2b$0$1207$afc38c87@news.optusnet.com.au> <44ca292c$0$1206$afc38c87@news.optusnet.com.au> Message-ID: <1154104617.344681.227190@m79g2000cwm.googlegroups.com> Graham, I won't write the program for you since I have my own program to work on but here is an idea how to do it. 1) Need to have a function to download the page -- use the urllib module. Like this: import urllib page=urllib.urlopen(URL_GOES_HERE).read() 2) Go to the page with your browser and view the source of the html. You will need to find specific html patterns that you can use to identify the boundaries between each race first. A good one would be the actual title 'Race 1 results:', then you have 'Race 2 results:' and so on until 'Race 8 results:'. From this you need to derive a regular expression in Python (here is documenation http://docs.python.org/lib/module-re.html) to express all those boundaries as one pattern it is: 'Race [0-9]+ results:'. In other words the word 'Race' then space then a digit repeated one or more times then another space and 'results:'. So you can do: races_pattern=re.comple(r'Race [0-9]+ results:') # <- this is your pattern chunks=races_pattern.split(page) #<- split the page into chunks based on the pattern you will have 9 chunks if you have 8 races. The first one will be all the stuff before the title (i.e. the start of the page), throw it away: chunks=chunks[1:] 3) Now go back to the html source and look inside each race at the table with the results, find a pattern for a good boundary between table rows. Again use the regular expressions like before to split each table away from other junk, then each table into rows (use ) 4) Look again at the source, and split each row into data cells (use ). 5) Then for each of the split cell chunks remove the html tag data with chunk=re.sub('<.*?>', '', chunk) 6) Now all you should have is pure data stored in strings in each of the data cell chunks in each of the table row in each of the table. 7) Then save to text file and import into your database. Anyway that's the general idea, there are other ways to do it, but that's my approach. I wrote a couple of screen scrapping applications like this before in Python and I used this method and it worked well enough. Good luck, Nick V. Graham Feeley wrote: > Thanks Nick for the reply > Of course my first post was a general posting to see if someone would be > able to help > here is the website which holds the data I require > http://www.aapracingandsports.com.au/racing/raceresultsonly.asp?storydate=27/07/2006&meetings=bdgo > > The fields required are as follows > NSW Tab > # Win Place > 2 $4.60 $2.40 > 5 $2.70 > 1 $1.30 > Quin $23.00 > Tri $120.70 > Field names are > Date ( not important ) > Track................= Bendigo > RaceNo............on web page > Res1st...............2 > Res2nd..............5 > Res3rd..............1 > Div1..................$4.60 > DivPlc...............$2.40 > Div2..................$2.70 > Div3..................$1.30 > DivQuin.............$23.00 > DivTrif...............$120.70 > As you can see there are a total of 6 meetings involved and I would need to > put in this parameter ( =bdgo) or (=gosf) these are the meeting tracks > > Hope this more enlightening > Regards > graham > > "Graham Feeley" wrote in message > news:44ca0e2b$0$1207$afc38c87 at news.optusnet.com.au... > > Hi this is a plea for some help. > > I am enjoying a script that was written for me and its purpose is to > > collect data from a web site and puts it into a access database table. > > It works fine, however it is a sports info table but now I need to collect > > the results of those races. > > > > I simply can't keep up putting the results in manually. > > I dont care if it is a access table or a text file ( whichever is easiest) > > there are only 12 fields to extract > > The person who wrote the script is not available as he is engrossed in > > another project which is talking all his time. > > I hope someone has a little time on his hands willing to help me > > Regards > > Graham > > > > > > From g.brandl-nospam at gmx.net Tue Jul 11 16:06:36 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Tue, 11 Jul 2006 22:06:36 +0200 Subject: Abuse of the object-nature of functions? In-Reply-To: References: <1152625508.056628.188690@p79g2000cwp.googlegroups.com> <44b3e7a3$0$23886$626a54ce@news.free.fr> Message-ID: Carl J. Van Arsdall wrote: > Hrmms, well, here's an interesting situation. So say we wanna catch > most exceptions but we don't necessarily know what they are going to > be. For example, I have a framework that executes modules (python > functions), the framework wraps each function execution in a try/except > block in order to compensate for what *might* happen. Upon coding the > framework I really have no idea what types of problems these modules > might have but I want to catch these errors so that I can clean up and > exit gracefully, not only that but I want to dump the exception to log > files so that we can attempt to fix it. So, I have the option of > catching all standard exceptions and not list the ones I know I don't > want to catch. But what about user defined exceptions? Do I then have > to enforce policies on the system stating what types of exceptions can > be raised? > > Is there a way in python to say, "hey, catch everything but these two"? Yes: try: ...some code... except (AttributeError, TypeError): raise except Exception, e: handle all other exceptions is the most Pythonic solution. Georg From python.list at tim.thechases.com Sun Jul 23 11:57:56 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 23 Jul 2006 10:57:56 -0500 Subject: building lists of dictionaries In-Reply-To: References: Message-ID: <44C39C84.3090601@tim.thechases.com> > parinfo = [{'value':0., 'fixed':0, 'limited':[0,0], 'limits':[0.,0.]}]*6 > parinfo[0]['fixed'] = 1 > parinfo[4]['limited'][0] = 1 > parinfo[4]['limits'][0] = 50. > > The first line builds a list of six dictionaries with > initialised keys. I expected that the last three lines > would only affect the corresponding keys of the > corresponding dictionnary and that I would end up with a > fully initialised list where only the 'fixed' key of the > first dict would be 1, and the first values of limited and > limits for dict number 4 would be 1 and 50. > respectively.... > > This is not so! I end up with all dictionaries being > identical and having their 'fixed' key set to 1, and > limited[0]==1 and limits[0]==50. > I do not understand this behaviour... The *6 creates multiple references to the same dictionary. Thus, when you update the dictionary through one reference/name (parinfo[0]), the things that the other entries (parinfo[1:5]) reference that changed dictionary. You're likely looking for something like parinfo = [{'value':0., 'fixed':0, 'limited':[0,0], 'limits':[0.,0.]}] for i in xrange(1,6): parinfo.append(parinfo[0].copy()) or something like parinfo = [{'value':0., 'fixed':0, 'limited':[0,0], 'limits':[0.,0.]}.copy() for i in xrange(0,6)] However, this will still reference internal lists that have been referenced multiple times, such that >>> parinfo[5]['limited'] [0, 0] >>> parinfo[4]['limited'][0] = 2 >>> parinfo[5]['limited'] [2, 0] Thus, you'd also want to change it to be something like parinfo = [ {'value':0., 'fixed':0, 'limited':[0, 0][:], 'limits':[0., 0.][:] }.copy() for i in xrange(0, 6)] where the slice operator is used to build a copy of the list for each element as well (rather than keeping a reference to the same list for each dictionary). Hopefully this makes some sense, and helps get you on your way. -tkc From Dennis.Benzinger at gmx.net Sat Jul 29 10:50:24 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Sat, 29 Jul 2006 16:50:24 +0200 Subject: Client/Server Question In-Reply-To: <1154119933.312433.264210@p79g2000cwp.googlegroups.com> References: <1154116446.226996.226410@s13g2000cwa.googlegroups.com> <44ca76d0$1@news.uni-ulm.de> <1154119933.312433.264210@p79g2000cwp.googlegroups.com> Message-ID: <44cb75ad$1@news.uni-ulm.de> diffuser78 at gmail.com wrote: > Is os.system() going to be deprecated in future ?.....I read somewhere. > [...] Sometime in the future it will. But that won't happen soon. Read the second paragraph of "Backwards Compatibility" in the subprocess PEP . Dennis From bayerj at in.tum.de Tue Jul 18 02:19:05 2006 From: bayerj at in.tum.de (bayerj) Date: 17 Jul 2006 23:19:05 -0700 Subject: function v. method In-Reply-To: <1153199618.435747.162950@i42g2000cwa.googlegroups.com> References: <1153199618.435747.162950@i42g2000cwa.googlegroups.com> Message-ID: <1153203544.989071.224450@75g2000cwc.googlegroups.com> I guess the python devs are not interested in implementing something that would require new syntax and does not give something entirely new to the language. The good thing about python is, that the devs are only implementing ideas that are very cool. There are a lot of cool (!= very cool) ideas in rejected peps - but they were never implemented for good reasons. If you *really* need privates, just use the naming convention. From girodt at gmail.com Wed Jul 19 10:05:58 2006 From: girodt at gmail.com (TG) Date: 19 Jul 2006 07:05:58 -0700 Subject: access to submodules In-Reply-To: <1153317444.615450.139700@h48g2000cwc.googlegroups.com> References: <1153315605.086825.229830@i3g2000cwc.googlegroups.com> <1153315931.613796.117060@p79g2000cwp.googlegroups.com> <1153317444.615450.139700@h48g2000cwc.googlegroups.com> Message-ID: <1153317958.271921.306370@m73g2000cwd.googlegroups.com> I know this is a bad habit ... I was just doing it to show what is disturbing me. Obviously the "star" syntax finds the submodules because they are loaded, but when I properly load the module alone with "import tom", the "dot" syntax does not find "tom.core". BartlebyScrivener wrote: > >> > from tom import * > > You CAN do this, but it's a bad habit. > > Try: > > >>import tom > > Then call by tom.function() > > rd From LittlePython at lost.com Sat Jul 1 15:21:27 2006 From: LittlePython at lost.com (LittlePython) Date: Sat, 01 Jul 2006 19:21:27 GMT Subject: Threading HowTo's in Windows platforms References: <44a6b763$1@nntp0.pdx.net> Message-ID: Well, I guess you have sold me on this. I will wait till I have grown up to be a big and wise python (who is still employed) and all my growing (scripting) scares have healed properly or maybe even forgotten by my employers. Thx "Jezzz ... What could possible go wrong!" Signed, Mr. DoRight "Scott David Daniels" wrote in message news:44a6b763$1 at nntp0.pdx.net... > Jean-Paul Calderone wrote: > > On Sat, 01 Jul 2006 16:36:02 GMT, LittlePython > > wrote: > >> I am looking for some good beginner how-to links and maybe some simple > >> example scripts that perform threading on windows platforms. Hopefully > >> authors who don't mind doing "a little spoon feeding" would be great > >> as I am a "baby python" who is very green with threading.... > > > > Threaded programming is extremely difficult. Most good newbie > > introductions to it consist of warnings not to use it. > > Just to expand on this reply -- even experts avoid threading unless > necessary. The real reason that everyone hates threading is that > wrong programs can run correctly, and errors cannot be reproduced. > Apparently, threaded programs have a "demo detector" that makes them > go wrong in the presence of anything more than a single vice president > (or major customer). > > So, the standard Python advice is to have each thread completely > independent (sharing no data), and communicating only with instances > of queue.Queue. That keeps the "demo detector" in check, because > you then have individually predictable (and hopefully testable) > parts with a logable communication pattern. You still may have > trouble (to which the best reply is, "See, we told you so."). > > --Scott David Daniels > scott.daniels at acm.org From rogue_pedro at yahoo.com Thu Jul 27 14:03:02 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 27 Jul 2006 11:03:02 -0700 Subject: iter(callable, sentinel) In-Reply-To: <44c8fc15$0$30316$fa0fcedb@news.zen.co.uk> References: <44c8fc15$0$30316$fa0fcedb@news.zen.co.uk> Message-ID: <1154023382.783119.205350@s13g2000cwa.googlegroups.com> Will McGugan wrote: > Hi, > > I've been using Python for years, but I recently encountered something > in the docs I wasnt familar with. That is, using two arguements for > iter(). Could someone elaborate on the docs and maybe show a typical use > case for it? > > > Thanks, > > Will McGugan > > -- > work: http://www.kelpiesoft.com > blog: http://www.willmcgugan.com D'oh! You said *elaborate*... Sorry. Fredrik Lundh gives a great example of it's use in this thread: http://groups.google.ca/group/comp.lang.python/browse_frm/thread/b3ab8141c492bb21/e3f71597917afaa3 Peace, ~Simon From http Mon Jul 17 03:57:00 2006 From: http (Paul Rubin) Date: 17 Jul 2006 00:57:00 -0700 Subject: General Hash Functions In Python References: <1153116124.032619.146410@s13g2000cwa.googlegroups.com> <7xirlw21by.fsf@ruckus.brouhaha.com> <1153122734.328499.289330@m79g2000cwm.googlegroups.com> Message-ID: <7xirlwvf3n.fsf@ruckus.brouhaha.com> "Arash Partow" writes: > For different data types different hash functions work > better/worse aka fewer or more collisions. But you give no indication of which of those hashes works best for what kind of data. How is the user supposed to figure out which one to choose? From paul at boddie.org.uk Thu Jul 27 07:26:42 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 27 Jul 2006 04:26:42 -0700 Subject: MySql References: <1153982385.121336.41500@i3g2000cwc.googlegroups.com> <1153986153.813580.291840@b28g2000cwb.googlegroups.com> <1153986732.011325.80000@i3g2000cwc.googlegroups.com> <1153987921.656101.257560@s13g2000cwa.googlegroups.com> <4irj3dF56enmU1@news.dfncis.de> <1153997300.286168.186800@m73g2000cwd.googlegroups.com> Message-ID: <1153999602.669156.89690@m73g2000cwd.googlegroups.com> John Machin wrote: > Sibylle Koczian wrote: > > John Machin schrieb: > > > > > > base.commit() [...] > > That's not really fair, because transactions were added to MySQL only a > > short time ago (at least to the default table type). There simply hasn't > > yet been time for every experienced MySQL user to get hit by the need to > > commit things. This is mentioned in the MySQLdb FAQ: http://sourceforge.net/docman/display_doc.php?docid=32070&group_id=22307 The default behaviour has been changed to match the DB-API standard, which probably matches the normal behaviour on most mainstream relational database systems. > As I said earlier, I don't use MySQL. I wasn't aware it didn't have > transactions -- what did people use it for, then? So is the upshot is > that he should thump himself for using a DBMS w/o transactions, > perhaps? Some awareness of common practice would certainly be beneficial. Attempting to insert data into PostgreSQL, Oracle, sqlite and so on would produce similar results to those described. The principal difference is that with MySQL (and presumably with things like Microsoft Access' storage engine that no-one takes seriously anyway), everyone has been able to get away with ignoring transactions and considering such behaviour as normal (or not even considering that anyone really uses anything which does anything else), and this obviously affects software governed by such assumptions. I suppose it's unfortunate for anyone who was using MySQLdb prior to release 1.2.0, especially if the software didn't give any obvious run-time warnings (not that I can say whether it did or not), but the MySQL-centric culture of ignoring/ridiculing stuff they don't support (and then eventually supporting it, in this case) is probably most to blame if we have to point the finger. Paul From cdsmith at twu.net Mon Jul 17 11:42:35 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 17 Jul 2006 09:42:35 -0600 Subject: What is a type error? References: <1152542831.623833.25880@m79g2000cwm.googlegroups.com> <1152597340.855103.153510@b28g2000cwb.googlegroups.com> <1152721450.433219.269270@s13g2000cwa.googlegroups.com> <44B536EB.6020308@durchholz.org> <1152728150.911515.263640@s13g2000cwa.googlegroups.com> <1152757188.426777.216560@h48g2000cwc.googlegroups.com> <1152805549.184625.117520@s13g2000cwa.googlegroups.com> <1152996978.533372.223000@b28g2000cwb.googlegroups.com> <1153017376.379831.306420@35g2000cwc.googlegroups.com> <1153070922.854289.270130@75g2000cwc.googlegroups.com> <1153091295.520674.287230@i42g2000cwa.googlegroups.com> Message-ID: Joachim Durchholz wrote: > I fail to see an example that would support such a claim. > > On the other hand, UPDATE can assign any value to any field of any > record, so it's doing exactly what an assignment does. INSERT/DELETE can > create resp. destroy records, which is what new and delete operators > would do. > > I must really be missing the point. I *think* I understand Marshall here. When you are saying "assignment", you mean assignment to values of attributes within tuples of the cell. When Marshall is saying "assignment", he seems to mean assigning a completely new *table* value to a relation; i.e., wiping out the entire contents of the relation and replacing it with a whole new set of tuples. Your assignment is indeed less powerful than DML, whereas Marshall's assignment is more powerful than DML. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From jedi200581 at yahoo.co.uk Thu Jul 20 02:48:03 2006 From: jedi200581 at yahoo.co.uk (jedi200581 at yahoo.co.uk) Date: 19 Jul 2006 23:48:03 -0700 Subject: Weird MemoryError issue In-Reply-To: <44be9342$1@news.eftel.com> References: <1153324701.599726.167760@h48g2000cwc.googlegroups.com> <44be90a7@news.eftel.com> <44be9342$1@news.eftel.com> Message-ID: <1153378083.344035.114640@h48g2000cwc.googlegroups.com> John Machin wrote: > On 20/07/2006 6:05 AM, John Machin wrote: > > On 20/07/2006 1:58 AM, jedi200581 at yahoo.co.uk wrote: > >> def is_prime n: > > > > Syntax error. Should be: > > def is_prime n: > > Whoops! Take 2: > > Should be: > > def is_prime(n): Sorry for that, I was not able to cut-paste the code at the moment, and was in a hurry, I know it's bad. Thanks for "xrange", I tried and it works fine. From fredrik at pythonware.com Wed Jul 12 03:19:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 12 Jul 2006 09:19:52 +0200 Subject: file.readlines() and IOError exceptions In-Reply-To: <44B43CA9.8090906@al.com.au> References: <44B43CA9.8090906@al.com.au> Message-ID: Astan Chee wrote: > now the file Im trying to read has recently had alot of read/writes from > other users/threads/etc, so every now and again I get a > IOError: [Errno 9] Bad file descriptor > I know this has something to do with not being able to read while some > filehandles are open (or is it?).. EBADF usually means that you're trying to read from a file that's no longer open. other users shouldn't be able to cause that error; I'd suspect sloppy thread programming... From conrad.ammon at gmail.com Mon Jul 3 06:03:59 2006 From: conrad.ammon at gmail.com (cmdrrickhunter@yaho.com) Date: 3 Jul 2006 03:03:59 -0700 Subject: list comprehension In-Reply-To: <1151906077.222770.111720@a14g2000cwb.googlegroups.com> References: <1151600332.552024.119990@y41g2000cwy.googlegroups.com> <1151602493.629010.269360@i40g2000cwc.googlegroups.com> <1151713797.748621.294120@i40g2000cwc.googlegroups.com> <1151717684.199257.191880@m73g2000cwd.googlegroups.com> <1151906077.222770.111720@a14g2000cwb.googlegroups.com> Message-ID: <1151921039.222869.308790@v61g2000cwv.googlegroups.com> I woulkdn't interate at the same time. zip takes two lists, and makes a single list of tuples, not the other way around. The easilest solution is feed_list = [ix.url for ix in feeds_list_select] feed_id = [ix.id for ix in feeds_list_select] Also, a big feature of list comprehension is it filters too... for example high_id_names = [ix.url for ix in feeds_list_select if ix.id > 500] Sometimes list comprehensions just read nicely. a wrote: > hey guys > this is gr8 > but in cheetah > i use > for test in $ix > $test.url > end for > to iterate thru loop > > now how do i iterate feed_list and feed_id along with i, > thanks a lot > > N = [(ix.url, ix.id) for ix in feeds_list_select] > > feed_list, feed_id = zip(*N) > > or just > > feed_list, feed_id = zip(*[(ix.url, ix.id) for ix in > feeds_list_select]) > > Simon Forman wrote: > > a wrote: > > > hi simon thanks for your reply > > > > You're most welcome > > > > > > > what if i want to do this > > > feed_list=[] > > > feed_id=[] > > > for ix in feeds_list_select: > > > global feeds_list > > > global feeds_id > > > feeds_list.append(ix.url) > > > feeds_id.append(ix.id) > > > > > > ie not one variable but more variables > > > thanks > > > > in a case like this I would usually reach for the zip() function, with > > the "varargs" * calling pattern > > > > N = [(ix.url, ix.id) for ix in feeds_list_select] > > > > feed_list, feed_id = zip(*N) > > > > > > or just > > > > feed_list, feed_id = zip(*[(ix.url, ix.id) for ix in > > feeds_list_select]) > > > > > > btw, please note that the global statements in your example are > > unnecessary.. *totally* unnecessary. :-D From vatamane at gmail.com Tue Jul 18 16:17:32 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 18 Jul 2006 13:17:32 -0700 Subject: No need to close file? In-Reply-To: References: <1153252214.457508.269880@35g2000cwc.googlegroups.com> Message-ID: <1153253852.070908.97460@35g2000cwc.googlegroups.com> I think file object should be closed whether they will be garbage collected or not. The same goes for DB and network connections and so on. Of course in simple short programs they don't have to, but if someone keeps 1000 open files it might be better to close them when done. Besides open files (in 'w' mode) might not be able to be opened by another process if they are not closed. In general this is usually a good habit to have (just like washing dishes right after a meal rather than hoping someone will do it later eventually ;) Regards, Nick V. Sybren Stuvel wrote: > T enlightened us with: > > Do I need to close the file in this case? Why or why not? > > > > for line in file('foo', 'r'): > > print line > > Nope, it'll get closed automatically when the file object gets garbage > collected. > > Sybren > -- > The problem with the world is stupidity. Not saying there should be a > capital punishment for stupidity, but why don't we just take the > safety labels off of everything and let the problem solve itself? > Frank Zappa From durumdara at gmail.com Thu Jul 20 09:47:42 2006 From: durumdara at gmail.com (Dara Durum) Date: Thu, 20 Jul 2006 15:47:42 +0200 Subject: Encode filenames to safe format Message-ID: <9e384ef60607200647r1b12559bia8d1892f2ad799d@mail.gmail.com> Hi ! I want to encode filenames to safe format, like in browser url (space -> %20, etc.). What the module and function name that helps me in this project ? Thanx for it: dd -------------- next part -------------- An HTML attachment was scrubbed... URL: From geli at tasmail.com Thu Jul 6 02:10:47 2006 From: geli at tasmail.com (gel) Date: 5 Jul 2006 23:10:47 -0700 Subject: How to trap the event of a new process starting with wmi In-Reply-To: <1152163890.268879.76400@75g2000cwc.googlegroups.com> References: <1152163890.268879.76400@75g2000cwc.googlegroups.com> Message-ID: <1152166246.899882.145850@m79g2000cwm.googlegroups.com> gel wrote: > Below is how it is down with vbscript. What is the best way to convert > this to python? > > strComputer = "." > Set objWMIService = GetObject("winmgmts:" _ > & "{impersonationLevel=impersonate}!\\" & strComputer & > "\root\cimv2") > Set colMonitoredProcesses = objWMIService. _ > ExecNotificationQuery("select * from __instancecreationevent " _ > & " within 1 where TargetInstance isa 'Win32_Process'") > i = 0 > > Do While i = 0 > Set objLatestProcess = colMonitoredProcesses.NextEvent > Wscript.Echo objLatestProcess.TargetInstance.Name > Loop A better question might be is there a method or guide for converting from vbs wmi to python wmi? From rogue_pedro at yahoo.com Fri Jul 7 16:54:07 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 7 Jul 2006 13:54:07 -0700 Subject: how can I avoid abusing lists? References: <1152289113.007295.23320@s13g2000cwa.googlegroups.com> <1152299404.248235.125160@h48g2000cwc.googlegroups.com> Message-ID: <1152305647.480844.279650@s13g2000cwa.googlegroups.com> Thomas Nelson wrote: > Thanks to everyone who posted. First, I don't think my question was > clear enough: Rob Cowie, Ant, Simon Forman, mensanator at aol.com, and Jon > Ribbens offered solutions that don't quite work as-is, because I need > multiple values to map to a single type. Tim Chase and Bruno > Destuilliers both offer very nice OOP solutions, and I think this is > the route I will probably go. However, for the simplest and easiest > solution, I really like this from Peter Otten: > inflated = [0]*5 > groups = [[0,1,3],[4],[2]] > for value in [1,1,0,4]: > inflated[value] += 1 > print [sum(inflated[i] for i in group) for group in groups] > > 4 lines (one more to assign the lists to name values, but that's > minor), and intuitive. If I had just thought of this to begin with, I > wouldn't have bothered posting. > > Thanks to all for the advice. > > THN I want to be sure I understand the above. inflated is a list of counters, one for each "type code"? groups is a list of groups of "type codes", one for each actual "type"? The for loop simulates four calls to an "increment()" function? The list comprehension sums all the counters that correspond to each actual type? so you could write: type1, type2, type3 = groups = [[0,1,3],[4],[2]] Is that right? Wow, very nice. Peace, ~Simon It was too easy to read map = {0:type1, 1:type1, 2:type3, 3:type1, 4:type2} as map = {0:type1, 1:type2, 2:type3, 3:type4, 4:type5} sorry. From fcorreia at gmail.com Sat Jul 8 12:46:05 2006 From: fcorreia at gmail.com (Filipe) Date: 8 Jul 2006 09:46:05 -0700 Subject: handling unicode data In-Reply-To: <1152344563.826456.66010@35g2000cwc.googlegroups.com> References: <1151684068.319765.42270@y41g2000cwy.googlegroups.com> <44a5b4f0$0$29917$9b622d9e@news.freenet.de> <1152024185.353047.263030@75g2000cwc.googlegroups.com> <44AAAF72.6050002@v.loewis.de> <1152098061.373859.159710@v61g2000cwv.googlegroups.com> <44AC0AD3.3040802@v.loewis.de> <1152200552.730834.187740@b68g2000cwa.googlegroups.com> <1152206961.838399.113410@m79g2000cwm.googlegroups.com> <1152271022.346944.171220@m73g2000cwd.googlegroups.com> <1152344563.826456.66010@35g2000cwc.googlegroups.com> Message-ID: <1152377165.077158.145410@b28g2000cwb.googlegroups.com> Frank Millman wrote: > Filipe wrote: > Try out the suggestions and let us know what happened. I for one will > be very interested. The last version of ODBTPAPI is 0.1-alpha, last updated 2004-09-25. Which is a bit scary... I might try it just the same though. From cliff at develix.com Mon Jul 31 17:23:17 2006 From: cliff at develix.com (Cliff Wells) Date: Mon, 31 Jul 2006 14:23:17 -0700 Subject: Using Python for my web site In-Reply-To: <1insadcgifsbv.dlg@gelists.gmail.com> References: <1154361480.915174.262720@b28g2000cwb.googlegroups.com> <44ce3a5c$0$18952$626a54ce@news.free.fr> <1154367359.931684.106650@m73g2000cwd.googlegroups.com> <44ce4530$0$28242$626a54ce@news.free.fr> <1pbgluuxgrgbf$.dlg@gelists.gmail.com> <1154377680.20290.37.camel@devilbox> <1insadcgifsbv.dlg@gelists.gmail.com> Message-ID: <1154380997.20290.64.camel@devilbox> On Mon, 2006-07-31 at 17:58 -0300, Gerhard Fiedler wrote: > On 2006-07-31 17:28:00, Cliff Wells wrote: > > >> I assume you don't agree... :) > > > > I certainly don't. [...] > > > Also, saying "a few years ago I did some research" in software terms is > > pretty much equivalent to saying "I don't know". > > Exactly. So what's your point with this comment? My point is to stop FUD right at that comment. I don't doubt your research from "a few years ago", but ancient research is entirely irrelevant for making a decision *today*. However, had I let it pass, then someone else might not make that distinction and come away with the impression that your research was somehow still relevant and that PostgreSQL is less reliable than MySQL. > I stated what was my impression at the time, with the hope that others > might want to comment. Thanks for the comment. You're welcome. > OTOH, anybody who says "I know" regarding a comparison in reliability > between databases must have pretty good data to back that up. Few have. > Most are in the "I don't know, but my impression is that ..." group. Absolutely. I can only give you anecdotal evidence myself. Further, if someone were to present a whitepaper of some sort demonstrating that one is superior with regard to reliability or performance, I'd probably be highly suspect of their motives. Regardless, since my job as a hoster requires that I assist customers with database issues, I have hands-on experience with dozens of instances of each and my *very recent* experience tells me that MySQL is far more prone to database corruption than PostgreSQL. In the past 6 months, I've repaired or restored at least 4 MySQL databases (and for no apparent reason, to boot), but I've had to do the same for exactly zero PostgreSQL installs since I started hosting over 3 years ago. And just to be clear, the number of PostgreSQL installs far exceeds the number of MySQL installs. Were there equal numbers of each I'd expect even more MySQL problems. Regards, Cliff -- From frank at chagford.com Sun Jul 9 04:08:37 2006 From: frank at chagford.com (Frank Millman) Date: 9 Jul 2006 01:08:37 -0700 Subject: Scope, type and UnboundLocalError In-Reply-To: <1152428844.123150.281420@75g2000cwc.googlegroups.com> References: <1152428844.123150.281420@75g2000cwc.googlegroups.com> Message-ID: <1152432517.210392.243040@75g2000cwc.googlegroups.com> Paddy wrote: > Hi, > I am trying to work out why I get UnboundLocalError when accessing an > int from a function where the int is at the global scope, without > explicitly declaring it as global but not when accessing a list in > similar circumstances. > There has just been a long thread about this. I think I understand it now. Here is my explanation. Ignoring nested scopes for this exercise, references to objects (i.e. variable names) can exist in the local namespace or the global namespace. Python looks in the local namespace first, and if not found looks in the global namespace. Any name assigned to within the function is automatically deemed to exist in the local namespace, unless overridden with the global statement. With the statement 'm = m + 1', as m is assigned to on the LHS, it is deemed to be local, but as m does not yet have a value on the RHS, you get Unbound Local Error. With the statement 'n[0] = n[0] + 1', n is not being assigned to, as it is mutable. Therefore Python looks in the global namespace, finds n there, and uses it successfully. My 2c Frank Millman From __peter__ at web.de Wed Jul 19 11:19:50 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Jul 2006 17:19:50 +0200 Subject: access to submodules References: <1153315605.086825.229830@i3g2000cwc.googlegroups.com> <1153315931.613796.117060@p79g2000cwp.googlegroups.com> <1153317444.615450.139700@h48g2000cwc.googlegroups.com> <1153317958.271921.306370@m73g2000cwd.googlegroups.com> <1153318278.065067.8520@b28g2000cwb.googlegroups.com> <1153318863.215301.52120@p79g2000cwp.googlegroups.com> Message-ID: TG wrote: > if I import tom, it is supposed to load functions defined in > tom/__init__.py and make all the modules inside accessible through the > "dot" syntax. > > Therefore, this is supposed to work : > > ?> import tom > ?> help(tom.core) > > AttributeError: 'module' object has no attribute 'core' > > But if I use the baaaaad star syntax > > ?> from tom import * > ?> help(core) > > this will work. No, it won't. Try again with a fresh interpreter (no prior imports) >>> from tom import * >>> core Traceback (most recent call last): File "", line 1, in ? NameError: name 'core' is not defined >>> import tom >>> tom.core Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'core' Only after an explicit import of tom.core... >>> from tom import core >>> del core >>> from tom import * >>> core is core added as an attribute to tom and will therefore be copied into the namespace of a module doing a star-import. Peter From vatamane at gmail.com Fri Jul 28 09:34:13 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 28 Jul 2006 06:34:13 -0700 Subject: Newbie..Needs Help References: <44ca0e2b$0$1207$afc38c87@news.optusnet.com.au> Message-ID: <1154093653.922739.309980@b28g2000cwb.googlegroups.com> Your description is too general. The way to 'collect the results' depends largely in what format the results are. If they are in an html table you will have to parse the html data if they are in a simple plaintext you might use a different method, and if the site renders the numbers to images and adds some noise and font effects to them, then you can abandon the idea altogether unless you have a good background in OCR. But let's assume that you data is embedded an html sourse. Even so you, it would largely depend on the specific syntax used. Sometimes you could just use regular expressions, other times a full HTML parser will be needed. Then you could have the issue of 'how to get to the right page' and/or 'how to uniquely identify and match each of the previously parsed rows of data to the new set of rows of data that also have the results added to them?' Perhaps if you post the website plus a clear and exact description of what you want to accomplish and what has already been accomplished you might find someone to help. -Nick V. Graham Feeley wrote: > Hi this is a plea for some help. > I am enjoying a script that was written for me and its purpose is to collect > data from a web site and puts it into a access database table. > It works fine, however it is a sports info table but now I need to collect > the results of those races. > > I simply can't keep up putting the results in manually. > I dont care if it is a access table or a text file ( whichever is easiest) > there are only 12 fields to extract > The person who wrote the script is not available as he is engrossed in > another project which is talking all his time. > I hope someone has a little time on his hands willing to help me > Regards > Graham From vatamane at gmail.com Wed Jul 12 05:22:59 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 12 Jul 2006 02:22:59 -0700 Subject: Object Persistence Using a File System In-Reply-To: <44b4afbb$0$5502$626a54ce@news.free.fr> References: <1O%sg.3749$wZ.3322@trndny01> <44b4afbb$0$5502$626a54ce@news.free.fr> Message-ID: <1152696179.937164.140390@b28g2000cwb.googlegroups.com> Good point about isinstance. Here is a good explanation why: http://www.canonical.org/~kragen/isinstance/ Also the frozenset should be added the list of immutable types. Nick Vatamaniuc Bruno Desthuilliers wrote: > Chris Spencer wrote: > > Before I get too carried away with something that's probably > > unnecessary, please allow me to throw around some ideas. I've been > > looking for a method of transparent, scalable, and human-readable object > > persistence, and I've tried the standard lib's Shelve, Zope's ZODB, > > Divmod's Axiom, and others. However, while they're all useful, none > > satisfies all my criteria. So I started writing some toy code of my own: > > http://paste.plone.org/5227 > > > > All my code currently does is transparently keep track of object changes > > without requiring any special coding on part of the user, and a function > > to convert an object to a file system hierarchy of folders and files. > > Please, let me know what you think. > > As you say, using filesystem for fine-grained persistance may not be the > most efficient solution. I also wonder how (if...) you intend to address > concurrent R/W access and transactions... > > A few observations and questions : > - you should avoid tests on concrete types as much as possible - at > least use isinstance > - tuples are immutable containers. What about them ? > - what about multiple references to a same object ? > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From no at spam.please Tue Jul 18 19:25:59 2006 From: no at spam.please (Lars) Date: Wed, 19 Jul 2006 01:25:59 +0200 Subject: Track keyboard and mouse usage In-Reply-To: <4i29tbF1s6otU1@uni-berlin.de> References: <1153163579.760753.236340@p79g2000cwp.googlegroups.com> <4i261mF1njk3U1@uni-berlin.de> <4i29tbF1s6otU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > will make the devices world readable. While I haven't thought about any > security implications that might have (and am not especially > knowledgeable in such things to be honest), I'm convinced it is way less > likely to introduce any exploitable holes than suid root would. Depending on what kind of info these devices produce, couldn't they be used to spy on someone typing in a password? (I can't check, I'm on FreeBSD.) From eduardo.padoan at gmail.com Wed Jul 5 15:21:22 2006 From: eduardo.padoan at gmail.com (eduardo.padoan at gmail.com) Date: 5 Jul 2006 12:21:22 -0700 Subject: EnhancedObject: Yet Another Python ORM (an RFC) References: <1152113120.248414.326690@a14g2000cwb.googlegroups.com> <1152115118.517322.99460@75g2000cwc.googlegroups.com> Message-ID: <1152127282.021241.196520@75g2000cwc.googlegroups.com> > So why tell us? What are your ideas? What does your design do that the > others don't? Basically, the API I exemplificated in the first exemple. My initial idea was to have a way of turn alread designed objects into persistent ones. This is not the goal of SQLObject, for example. Other litle difference is the 'multiplexity' (mult) argument in the EAssociation. From phil_nospam_schmidt at yahoo.com Mon Jul 17 14:04:47 2006 From: phil_nospam_schmidt at yahoo.com (Phil Schmidt) Date: 17 Jul 2006 11:04:47 -0700 Subject: sqlobject for Python 2.5 Message-ID: <1153159486.965366.100870@35g2000cwc.googlegroups.com> I'd like to get sqlobject for Python 2.5, but it appears it's not available. Can I use sqlobject for Python 2.4 and use it on 2.5? If so, how? I have no experience using setuptools, but it appears that unless there's a specific .egg file for 2.5, then I'm outta luck. True? Thanks, Phil From gherron at islandtraining.com Sat Jul 1 13:23:57 2006 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 01 Jul 2006 10:23:57 -0700 Subject: missing feature classes and missing fields In-Reply-To: <200607010642.MAA21799@WS0005.indiatimes.com> References: <200607010642.MAA21799@WS0005.indiatimes.com> Message-ID: <44A6AFAD.9080907@islandtraining.com> subramanian2003 wrote: > Hello All, > > How can I check missing feature classes in a folder/personal geodatabase using python script. And how can I check missing fields in shape files. And also I want to check the attribute values using python. > > Thnx, > Subramanian. > > > > This list is usually very helpful, however, I think you are going to need to be more specific to get an answer here. For instance, What's are "missing feature classes"? What's a "folder/personal geodatabase"? What's are "missing fields"? What's a "shape file"? On what object to you wish to check "attribute values"? I'm not sure I can help even if I have those answers, but I'm sure I can't help if I don't. Gary Herron From piet at cs.uu.nl Mon Jul 17 08:05:55 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 17 Jul 2006 14:05:55 +0200 Subject: Augument assignment versus regular assignment References: <1152328454.430620.59050@m79g2000cwm.googlegroups.com> <1152424924.533353.323280@75g2000cwc.googlegroups.com> <12b4i7c75nits85@corp.supernews.com> Message-ID: >>>>> Antoon Pardon (AP) wrote: >AP> On 2006-07-14, Piet van Oostrum wrote: >>> Just read what it says. `It is only evaluated once' is quite clear I would >>> say. >AP> If it is so clear, why don't you explain it? I have done that in another thread. >>> Your problem is that you thought __setitem__ is part of evaluation, >AP> No I think the other way around. The evaluation is part of __setitem__ >AP> In so far as it makes sense to talk about the evaluation of a target >AP> in python How can evaluation be part of __setitem__? (If we talk about targets). The LRM says clearly that it is part of assignment. >>> but it isn't. It is part of assignment, >AP> No the assignment is part of __setitem__ __setitem__( self, key, value) Called to implement assignment to self[key] >>> while __getitem__ is part of evaluation. >AP> How can __getitem__ be part of the evaluation of col['t'] in >AP> a statment like >AP> col['t'] = 5 It isn't, because there is a difference between evaluation in the lefthandside and in the righthandside. See the description of assignment. >AP> The language reference about augmented assigments is not only >AP> talking about evaluating a language element as an expression, >AP> it is also talking about evaluating that language element as >AP> a target. Now I'm not so sure that it makes sense to talk about >AP> evaluating a target in python, but I see no way to avoid that >AP> interpretation in: In the description of assignment the distinction is made for each case of the lefthandside. So that for example when the lefthandside is a subscription, only the primary and the index are evaluated, but no __getitem__ is called. >AP> An augmented assignment expression like x += 1 can be rewritten as >AP> x = x + 1 to achieve a similar, but not exactly equal effect. In >AP> the augmented version, x is only evaluated once. >AP> x is only evaluated once in a statement like: x+= 1 >AP> This suggests x is evaluated twice in a statement like: x = x + 1 >AP> The only way to eavlaute x twice in that statement is that >AP> x is evaluated once as a target. >AP> So the langauage reference is here talking about (among other things) >AP> evaluating a target. yes. >AP> What the language reference should have said IMO is that in case x >AP> is an attribute reference, index or slicing, the primary expression >AP> will be evaluated only once, as will be the index or slice in the >AP> two latter cases. You should read the part about Augmented assignment statements after carefully reading the part about assignments. Then you know already that evaluation of the target is only about the primary and the index. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From Michael.J.Fromberger at Clothing.Dartmouth.EDU Tue Jul 18 14:53:36 2006 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Tue, 18 Jul 2006 14:53:36 -0400 Subject: Dispatch with multiple inheritance Message-ID: Consider the following class hierarchy in Python: class A (object): def __init__(self): print "cons A" class B (object): def __init__(self): print "cons B" class C (A): def __init__(self): super(C, self).__init__() print "cons C" class D (B): def __init__(self): super(D, self).__init__() print "cons D" Now, suppose I would like to define a new class as follows: class E (C, D): ... In the constructor for E, I would like to invoke the constructors of both parent classes. The correct way to do this seems to be exemplified by the following: class E (C, D): def __init__(self): super(E, self).__init__() # calls C constructor super(A, self).__init__() # calls D constructor (**) print "cons E" This works, but I find it somewhat troubling. It seems to me that one should not have to "know" (i.e., write down the names of) the ancestors of C in order to dispatch to superclass methods in D, since C and D share no common ancestors south of object. Is there a better (i.e., more elegant) way to handle the case marked (**) above? Curious, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From invalidemail at aerojockey.com Sun Jul 16 16:10:36 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 16 Jul 2006 13:10:36 -0700 Subject: insert method in ElementTree In-Reply-To: <1153073550.140238.70060@p79g2000cwp.googlegroups.com> References: <1153073550.140238.70060@p79g2000cwp.googlegroups.com> Message-ID: <1153080636.472539.232900@h48g2000cwc.googlegroups.com> mirandacascade at yahoo.com wrote: > My request for advice is this: instead of creating a second XML > document that represents the output, would it be possible to expand the > input XML document as needed? I was thinking that the program could > iterate through all the elements. As it is iterating, it would check > for the createAnotherWhenCondition attribute. If encountered and if > the condition were true, the program would: > - make a copy of the parent element (perhaps with copy.copy) > - use the insert method to insert the just-created copy > Where I'm struggling is figuring out what the index argument should > be in the insert method. I recommend not using the insert method; instead, build a new list of elements and set the parent to the new list. Another problem is that you have to have the parent node around, since children don't indicate their parents. Using getiterator won't work. I recommend a recursive function instead. Something like this should do it: def expand_children(parent): if len(parent) == 0: return newchildren = [] for child in parent: expand_children(child) # recursively process child nodes if : newchildren.append(child) # or copy.copy(child) newchildren.append(child) parent[:] = newchildren # slice assign So, basically, for each node, you build a list of children in parallel, making duplicates as necessary, then use slice assignment to set the parent's children to be the new list. No more mucking around with indexes. Carl Banks From bdesth.quelquechose at free.quelquepart.fr Tue Jul 18 19:29:17 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 19 Jul 2006 01:29:17 +0200 Subject: Object Persistence Using a File System In-Reply-To: <1152696179.937164.140390@b28g2000cwb.googlegroups.com> References: <1O%sg.3749$wZ.3322@trndny01> <44b4afbb$0$5502$626a54ce@news.free.fr> <1152696179.937164.140390@b28g2000cwb.googlegroups.com> Message-ID: <44bd6d3e$0$21607$626a54ce@news.free.fr> Nick Vatamaniuc a ?crit : (please don't top-post - corrected) > > Bruno Desthuilliers wrote: > (snip) >>A few observations and questions : >>- you should avoid tests on concrete types as much as possible - at >>least use isinstance > > Good point about isinstance. Here is a good explanation why: > http://www.canonical.org/~kragen/isinstance/ Err... I'm sorry but justifying the use of explicit tests on concrete type not even taking inheritance into consideration with a paper explaining why type tests taking inheritance into consideration may be bad seems rather strange to me... Or did I missed your point here ? From spam at spam.spam Sat Jul 22 20:45:50 2006 From: spam at spam.spam (rsd) Date: Sat, 22 Jul 2006 20:45:50 -0400 Subject: Sansung YH-920 + Linux + yh-925-db-0.1.py = AttributeError: 'module' object has no attribute 'decode' In-Reply-To: <1153609793.954581.23640@p79g2000cwp.googlegroups.com> References: <1153609793.954581.23640@p79g2000cwp.googlegroups.com> Message-ID: > > You don't say which version of Python you are running ... but my guess > is that it's 2.3 or earlier. Yes, you're right. I was using version 2.3.5 I'll see if I can get it working with 2.4 Thanks From originalbrownster at gmail.com Mon Jul 31 23:02:22 2006 From: originalbrownster at gmail.com (OriginalBrownster) Date: 31 Jul 2006 20:02:22 -0700 Subject: FOR LOOPS Message-ID: <1154401342.560477.235640@i3g2000cwc.googlegroups.com> I am using a class called UploadedFile. I want to create a for loop to itterate through the objects within file name class UploadedFile(SQLObject): filename = StringCol(alternateID=True) abspath = StringCol() uniqueid = IntCol() I'll show you a snippit of the code I am trying to use it in:: zip= ["zip.txt"] file_path = [myfile.filename for myfile in UploadedFile.select(orderBy=UploadedFile.q.filename)] if kw: for filename in file_path: zip.append(filename) flash('Options selected'+ str(kw) + str(zip)) else: pass When i run this the flash displays all the values for kw...however zip only shows up as "zip.txt" using the str function. Meaning that the FOR LOOP is not working correctly. Any ideas why this is happening?? perhaps someone could shoe me how to make a proper list for this if this is incorrect. Thank you From davehowey at f2s.com Wed Jul 19 12:41:31 2006 From: davehowey at f2s.com (davehowey at f2s.com) Date: 19 Jul 2006 09:41:31 -0700 Subject: using names before they're defined In-Reply-To: <1153326926.822085.219150@m73g2000cwd.googlegroups.com> References: <1153323036.369990.182240@i42g2000cwa.googlegroups.com> <1153326926.822085.219150@m73g2000cwd.googlegroups.com> Message-ID: <1153327291.435761.316560@i3g2000cwc.googlegroups.com> > Even if you need to do something during attachment of components it is > more Pythonic to use properties. So you will write a method in your > class name something like _set_up(self,upstream_obj) an _get_up(self). > And then at the end of your class put up=property(_get_up, _set_up). > You can still use the compr.up=... format. sorry, I don't quite follow. what are properties? > Also, you might want to re-think your OO design. It seem that all of > your components do a lot of things in common already. For one they all > are connected to other components like themselves, they also propably > will have method to do some computing, perhaps send or receive stuff > from other components, or they all will implement somekind of an event > model. In that case you could create a generic component class and > sublass the specific implementations from it. yes, I already do this - I have a component class and then the other components inherit from it. Dave From diffuser78 at gmail.com Sat Jul 29 16:33:46 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 29 Jul 2006 13:33:46 -0700 Subject: Math package References: <1154199358.875446.62310@b28g2000cwb.googlegroups.com> <1154202722.389656.244660@h48g2000cwc.googlegroups.com> Message-ID: <1154205226.881465.172070@s13g2000cwa.googlegroups.com> I will write the problem a little more clearer so that you guys can recommend me better. In a graphs of size N ( where, N = 1e9), each node has a degree D=1000. i.e There are overall (D*N)/2 edges in the graph. This graph needs to be generated randomly using the program. Now my task is to find the shortest distance from each node to every other node. And finally I want to find is the average distance from one node to another node in the graph. This is an average Erdos number or equivalently what degree of seperation exists in the graph. I can start with low values of N and D but my ultimate aim is to simulate this graph on big values of N and D. Every help is greatly appreciated. Thanks bearophileHUGS at lycos.com wrote: > diffuser78 at gmail.com: > > I want to write a program which would have a 2 dimensional array of 1 > > billion by 1 billion. This is for computational purposes and evaluating > > a mathematical concept similar to Erdos number. > > Maybe you are talking about the edges of a graph with 1e9 nodes. This > structure is surely quite sparse, so you don't need to store the edges > in a matrix, you can manage is as a sparse structure, and maybe you > don't need a Blue Gene. > > If you find ways to clean your data, reduce the vertex and arc count, > and if you have a lot of memory, then maybe Boost Graph for Python may > suffice: > http://www.osl.iu.edu/~dgregor/bgl-python/ > > Bye, > bearophile From grflanagan at yahoo.co.uk Wed Jul 26 12:45:58 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 26 Jul 2006 09:45:58 -0700 Subject: list problem In-Reply-To: <1153930721.406207.134340@s13g2000cwa.googlegroups.com> References: <1153886273.925853.60520@b28g2000cwb.googlegroups.com> <1153930721.406207.134340@s13g2000cwa.googlegroups.com> Message-ID: <1153932358.615129.220390@b28g2000cwb.googlegroups.com> Gerard Flanagan wrote: > placid wrote: > > Hi all, > > > > I have two lists that contain strings in the form string + number for > > example > > > > >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX5'] > > > > the second list contains strings that are identical to the first list, > > so lets say the second list contains the following > > > > >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX6'] > > > > and now what ive been trying to do is find the first string that is > > available, > > i.e a string that is in neither of the two lists so the following code > > should only print XXX4 then return. > > > > for i in xrange(1,10): > > numpart = str(1) + str("%04i" %i) > > str = "XXX" + numpart > > > > for list1_elm in list1: > > if list1_elm == str: > > break > > else: > > for list2_elm in list2: > > if list2_elm == str: > > break > > else: > > print str > > return > > > > Cheer > > I don't know how close the following is to what you want ( or how > efficient etc...). If both lists are the same up to a certain point, > then the first function should do, if not, try the second function. > > Gerard > > from itertools import izip, dropwhile > > def get_first_missing1( seq1, seq2 ): > i = int( seq1[0][-1] ) > for x1, x2 in izip( seq1, seq2 ): > if int(x1[-1]) != i and int(x2[-1]) != i: > return x1[:-1] + str(i) > i += 1 > return -1 > > def get_first_missing2( seq1, seq2 ): > i = int( seq1[0][-1] ) > j = int( seq2[0][-1] ) > if j < i: > seq1, seq2 = seq2, seq1 > i, j = j, i > return get_first_missing1( list(dropwhile(lambda s: int(s[-1]) < j, > seq1)), seq2 ) > > L1 = [ 'XXX1', 'XXX2', 'XXX3', 'XXX5'] > L2 = [ 'YYY1', 'YYY2', 'YYY3', 'YYY6'] > > print get_first_missing1(L1, L2) > print get_first_missing2(L1, L2) > 'XXX4' > 'XXX4' ehm...a bit limited in what it will handle, now that I look at it! like more than ten items in a list - '11'[-1] == '1'...no time to test further, sorry:( Gerard From sjmaster at gmail.com Fri Jul 28 12:28:56 2006 From: sjmaster at gmail.com (Steve M) Date: 28 Jul 2006 09:28:56 -0700 Subject: Unicode question References: Message-ID: <1154104136.058131.12850@m73g2000cwd.googlegroups.com> Ben Edwards (lists) wrote: > I am using python 2.4 on Ubuntu dapper, I am working through Dive into > Python. > > There are a couple of inconsictencies. > > Firstly sys.setdefaultencoding('iso-8859-1') does not work, I have to do > sys.setdefaultencoding = 'iso-8859-1' When you run a Python script, the interpreter does some of its own stuff before executing your script. One of the things it does is to delete the name sys.setdefaultencoding. This means that by the time even your first line of code runs that name no longer exists and so you will be unable to invoke the function as in your first attempt. The second attempt "sys.setdefaultencoding = 'iso-8859-1' " is creating a new name under the sys namespace and assigning it a string. This will not have the desired effect, or probably any effect at all. I have found that in order to change the default encoding with that function, you can put the command in a file called sitecustomize.py which, when placed in the appropriate location (which is platform-dependent), will be called in time to have the desired effect. So the order of events is something like: 1. Invoke Python on myscript.py 2. Python does some stuff and then executes sitecustomize.py 3. Python deletes the name sys.setdefaultencoding, thereby making the function that was so-named inaccessible. 4. Python then begins executing myscript.py. Regarding the location of sitecustomize.py, on Windows it is C:\Python24\Lib\sitecustomize.py. My guess is that you should put it in the same directory as the bulk of the Python standard library files. (Also in that directory is a subdirectory called site-packages, where you can put custom modules that will be available for import from any of your scripts.) From stefita at gmail.com Wed Jul 5 12:25:24 2006 From: stefita at gmail.com (Stefka) Date: 5 Jul 2006 09:25:24 -0700 Subject: XML-RPC server-client communication Message-ID: <1152116724.487542.222680@b68g2000cwa.googlegroups.com> Hi all, I try to implement a python xml-rpc server and call it from a php client. If the server and the client are on the same machine (localhost) the communication between them is just fine. When I start the server on a different host I don't get an answer. What is missing there?? I tried also to set username and password, cause I thought there is an authenticate issue but it didn't work either. Here is my code: python server: import SimpleXMLRPCServer from re import * import string #The server object class myFunctions: def myTest(self, code): mya = findall('#include.+',code) stringo = string.join(mya,', ') return stringo calendar_object = myFunctions() server = SimpleXMLRPCServer.SimpleXMLRPCServer(("xxx.xxx.xxx.xxx", 22999)) server.register_instance(calendar_object) #Go into the main listener loop print "Listening on port 22999" server.serve_forever() php client: #include'; $function = "myTest"; $param = new XML_RPC_Value(htmlspecialchars($code), "string"); $params = array($param); $message = new XML_RPC_Message($function, $params); $client = new XML_RPC_Client("/new2.py","xxx.xxx.xxx.xxx",22999); print_r($client); $result = $client->send($message); print_r($result); $value = $result->value(); $number = $value->scalarval(); echo "

Return Value: $number

"; echo "

Headers are: $number

"; ?>
Thanx in advance :) From fredrik at pythonware.com Mon Jul 10 18:30:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 11 Jul 2006 00:30:47 +0200 Subject: About __files In-Reply-To: References: Message-ID: venkat pathy wrote: > I came across a series of functions starting with "__". For > example, __fun() . May I know what are all these functions ? > I came across __init__ like functions starting and ending with "__". > Whether they are constructors which are overloaded ? reading the documentation might be helpful: http://docs.python.org/tut/node11.html From hanumizzle at gmail.com Sat Jul 22 20:31:43 2006 From: hanumizzle at gmail.com (hanumizzle at gmail.com) Date: 22 Jul 2006 17:31:43 -0700 Subject: Which Pyton Book For Newbies? In-Reply-To: References: Message-ID: <1153614703.211074.38830@i3g2000cwc.googlegroups.com> W. D. Allen wrote: > I want to write a retirement financial estimating program. Python was > suggested as the easiest language to use on Linux. I have some experience > programming in Basic but not in Python. > > I have two questions: > 1. What do I need to be able to make user GUIs for the program, and > 2. Which book would be easiest to use to learn Python programming? I am a fairly experienced programmer and I have been reading Dive Into Python. If you have prior experience, you may find it very satisfactory. (But see a recent thread I started which points out a few small mistakes...nothing too bad over all.) If you have less programming experience, you may wish to look at Byte of Python. The great thing about Python is that there is a ton of online material to peruse... From onurb at xiludom.gro Tue Jul 18 10:04:46 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 18 Jul 2006 16:04:46 +0200 Subject: Accessors in Python (getters and setters) In-Reply-To: <1153213630.721413.95290@i42g2000cwa.googlegroups.com> References: <1152533987.503050.160980@b28g2000cwb.googlegroups.com> <1152610388.017929.285680@b28g2000cwb.googlegroups.com> <44b38b7e$0$14341$626a54ce@news.free.fr> <1152695847.706091.115340@b28g2000cwb.googlegroups.com> <44b4d9d6$0$14332$626a54ce@news.free.fr> <1152780657.174836.263530@h48g2000cwc.googlegroups.com> <44b61d94$0$23082$626a54ce@news.free.fr> <1152789577.742527.201570@75g2000cwc.googlegroups.com> <44b641e5$0$18110$636a55ce@news.free.fr> <1152801514.683329.252080@75g2000cwc.googlegroups.com> <44b66c67$0$31799$626a54ce@news.free.fr> <1152957314.252038.29290@m79g2000cwm.googlegroups.com> <1152975860.267475.166030@i42g2000cwa.googlegroups.com> <44bb8a7c$0$21801$626a54ce@news.free.fr> <1153213630.721413.95290@i42g2000cwa.googlegroups.com> Message-ID: <44bcea80$0$23108$626a54ce@news.free.fr> mystilleef wrote: > Bruno Desthuilliers wrote: > >>mystilleef wrote: >> >>>Gerhard Fiedler wrote: >>> >>> >>>>On 2006-07-15 06:55:14, mystilleef wrote: >>>> >>>> >>>> >>>>>In very well designed systems, the state of an object should only be >>>>>changed by the object. >>>> >>>>IMO that's not quite true. Ultimately, the state always gets changed by >>>>something else (user interaction, physical events); very few objects are >>>>completely self-contained in their behavior. >>>> >>> >>>Then in those cases the system becomes a victim of high coupling. >> >>Time to burn your book and face reality. ObjA sends message Msg1 to >>ObjB. Part of the associated behaviour is that in responce to Msg1, objB >>changes it's own state. Practical result : ObjB's state has been changed >>by ObjA. Practical question : how do you hope to avoid this "hi >>coupling" (lol), apart from making all your objects totally autistic ? >> > > > Are you serious? Deadly serious. But I'm afraid you're still missing the point. > Well, you design an object that serves as a mediator. > All objects can then only interact with themselves and the mediator > only. Via signals, objects learn to automatically adjust their states > and respond to events. signal -> message -> method call -> change state. Spell it how you like, add as many indirection levels you want, it still boils down to the fact that *something* triggers the state change. > This is just one of several methods you can > dramatically reduce coupling. It's just one of several methods that dramatically increases complexity, without changing anything to the fact that in the end, *practically*, some object ObjA changes its state as a response to a message sent by ObjB. > I'm sure glad I didn't burn my book. No comment. > >>>>In most systems (and you possibly have written some of them) are objects >>>>whose state gets changed by other objects -- possibly through the >>>>intermediation of setter methods that do nothing else but set the state. >>>>There's no conceptual difference between directly setting the state or >>>>calling a setter function that does nothing else but directly setting the >>>>state -- except for one unnecessary level of indirection in the latter. >>>> >>> >>> >>>It depends. If certain conditions need to be met before changing the >>>state of an object, then arbitrarily changing it can be dangerous. >> >>Does this imply a 'method call' *syntax* ? > > > That's language dependent. > > >>Given the existence of >>"computed attributes" (ie: support for 'attribute access' *syntax* with >>hidden accessors) and the possibility to redefine implementation (from >>default attribute r/w access to computed/controlled) without touching >>the interface, why advocate the *systematic* use of computed attributes >>when it's just duplicating the default behaviour ? >> > > > I'm not advocating anything. cf below on this. > I'm just stating the use case for > accessors and the wisdom behind them. My qualm with implicit accessors > remains the name issue. The "name issue" is *your* problem. And AFAICT, it's a "problem" because you refuse to free your mind from a "what's in the book" mindset. > >>>>>For example, a third party randomly changing is_active, (which Python >>>>>lets you do freely and easily) from False to True may crash your GUI. >>>>>And I'm not making this up. Things like this do really happen depending >>>>>on the whackyness of your toolkit. >>>> >>>>That's quite true, but a setter that does nothing but change is_active >>>>doesn't prevent this. If there is logic necessary to prevent state changes >>>>in certain situations, this should be implemented. But whether you then >>>>call this a part of the "behavior" (looking at the implementation as being >>>>a setter method) or a part of the "state" (looking at the implementation as >>>>being an added feature of the attribute) doesn't really make an objective >>>>difference. >>>> >>> >>> >>>Of course using setters for the sake of just using them is pointless. >> >>Indeed. >> >> >>>The reason to use them is if pre-conditions or post-conditions need to >>>be met. Or to control access to an objects states. >> >>Then why advocate *systematic* use of them ? >> >>(snip) > > I never advocated anything. You advocated """ 1). Make all attributes of a class private/protected . 2). If a "non-callable" attribute is going to be used outside a class, think about making it a property and name the property well, because you never know... """ > >>>State - behavior is not something I made up, so it isn't subjective. >> >>The words (and the concept they describe) are not. Interpretation of >>what is state and what is behaviour is subjective. >> >> >>>It >>>is a common term used in OO literature. In fact, the only reason I used >>>it is because I thought is was common knowledge. >> >>It is. >> >> >>>And behaviors are not >>>just necessarily getters/setters, they are methods of objects. >> >>Behaviour is how a given object reacts to a given message. *Nothing* in >>this implies the notions of attributes or methods. Attributes and >>methods are implementation details of the concepts of state and >>behaviour, and - while this is a common implementation of OO concepts - >> the choice to use non-callable attributes as representing the state >>and callable ones as representing behaviour is totally >>implementation-dependant. >> > > I agree. And I already told you I think in terms of state and behavior > and not language dependent semantics. Then why do you advise "(making) all attributes of a class private/protected" and systematically using properties ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jzgoda at o2.usun.pl Tue Jul 25 15:43:11 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 25 Jul 2006 21:43:11 +0200 Subject: cStringIO.StringIO has no write method? In-Reply-To: References: <44C66D88.8030601@designaproduct.biz> Message-ID: Laszlo Nagy napisa?(a): >> Nope. StringI is an input-only object, StringO is an output object. >> You got a StringI because you gave a string argument to the creator. >> >> >> >>> f1 = cStringIO.StringIO() >> >>> f1 >> >> >>> dir(f1) >> ['__class__', '__delattr__', '__doc__', '__getattribute__', >> '__hash__', '__init__', '__iter__', '__new__', '__reduce__', >> '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'close', >> 'closed', 'flush', 'getvalue', 'isatty', 'next', 'read', 'readline', >> 'readlines', 'reset', 'seek', 'softspace', 'tell', 'truncate', >> 'write', 'writelines'] >> >>> f2 = cStringIO.StringIO("This is the fixed content of the StringIO") >> >>> f2 >> >> >>> dir(f2) >> ['__class__', '__delattr__', '__doc__', '__getattribute__', >> '__hash__', '__init__', '__iter__', '__new__', '__reduce__', >> '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'close', >> 'closed', 'flush', 'getvalue', 'isatty', 'next', 'read', 'readline', >> 'readlines', 'reset', 'seek', 'tell', 'truncate'] > > Is it possible to have a direct access in-memory file that can be > written and read too? Read it again. You get readable-and-writable object by *not* assigning initial value in constructor. -- Jarek Zgoda http://jpa.berlios.de/ From __peter__ at web.de Mon Jul 31 14:05:16 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 31 Jul 2006 20:05:16 +0200 Subject: getting debug from urllib2 References: Message-ID: Ben Edwards wrote: > Have been experimenting with HTTP stuff in python 2.4 and am having a > problem getting debug info. If I use utllib.utlopen I get debug but if I > user utllib2 I do not. Below is the probram and the output I am > getting. > > Any insight? Use the source :-) urllib2.build_opener() accepts prebuilt handlers: import urllib2 url = 'http://www.mozillazine.org/atom.xml' request = urllib2.Request(url) opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)) feeddata = opener.open(request).read() Peter From vatamane at gmail.com Wed Jul 12 05:08:54 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 12 Jul 2006 02:08:54 -0700 Subject: Object Persistence Using a File System In-Reply-To: <1O%sg.3749$wZ.3322@trndny01> References: <1O%sg.3749$wZ.3322@trndny01> Message-ID: <1152695334.662414.218420@m73g2000cwd.googlegroups.com> Chris, Interesting concept. But why is there a need for a human readable object persistence that is x10 slower than pickle? In other words present a good use case with a rationale (i.e. your "criteria" that you mentioned). The only one I can think of so far is debugging. Also some objects are inherently not human readable (they are large, or just binary/array data for example), or you could simply end up having so many of them (10GB worth of disk space) that just due to the volume they will become not very readable and you would need some kind of a custom query mechanism (or find+grep) to search through your objects if you wanted to read/edit values in them. In your code comments I saw that another reason is resistance to corruption. I think that a database that is backed up regularly is probably a better solution. Besides, sometimes you want your failure to be dramatic (go down with a bang!) so it gets your attention and you can restore everything with a backup. Otherwise, with a tens of thousands of files, some of them might end up being corrupted before your next filesystem check gets to them, by then, the corruption could spread (your program would load it, perform computations, persist the wrong results and so on), and you wouldn't even notice it. Hope these comments help, Nick V. Chris Spencer wrote: > Before I get too carried away with something that's probably > unnecessary, please allow me to throw around some ideas. I've been > looking for a method of transparent, scalable, and human-readable object > persistence, and I've tried the standard lib's Shelve, Zope's ZODB, > Divmod's Axiom, and others. However, while they're all useful, none > satisfies all my criteria. So I started writing some toy code of my own: > http://paste.plone.org/5227 > > All my code currently does is transparently keep track of object changes > without requiring any special coding on part of the user, and a function > to convert an object to a file system hierarchy of folders and files. > Please, let me know what you think. > > Thanks, > Chris From cvanarsdall at mvista.com Tue Jul 25 12:55:39 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Tue, 25 Jul 2006 09:55:39 -0700 Subject: How to force a thread to stop In-Reply-To: <12qrr8nnk5uc0$.dlg@gelists.gmail.com> References: <44c21e51$0$10140$3a628fcd@textreader.nntp.hccnet.nl> <9bl4c2lsid4i67gnlc447her5aoau265t2@4ax.com> <1153831188.646392.185770@i42g2000cwa.googlegroups.com> <44C6471E.3080106@mvista.com> <12qrr8nnk5uc0$.dlg@gelists.gmail.com> Message-ID: <44C64D0B.8040503@mvista.com> Gerhard Fiedler wrote: > On 2006-07-25 13:30:22, Carl J. Van Arsdall wrote: > > >>> Running os.system() in multiple threads strikes me as kind of whacked. >>> Won't they all compete to read and write stdin/stdout simultaneously? >>> >>> >> Unfortunately this is due to the nature of the problem I am tasked with >> solving. I have a large computing farm, these os.system calls are often >> things like ssh that do work on locations remote from the initial python >> task. >> > > [...] > > >> Again, the problem I'm trying to solve doesn't work like this. I've been >> working on a framework to be run across a large number of distributed >> nodes (here's where you throw out the "duh, use a distributed >> technology" in my face). The thing is, I'm only writing the framework, >> the framework will work with modules, lots of them, which will be >> written by other people. Its going to be impossible to get people to >> write hundreds of modules that constantly check for status messages. >> > > Doesn't this sound like a case for using processes instead of threads? > Where you don't have control over the thread, you can use a process and get > the separation you need to be able to kill this task. > > Alternatively you could possibly provide a base class for the threads that > handles the things you need every thread to handle. They'd not have to > write it then; they'd not even have to know too much about it. > > Gerhard > > I'd be all for using processes but setting up communication between processes would be difficult wouldn't it? I mean, threads have shared memory so making sure all threads know the current system state is an easy thing. With processes wouldn't I have to setup some type of server/client design, where one process has the system state and then the other processes constantly probe the host when they need the current system state? -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From bdesth.quelquechose at free.quelquepart.fr Thu Jul 20 17:25:25 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 20 Jul 2006 23:25:25 +0200 Subject: [OT] Accessors in Python (getters and setters) In-Reply-To: <7cbvb2td29oo672rciqhu08rs7fml9qgjg@4ax.com> References: <1152975860.267475.166030@i42g2000cwa.googlegroups.com> <44bb8a7c$0$21801$626a54ce@news.free.fr> <1153213630.721413.95290@i42g2000cwa.googlegroups.com> <44bcea80$0$23108$626a54ce@news.free.fr> <1153244682.923384.71370@75g2000cwc.googlegroups.com> <44be63e0$0$14345$626a54ce@news.free.fr> <44bf6084$0$18895$626a54ce@news.free.fr> <7cbvb2td29oo672rciqhu08rs7fml9qgjg@4ax.com> Message-ID: <44bff328$0$30106$636a55ce@news.free.fr> Dennis Lee Bieber a ?crit : > On Thu, 20 Jul 2006 12:52:52 +0200, Bruno Desthuilliers > declaimed the following in comp.lang.python: > > >>Granted. Actually, it *was* a typo - but it happened to also make sens, >>so I decided it was not a typo !-) >> > > Ah... One of those "it's faster to just continue typing than to > break my flow and go backwards" moments. Almost... I noticed it while re-reading. > (and I forgot to include > the on my prior post) We won't hold it against you !-) From techxplorer at gmail.com Sun Jul 9 04:22:55 2006 From: techxplorer at gmail.com (Corey Wallis) Date: Sun, 9 Jul 2006 18:22:55 +1000 Subject: subprocess returncode always None Message-ID: <19fa495f0607090122m3f333eb2w3bcbb7376c5fa322@mail.gmail.com> Dear All, I'm currently working on a project that needs to collect the output of the JHOVE application. More information about the application is available at this website: http://hul.harvard.edu/jhove/ The application is written in Java and is executed by a shell script. There are occasions where this application may get stuck in an infinite loop. For this reason I've been trying to implement a simple class that I can use to execute the JHOVE application and if it doesn't complete in the required period of time to raise an exception and kill the process. The class is as follows, apologies for the odd line wrapping. class niceSubprocess(object): """ A class that implements a call to the subprocess method with a timeout - command, the command to execute - params, the parameters to pass to the application - timeout, the amount of time in seconds to wait """ def executeCommand(self, command, params, timeout): try: timeElapsed = 0 process = subprocess.Popen((command, params), stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, close_fds = True) while process.poll() == None and timeElapsed < timeout: print process.poll() #print process.stdout.read() timeElapsed = timeElapsed + 1 time.sleep(1) if process.poll() == None: # kill off the process, and don't be terribly nice about it os.kill(process.pid, signal.SIGKILL) raise timeoutError, timeout else: if process.stdout.read() == "": raise executeError, process.stderr.read() else: return process.stdout.read() except Exception, errorInfo: # pass the exception to the calling code raise errorInfo I'm running this on Linux and through the use of top can see the JAVA process start and complete. The problem I have is that process.poll() always returns None, even though the application has successfully ran and returned output. Can anyone shed some light on why the call to the shell script always returns None as a return code? With thanks. -Corey -- Corey Wallis RUBRIC Technical Officer University of Southern Queensland http://www.rubric.edu.au http://techxplorer.wordpress.com From chris at kateandchris.net Mon Jul 24 11:24:46 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Mon, 24 Jul 2006 11:24:46 -0400 Subject: list of indices In-Reply-To: <20060724151435.31874.qmail@web60322.mail.yahoo.com> References: <20060724151435.31874.qmail@web60322.mail.yahoo.com> Message-ID: <20060724152446.GC8234@kateandchris.net> On Mon, Jul 24, 2006 at 08:14:35AM -0700, Julien Ricard wrote: > hi, > > is there any method to get only some elements of a list from a list of > indices. Something like: > > indices=[0,3,6] > new_list=list[indices] new_list = [list[x] for x in indicies] > > which would create a new list containing 0th, 3rd and 6th elements from > the original list? I do this with a loop but I'd like to know if there is > a simpler way. > > thanks in advance > > Jul > -- > http://mail.python.org/mailman/listinfo/python-list From i at mindlace.net Wed Jul 5 18:37:21 2006 From: i at mindlace.net (emf) Date: Wed, 05 Jul 2006 18:37:21 -0400 Subject: [Mailman-Developers] Parsing and Rendering rfc2822 In-Reply-To: <1152111345.32574.18.camel@finch.boston.redhat.com> References: <44AAC503.9020901@mindlace.net> <1152111345.32574.18.camel@finch.boston.redhat.com> Message-ID: <44AC3F21.1020104@mindlace.net> John Dennis wrote: > It's not at all clear to me that mailman should be responsible for > archiving. While I am somewhat in agreement, the current situation is that archiving comes bundled with mailman and represents a significant weakness in its current web UI. Not doing anything about the web UI presented by the archives would, in my mind, represent a substantial failing. > Archiving and MLM (Mailing List Manager) functionality can be > orthogonal to each other. I can imagine - but have never used - a mailing list where access to past emails is 'orthogonal' to the use of the mailing list. It is hard for me to see the orthogonality except inasmuch as there's often a different user agent involved. > Archiving has a complex feature set if it's > done right, and it's complex to implement. Well, happily mailman is in the situation where archiving is not done right, and it seems like there's room for doing enough to a.) represent an improvement on the current situation and b.) lay a decent groundwork for plugging in different archivers or offering more of this complexity you speak of. > There are many items on Mailman's UI task list which need attention and can be done > independently of also trying to tackle the 800 pound gorilla known as > archiving. I am indeed taking this tack. However, even for things like the moderation approval page I need to parse & render emails. > I seem to > recall this is also Barry's preference who noted the existing pipermail > was only a stop-gap solution so there would be some default archiver, > but it was never the intention Mailman would have any extensive > archiving implementation. Like many stop gap solutions, this one is widely used, and represents the most visited portion of the "mailman web UI". At a bare minimum, the archive pages should provide decent navigation. The requirement for a default archiver remains, and the solution I propose is much more override friendly than the existing one; it wouldn't create hundreds of webpages out of the archives, just read out of the existing mbox files. > For what its worth I went looking for best of breed in open source > archivers about 6 months ago and what I came up with was a project > called "Lurker" (http://lurker.sourceforge.net) Thanks! I will look into this and see what I can glean from it. > IMHO let the archiving experts deal with archiving, let the MLM experts > (e.g. Mailman) deal with managing mailing lists. It is probably just a sign that I haven't explored the extant solutions sufficiently, but I have seen no sign that there are a variety of high-quality archiving solutions out there. What appears to me to be your main point - don't let archiving get in the way of delivering other UI functionality - is well taken; it is not at all at the top of my queue. ~ethan fremen From xah at xahlee.org Fri Jul 21 15:16:45 2006 From: xah at xahlee.org (Xah Lee) Date: 21 Jul 2006 12:16:45 -0700 Subject: On Computing and Its People In-Reply-To: <1153290273.890438.56440@i3g2000cwc.googlegroups.com> References: <1152721450.433219.269270@s13g2000cwa.googlegroups.com> <44B536EB.6020308@durchholz.org> <1152728150.911515.263640@s13g2000cwa.googlegroups.com> <1152757188.426777.216560@h48g2000cwc.googlegroups.com> <1152805549.184625.117520@s13g2000cwa.googlegroups.com> <1152996978.533372.223000@b28g2000cwb.googlegroups.com> <1153017376.379831.306420@35g2000cwc.googlegroups.com> <1153070922.854289.270130@75g2000cwc.googlegroups.com> <1153091295.520674.287230@i42g2000cwa.googlegroups.com> <1153151694.674061.133510@p79g2000cwp.googlegroups.com> <1153290273.890438.56440@i3g2000cwc.googlegroups.com> Message-ID: <1153509405.284210.48400@m79g2000cwm.googlegroups.com> Hi all, in the past years, i have written few hundreds of essays and tutorials on computing. Now, i've but a index page to this collection: http://xahlee.org/Periodic_dosage_dir/skami_prosa.html many of these, originated from online forum. The writing style is enticing and the content astute. also, as many of you may know, in the past month there's some controversy regarding me, that resulted in a small web hosting company kicking me out, giving the legal reason of _no reason_ as by the contract agreement (with a 30 days notice in advance). I feel there's some public obligation to give this update. More details is at http://xahlee.org/Periodic_dosage_dir/t2/harassment.html i have been busy in the past month so i haven't wrote anything new (regarding computing). Recently i started to do Java again, and will probably soon complete the other sections of this exposition: What are OOP's Jargons and Complexities http://xahlee.org/Periodic_dosage_dir/t2/oop.html Xah xah at xahlee.org ? http://xahlee.org/ From ray_usenet at yahoo.com Fri Jul 28 01:11:05 2006 From: ray_usenet at yahoo.com (Ray) Date: 27 Jul 2006 22:11:05 -0700 Subject: Why XP can not run Python after being setting the PATH? In-Reply-To: <1154063194.224649.110810@i42g2000cwa.googlegroups.com> References: <1154063194.224649.110810@i42g2000cwa.googlegroups.com> Message-ID: <1154063465.925458.227040@p79g2000cwp.googlegroups.com> By any chance the command window hasn't been restarted after you've changed the PATH? Strange that looks OK. If you do echo %PATH% what does it tell you, is Python there? Cheers Ray Daniel Mark wrote: > Hello all: > > I have set the PATH for Python as follows: > > My Computer->Properties->Advanced->Environment Variables->System > Variables->Path > > ...; C:\Program Files\Python24; > > Then I try to run python under command line > > C:\>python > > C:\>python.exe > > I got nothing:) > > It works iff I run as follows: > > C:\>"Program Files\Python24\python.exe" > Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] > on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> > > My question is how I can set the path so that the XP can run python > without the full path? > > > Thank you very much > -Daniel From no at spam.com Fri Jul 14 12:52:49 2006 From: no at spam.com (El Duderino) Date: Fri, 14 Jul 2006 09:52:49 -0700 Subject: time.clock() In-Reply-To: <44b7b53b$0$14990$88260bb3@free.teranews.com> References: <44b7b53b$0$14990$88260bb3@free.teranews.com> Message-ID: Tobiah wrote: > Am I barking up the wrong tree? I don't think so, time.clock() has always worked fine for me. You can also try time.time(). It is not as precise, but it might be sufficient for your needs. From simon at brunningonline.net Wed Jul 26 08:11:03 2006 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 26 Jul 2006 13:11:03 +0100 Subject: Problem with readlines() and uml In-Reply-To: <1153914937.623810.235150@i3g2000cwc.googlegroups.com> References: <1153909950.254371.126140@i3g2000cwc.googlegroups.com> <1153914937.623810.235150@i3g2000cwc.googlegroups.com> Message-ID: <8c7f10c60607260511q203aa599p93fb83bf4e5cdd5c@mail.gmail.com> On 26 Jul 2006 04:55:37 -0700, wscrsurfdude wrote: > Sorry it is so hot in here, I make mistakes, I meant it to be an xml > file. But still sthe same problem Check out elementtree - . -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From ptmcg at austin.rr._bogus_.com Sat Jul 1 19:19:58 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 01 Jul 2006 23:19:58 GMT Subject: really basic question regarding arrays/function output... References: Message-ID: "bruce" wrote in message news:mailman.7696.1151792861.27775.python-list at python.org... > hi... > > i have the following test python script.... i'm trying to figure out a > couple of things... > > 1st.. how can i write the output of the "label" to an array, and then how i > can select a given element of the array.. i know real basic.. > I think this is so basic, I'm not sure what you're talking about. One does not really "write to an array". In fact, Python's most natural data structure is a list, which has many array-like features (there is also an array module, but since you are asking basic questions, I'm trying to stick to basic Python). To append an item to a list, use append. To graft one list on to the end of another, use += or extend. To access the i'th element of a list use [i] (indices are zero-based). This is covered in far better detail in the Python tutorials. These fundamental data structures of Python (list, tuple, dict, set, str) are your fundamental tools when writing Python code, so you should read up on them. > 2nd.. where can i go to find methods of libxml2dom. i've been looking using > google, but can't seem to find a site pointing out the underlying methods, > which is kind of strange... > Try dir and help from the Python interactive command line. Assuming you have installed libxml2dom, do this: import libxml2dom dir(libxml2dom) help(libxml2dom) I see that this module also contains directories for tests and tools, these may provide you with some usage examples. (The docs directory *is* woefully brief...) -- Paul From bryanjugglercryptographer at yahoo.com Thu Jul 27 03:21:33 2006 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: 27 Jul 2006 00:21:33 -0700 Subject: How to force a thread to stop In-Reply-To: References: <44c21e51$0$10140$3a628fcd@textreader.nntp.hccnet.nl> <9bl4c2lsid4i67gnlc447her5aoau265t2@4ax.com> <1153831188.646392.185770@i42g2000cwa.googlegroups.com> <1153880729.687711.227570@h48g2000cwc.googlegroups.com> <1153942270.301732.99880@h48g2000cwc.googlegroups.com> Message-ID: <1153984893.730194.126140@h48g2000cwc.googlegroups.com> Carl J. Van Arsdall wrote: > bryanjugglercryptographer at yahoo.com wrote: > > Carl J. Van Arsdall wrote: > > > >> bryanjugglercryptographer at yahoo.com wrote: > >> > >>> Carl J. Van Arsdall wrote: > >>> > >>> I don't get what threading and Twisted would to do for > >>> you. The problem you actually have is that you sometimes > >>> need terminate these other process running other programs. > >>> Use spawn, fork/exec* or maybe one of the popens. > >>> > >>> > >> I have a strong need for shared memory space in a large distributed > >> environment. > >> > > > > Distributed shared memory is a tough trick; only a few systems simulate > > it. > > > Yea, this I understand, maybe I chose some poor words to describe what I > wanted. Ya' think? Looks like you have no particular need for shared memory, in your small distributed system. > I think this conversation is getting hairy and confusing so I'm > going to try and paint a better picture of what's going on. Maybe this > will help you understand exactly what's going on or at least what I'm > trying to do, because I feel like we're just running in circles. [...] So step out of the circles already. You don't have a Python thread problem. You don't have a process overhead problem. [...] > So, I have a distributed build system. [...] Not a trivial problem, but let's not pretend we're pushing the state of the art here. Looks like the system you inherited already does some things smartly: you have ssh set up so that a controller machine can launch various build steps on a few dozen worker machines. [...] > The threads invoke a series > of calls that look like > > os.system(ssh ) > > or for more complex operations they would just spawn a process that ran > another python script) > > os.system(ssh