Re: getting text from WinXP console
"Chris Maloof" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hello, > > Does anyone know how I can read the ASCII text from a console window > (from another application) in WinXP? It doesn't sound like a major > operation, but although I can find the window via pywin32, I haven't > been able to do anything with it. I'd really just like to get the > window text into a string. > > By "console window", I mean the sort of thing that comes up when you > run "command" (although this particular one is for the game NetHack). > > Thanks, > Chris Check out the Win32 Console functions on MSDN, such as AlocConsole(), ReadConsoleOutput(), GetStdHandle(). I don't see an easy way to get the screen buffer handle unless you are the process that owns the console, however. Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Challenge ahead [NEW] for riddle lovers
"pythonchallenge" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > For the riddles' lovers among you, you are most invited to take part > in the Python Challenge, the first python programming riddle on the net. > > You are invited to take part in it at: > http://www.pythonchallenge.com Excellent puzzles! For others like this see http://www.osix.net. I love these things :^) -- http://mail.python.org/mailman/listinfo/python-list
Re: Why can not catch the inner exception
"人言落日是天涯,望极天涯不见家" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Please see the follow code, I can not catch the exception " IOError" raised from shutil.copyfile() , why? try: if (DEST_TYPE & TYPE_FTP): fn = oname ftpc.UploadFile(f, fn) else: fn = os.path.join(dst, oname) shutil.copyfile(f, fn) other code except [IOError, FtpcException],why: num = 0 print >>sys.stderr, "can not copy '%s' to '%s': %s"%(f, fn, why) ERR_NUM += 1 I must do like this: try: if (DEST_TYPE & TYPE_FTP): fn = oname ftpc.UploadFile(f, fn) else: fn = os.path.join(dst, oname) try: shutil.copyfile(f, fn) except IOError: other code except [IOError, FtpcException],why: num = 0 print >>sys.stderr, "can not copy '%s' to '%s': %s"%(f, fn, why) ERR_NUM += 1 Thanks! 你好, Use a tuple (IOError,FtpcException) instead of a list in the except statement and it works. --马克 -- http://mail.python.org/mailman/listinfo/python-list
Re: passing arguments to tcpserver classes
"Eric Spaulding" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Is there an easy way to pass arguments to a handler class that is used by > the standard TCPServer? > > normally --> srvr =SocketServer.TCPServer(('',port_num), TCPHandlerClass) > > I'd like to be able to: srvr =SocketServer.TCPServer(('',port_num), > TCPHandlerClass, (arg1,arg2)) > > And have arg1, arg2 available via TCPHandlerClass.__init__ or some other > way. > > Where TCPHandlerClass: > > class TCPHandlerClass(SocketServer.StreamRequestHandler): >def handle(self): > #handle stream events here# > > > Thanks for any advice. > In the handler class, self.server refers to the server object, so subclass the server and override __init__ to take any additional server parameters and store them as instance variables. import SocketServer class MyServer(SocketServer.ThreadingTCPServer): def __init__(self, server_address, RequestHandlerClass,arg1,arg2): SocketServer.ThreadingTCPServer.__init__(self,server_address,RequestHandlerClass) self.arg1 = arg1 self.arg2 = arg2 class MyHandler(SocketServer.StreamRequestHandler): def handle(self): print self.server.arg1 print self.server.arg2 if __name__ == '__main__': srv = MyServer(('',5000),MyHandler,123,456) srv.serve_forever() --Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: str() and repr() question
"adima" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hi All! > Sorry, my English isnt good, but get a try to describe my problem. > > Today we wrote next script: > > import os, glob, time, string > files_to_test = ( "J:\\BWNEW\\!Unerase\\test.test", "L:\\Temp\Nick\ > \test.test", "F:\\TRANSIT\\nick\\test.test") > outfile="c:\\temp\\statistic" > > > def DoTestTime(file): > StartTime = time.time() > filehandle = open(file) > alllines = filehandle.read() > filehandle.close() > > FileSize = os.path.getsize(file) > EndTime = time.time() > return time.ctime() , "\tDisk\t" , file[:3] , "\tfile size (bytes) = > \t" , FileSize , "\taccess time =\t" , EndTime - StartTime > > > if __name__ == "__main__": > out = open(outfile, 'w') > for EachFile in files_to_test: > str = DoTestTime(EachFile) > print type(str) > for s in str: > print s > out.write(str(s)) > out.close() > > When I executed it, the output was > C:\test\py>File_Stat.py > Thu Apr 26 12:08:33 2007 > > Traceback (most recent call last): > File "C:\test\py\File_Stat.py", line 26, in ? >out.write(str(s)) > TypeError: 'tuple' object is not callable > > When I replace "str" with "repr" in out.write(str(s)), script executed > normally. > > Where is the problem here? > Thanks in advance. > You might want to check out pychecker.py. Its output: Processing Script1... Warnings... Script1.py:1: Imported module (glob) not used Script1.py:1: Imported module (string) not used Script1.py:9: Local variable (alllines) not used Script1.py:20: (str) shadows builtin You've replaced the built-in function str with the return value of DoTestTime(). -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Threaded Design Question
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hi all! I'm implementing one of my first multithreaded apps, and have > gotten to a point where I think I'm going off track from a standard > idiom. Wondering if anyone can point me in the right direction. > > The script will run as a daemon and watch a given directory for new > files. Once it determines that a file has finished moving into the > watch folder, it will kick off a process on one of the files. Several > of these could be running at any given time up to a max number of > threads. > > Here's how I have it designed so far. The main thread starts a > Watch(threading.Thread) class that loops and searches a directory for > files. It has been passed a Queue.Queue() object (watch_queue), and > as it finds new files in the watch folder, it adds the file name to > the queue. > > The main thread then grabs an item off the watch_queue, and kicks off > processing on that file using another class Worker(threading.thread). > > My problem is with communicating between the threads as to which files > are currently processing, or are already present in the watch_queue so > that the Watch thread does not continuously add unneeded files to the > watch_queue to be processed. For example...Watch() finds a file to be > processed and adds it to the queue. The main thread sees the file on > the queue and pops it off and begins processing. Now the file has > been removed from the watch_queue, and Watch() thread has no way of > knowing that the other Worker() thread is processing it, and shouldn't > pick it up again. So it will see the file as new and add it to the > queue again. PS.. The file is deleted from the watch folder after it > has finished processing, so that's how i'll know which files to > process in the long term. > > I made definite progress by creating two queues...watch_queue and > processing_queue, and then used lists within the classes to store the > state of which files are processing/watched. > > I think I could pull it off, but it has got very confusing quickly, > trying to keep each thread's list and the queue always in sync with > one another. The easiset solution I can see is if my threads could > read an item from the queue without removing it from the queue and > only remove it when I tell it to. Then the Watch() thread could then > just follow what items are on the watch_queue to know what files to > add, and then the Worker() thread could intentionally remove the item > from the watch_queue once it has finished processing it. > > Now that I'm writing this out, I see a solution by over-riding or > wrapping Queue.Queue().get() to give me the behavior I mention above. > > I've noticed .join() and .task_done(), but I'm not sure of how to use > them properly. Any suggestions would be greatly appreciated. > > ~Sean > Just rename the file. We've used that technique in a similar application at my work for years where a service looks for files of a particular extension to appear in a directory. When the service sees a file, in renames it to a different extension and spins off a thread to process the contents. -Mark T. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python equivalent of Perl's $/
"John K Masters" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] >I am currently working my way through Jeffrey Friedl's book Mastering > Regular Expressions. Great book apart from the fact it uses Perl for the > examples. > > One particular expression that interests me is '$/ = ".\n"' which, > rather than splitting a file into lines, splits on a period-newline > boundary. Combined with Perl's 'while (<>)' construct this seems a great > way to process the files I am interested in. > > Without wishing to start a flame war, is there a way to do this in Python? > > Regards, John > -- > War is God's way of teaching Americans geography > Ambrose Bierce (1842 - 1914) >>> 'test\ntest2.\ntest3\ntest4.\ntest5'.split('.\n') ['test\ntest2', 'test3\ntest4', 'test5'] -Mark T. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3000 idea: reversing the order of chained assignments
"Marcin Ciura" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Given > class Node(object): > pass > > node = Node() > nextnode = Node() > > I tried to refactor the following piece of code > node.next = nextnode > node = nextnode You have an error above. The first node's "next" points to nextnode, then node is reassigned to point to nextnode, losing the original node! The refactoring below is doing the same thing. It is, however, evaluating right-to-left as you want. nextnode is place in node.next and placed in node, also losing the original value of node. -Mark T. > > as > node = node.next = nextnode > > only to discover that Python performs chained assignments > backwards compared to other languages, i.e. left-to-right > instead of right-to-left. From the user's perspective, > I can't think of any reasonable argument for keeping it > this way in Python 3000. What is your opinion? > Marcin -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3000 idea: reversing the order of chained assignments
"Alex Martelli" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > John Nagle <[EMAIL PROTECTED]> wrote: > >> Marcin Ciura wrote: >> >> > Neither would I. I must have expressed myself not clearly enough. >> > Currently >> > x = y = z >> > is roughly equivalent to >> > x = z >> > y = z >> > I propose to change it to >> > y = z >> > x = z >> >> Actually, it is equivalent to >> >> y = z >> x = y > > Not really: > >>>> class chatty(object): > ... def __init__(self): self.__dict__['__hide'] = {} > ... def __setattr__(self, name, value): > ... print 'sa', name, value > ... self.__dict__['__hide'][name] = value > ... def __getattr__(self, name): > ... print 'ga', name > ... return self.__dict__['__hide'].get(name) > ... >>>> c = chatty() >>>> x = c.zop = 23 > sa zop 23 >>>> > > As you can see, there is no read-access to c.zop, which plays the role > of y there. > > > Alex This is interesting: >>> class Test(object): ... def __getattribute__(self,n): ... print 'reading',n ... return object.__getattribute__(self,n) ... def __setattr__(self,n,v): ... print 'writing',n,v ... return object.__setattr__(self,n,v) ... >>> x=Test() >>> x.a=1; x.b=2; x.c=3 writing a 1 writing b 2 writing c 3 >>> x.a=x.b=x.c reading c writing a 3 writing b 3 >>> I wouldn't have expected "a" to be assigned first in a right-to-left parsing order. The result is the same in any case. -Mark T. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python automatic testing: mocking an imported module?
"Silfheed" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Heyas > > So we have the following situation: we have a testee.py that we want > to automatically test out and verifiy that it is worthy of being > deployed. We want our tester.py to test the code for testee.py > without changing the code for testee.py. testee.py has a module in it > that we want to mock in some tests and in others use the real module. > > /foo.py: (real module) > class bar: > def __init__(self): >"I am real" > > /foo_fake/foo.py: (fake module) > class bar: > def ___init__(self): >"I am a banana" > > /testee.py: > import foo > foo.bar() > > /tester.py: > from foo_fake import foo > foo.bar()# prints I am a banana > testee.py # also prints I am a banana > import foo > foo.bar() # prints I am real > testee.py # also prints I am real > > > This isnt working as we would like, does anyone have any tips on how > to get something like this working? > If you add the foo_fake directory to the front of sys.path, "import foo" will import the foo.py in foo_fake directory before the one in the local directory. # unverified code import sys sys.path.append(0,'foo_fake') # add foo_fake to front of path import foo foo.bar() execfile('testee.py') sys.path.pop(0) # remove foo_fake reload(foo) foo.bar() execfile('testee.py') -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: elementtree question
"Gabriel Genellina" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > En Fri, 21 Sep 2007 11:49:53 -0300, Tim Arnold <[EMAIL PROTECTED]> > escribi�: > >> Hi, I'm using elementtree and elementtidy to work with some HTML files. >> For >> some of these files I need to enclose the body content in a new div tag, >> like this: >> >> >>original contents... >> >> >> >> I figure there must be a way to do it by creating a 'div' SubElement to >> the >> 'body' tag and somehow copying the rest of the tree under that >> SubElement, >> but it's beyond my comprehension. > > import xml.etree.ElementTree as ET > source = """Test > original contents... 2&3 some text > Another paragraph > """ > tree = ET.XML(source) > body = tree.find("body") > newdiv = ET.Element('div', {'class':'remapped'}) > newdiv.append(body) > bodyidx = tree.getchildren().index(body) > tree[bodyidx]=newdiv > ET.dump(tree) > > -- > Gabriel Genellina > The above wraps the body element, not the contents of the body element. I'm no ElementTree expert, but this seems to work: import xml.etree.ElementTree as ET source = """Test original contents... 2&3 some text Another paragraph """ tree = ET.XML(source) body = tree.find("body") newdiv = ET.Element('div', {'class':'remapped'}) for e in body.getchildren(): newdiv.append(e) newdiv.text = body.text newdiv.tail = body.tail body.clear() body.append(newdiv) ET.dump(tree) Result: Test original contents... 2&3 some text Another paragraph -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: slice with negative stride
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I'm really confused about results of slices with negative strides. For > example > >>>mystr = 'my string' > > I would have then thought of the contents of mystr as: > > indices0 1 2 3 4 5 6 7 8 > contentm y s t r i n g > > with mystr[:3] = 'my ' > > Can someone explain to me how mystr[:3:-1] = 'gnirt'? > > I was expecting the result to be mystr[:3] reversed (' ym') i.e slice > then reverse or even the first 3 elements of the string after being > reversed ('gni') i.e. reverse then slice. > > Thanks > > Andy > When the step is negative, a missing start is interpreted as the end of the string. A slice always includes the start index character through, but not including, the end index character. In your example, the end index character was mystr[3], so you received the end of the string ('g') down to but not including 's', which is 'gnirt'. To see the indices a slice is using, use the slice object's indices method. Given the length of a string, it returns the exact start,stop,step indices used: >>> mystr='my string' >>> s=slice(None,3,-1) >>> s.indices(len(mystr)) # start is the end of the string if step is >>> negative (8, 3, -1) >>> mystr[8],mystr[3] ('g', 's') >>> mystr[8:3:-1] 'gnirt' >>> s=slice(None,3,1) >>> s.indices(len(mystr)) # start is the beginning of the string if step is >>> positive (0, 3, 1) >>> mystr[0],mystr[3] ('m', 's') >>> mystr[0:3:1] 'my ' -Mark T -- http://mail.python.org/mailman/listinfo/python-list
Re: View XMLRPC Requests/Responses?
"xkenneth" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hi, > >I'm working on developing an XML-RPC interface from LabVIEW to > python and I would really like to see how python is forming it's XML- > RPC requests/responses. Is there any way I can force these to a log or > print them to the screen? Thanks. > > Regards, > Ken > www.wireshark.org -Mark T. -- http://mail.python.org/mailman/listinfo/python-list
Re: File Closing Problem in 2.3 and 2.4, Not in 2.5 (Final report)
"Gabriel Genellina" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > At Tuesday 9/1/2007 20:31, Carroll, Barry wrote: > >>I've spent about a day investigating our "too many open files" error. I >>found the following: >> >> 1. Windows XP allows a Python 2.5 script to open 509 concurrent >>files. > > And do you actually need so many open files simultaneously? > Try to close them explicitely when you finish working on them - do not > rely on GC for closing files. This has *always* been the recomended > practice (except maybe, inside a short script that finishes quickly). > On Python 2.5 you can use the new `with` statement. > > > -- > Gabriel Genellina > Softlab SRL After a quick scan of this thread, I didn't see the actual source for your call to the file's close(). Is it perhaps "file.close" and not "file.close()"? Forgotten parentheses won't give an error and won't close the file. >>> f=file('blah.txt','wt') >>> f >>> f.close >>> f >>> f.close() >>> f >>> -Mark Tolonen -- http://mail.python.org/mailman/listinfo/python-list
Re: how to fill many data strings from socket.recvfrom()
"lgwe" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] >I want to receive 200 udp datagrams. Each into a new data string. > But I dont know how to do that, this is wrong: > > import socket > s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) > s.bind(("",port)) > i = 0 > while i<200: >data[i],addr = s.recvfrom(1024) >i = +1 > > data[i] is illegal. > > Any suggestion welcome! > import socket s=socket(socket.AF_INET,socket.SOCK_DGRAM) s.bind(('',5000)) data=[] for i in range(200): tmp,addr = s.recvfrom(1024) data.append(tmp) -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Next float?
"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Is there a simple, elegant way in Python to get the next float from a > given one? By "next float", I mean given a float x, I want the smallest > float larger than x. > > Bonus points if I can go in either direction (i.e. the "previous float" > as well as the next). > > Note to maths pedants: I am aware that there is no "next real number", > but floats are not reals. > > > -- > Steven Here's some functions to get the binary representation of a float. Then just manipulate the bits (an exercise for the reader): import struct def f2b(f): return struct.unpack('I',struct.pack('f',f))[0] def b2f(b): return struct.unpack('f',struct.pack('I',b))[0] >>> f2b(1.0) 1065353216 >>> hex(f2b(1.0)) '0x3f80' >>> b2f(0x3f80) 1.0 >>> b2f(0x3f81) 1.001192092896 >>> b2f(0x3f7f) 0.9994039535522 -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Hexadecimal list conversion
"Gabriel Genellina" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > En Thu, 20 Dec 2007 09:30:14 -0300, Neil Webster <[EMAIL PROTECTED]> > escribi�: > >> I have a list which is a line from a file: >> ['\x003\x008\x001\x004\x007\x005\x00.\x005\x000\x002\x005\x009\x009\x00', >> '\x002\x001\x003\x006\x002\x002\x00.\x001\x007\x004\x002\x008\x002\x00'] >> >> This should be in the format: >> ['381475.502599', '213622.174282'] >> >> I've tried a few options using replace (replacing "\x00" with "") and >> trying to convert from hexademical to decimal. > > The replace works: > > py> for item in L: > ... print item.replace('\x00','') > ... > 381475.502599 > 213622.174282 > > If you got that from a file, I bet you read it using the wrong encoding. > Try opening the file using codecs.open("filename", "rb", > encoding="utf-16-be") instead of plain open. When your read it, you'll get > unicode objects instead of strings, but with the right contents. If you > wish you can convert to strings using > line_read.encode(your_system_encoding); if all your data is numeric the > encoding used is irrelevant and can be omited. > > -- > Gabriel Genellina > There is an odd number of bytes in each string. Each begins and ends with \x00, so it doesn't look like utf-16-be. But replace works: >>> L=['\x003\x008\x001\x004\x007\x005\x00.\x005\x000\x002\x005\x009\x009\x00','\x002\x001\x003\x006\x002\x002\x00.\x001\x007\x004\x002\x008\x002\x00'] >>> [s.replace('\x00','') for s in L] ['381475.502599', '213622.174282'] -Mark Tolonen -- http://mail.python.org/mailman/listinfo/python-list