Sending USB commands with Python
So I'm trying to get as low level as I can with my Dymo label printer, and this method described the PDF http://sites.dymo.com/Documents/LW450_Series_Technical_Reference.pdf seems to be it. I'm unfamiliar with dealing with the USB interface and would greatly appreciate it if someone could tell me how to send and receive these commands with Python. Perhaps if you were feeling generous and wanted to write a bit of sample code, sending the "Get Printer Status" command and receiving the response (page 17 of the PDF) would be perfect to get me on my way. Thanks, Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending USB commands with Python
On Wednesday, August 29, 2012 2:45:17 AM UTC-4, Tim Roberts wrote: > Which operating system are you using? If you are on Windows, then the > > operating system has already loaded a printer driver for this device. > > > The libusb or libusbx libraries can be used to talk to USB devices. There > > is a Python binding. On Windows, you still need to have a driver, but the > > libusbx instructions can help you find an install one. > I am on Windows and have installed a driver using libusb-win32. Using http://pyusb.sourceforge.net/docs/1.0/tutorial.html as a template, this is my code so far: import usb.core import usb.util dev = usb.core.find(idVendor=0x0922, idProduct=0x0021) # set the active configuration. With no arguments, the first # configuration will be the active one dev.set_configuration() # get an endpoint instance cfg = dev.get_active_configuration() interface_number = cfg[(0,0)].bInterfaceNumber alternate_settting = usb.control.get_interface(dev,interface_number) intf = usb.util.find_descriptor( cfg, bInterfaceNumber = interface_number, bAlternateSetting = 0 ) ep = usb.util.find_descriptor( intf, # match the first OUT endpoint custom_match = \ lambda e: \ usb.util.endpoint_direction(e.bEndpointAddress) == \ usb.util.ENDPOINT_OUT ) assert ep is not None I had to manually set bAlternateSetting to 0 for it to run and add dev to usb.control.get_interface(dev,interface_number). Trying to do the status thing mentioned before, in the interpreter I did: >>> ep.write('A') 2 And the manual says 2 is not a valid option... So something isn't adding up. -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending USB commands with Python
On Wednesday, August 29, 2012 4:09:49 PM UTC-4, Dennis Lee Bieber wrote: > > Don't the commands require an character? "\x1BA" (or >"\x1B\x41") > > OTOH, if the is issued behind the scenes, I'm not sure which esc char it is asking for, I don't think libusb is providing its own, and it seems like the one you suggested isn't what it wants either.. > ... and you do not need to issue some sort of read() > the "2" you are seeing is the "number of bytes written"; > > you need to issue a read request to retrieve the returned printer > > status. > You are correct about the 2 being the number of bytes written. However when I issue a read command I get: >>> ep.write('\x1BA') 4 >>> ep.read(1) Traceback (most recent call last): File "", line 1, in ep.read(1) File "C:\Python32\lib\site-packages\usb\core.py", line 301, in read return self.device.read(self.bEndpointAddress, size, self.interface, timeout) File "C:\Python32\lib\site-packages\usb\core.py", line 654, in read self.__get_timeout(timeout) File "C:\Python32\lib\site-packages\usb\backend\libusb01.py", line 483, in bulk_read timeout) File "C:\Python32\lib\site-packages\usb\backend\libusb01.py", line 568, in __read timeout File "C:\Python32\lib\site-packages\usb\backend\libusb01.py", line 384, in _check raise USBError(errmsg, ret) usb.core.USBError: [Errno None] b'libusb0-dll:err [_usb_setup_async] invalid endpoint 0x02\n' Avoiding the read command all together I should be able to write " E" and have it feed some paper, which it is not doing, so obviously there is more to uncover. That said I feel this endeavor has evolved and is no longer pertinent to the Python group so I will let you guys off the hook on this (although responses/suggestions are still welcome). Thanks for all your help! -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending USB commands with Python
On Wednesday, August 29, 2012 6:56:16 PM UTC-4, Dennis Lee Bieber wrote: > > BUT you do give a possible clue. Is the OP using a 3.x Python where > > strings are Unicode -- in which case the above may need to be explicitly > > declared as a "byte string" rather than text (unicode) string. > Huzzah! I am indeed using 3.x, and slapping on an .encode('utf-8') made my printer try to spit paper at me! Progress. Also, astute observation about the endpoint needing to be an input, with the following modification I get: >>> ep.write('\x1BA'.encode('utf-8')) 2 >>> ep = usb.util.find_descriptor( intf, custom_match = \ lambda e: \ usb.util.endpoint_direction(e.bEndpointAddress) == \ usb.util.ENDPOINT_IN ) >>> ep.read(1) array('B', [163]) >>> Anyone want to venture a guess on how I should interpret that? It seems the [163] is the byte data the manual is talking about, but why is there a 'B' there? If I put paper in it and try again I get: array('B', [3]) Thanks for all your help guys, just about ready to stared coding the fun part! -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending USB commands with Python
On Wednesday, August 29, 2012 10:07:54 PM UTC-4, Dennis Lee Bieber wrote: > On Wed, 29 Aug 2012 16:45:10 -0700 (PDT), "Adam W." > > I'm a tad curious if using the notation > > > > b'\x1bA' > > > > without the .encode() would work. > > > > My concern is that you may encounter some "string" of data for > > printing which the .encode() ends up /changing/ (don't UTF-8 strings use > > a high-bit to signal a multi-byte encoding of what had been a single > > character?). A pure byte string shouldn't have that problem. > Your notation does work, and I was just coming around to reevaluating the use of the encode because I am getting really odd results when trying to print lines. For example I set the byte length to 10 and sent this 500 times or so expecting to get a solid black bar: ep.write('\x16FF'.encode('utf-8')) But what I got was a weird stripped pattern... I feel like a lot of my commands are working by chance, I can't explain to myself why the A in \x1bA isn't being treated as part of the hex. This stuff always confuses me. > > > >>> ep = usb.util.find_descriptor( > > > intf, > > > custom_match = \ > > > lambda e: \ > > > usb.util.endpoint_direction(e.bEndpointAddress) == \ > > > usb.util.ENDPOINT_IN > > > ) > > > > Seems tedious to keep swapping -- does USB support bidirectional > > connections? > I assigned the input to ep2 to resolve the switching issue. -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending USB commands with Python
On Thursday, August 30, 2012 12:55:14 AM UTC-4, Dennis Lee Bieber wrote: > > How many bytes did it claim to send? > 11, which is what I expected. But I changed the byte value to 16 (because I was having trouble getting single digit hex values working in the command) and sent this command: >>> for x in range(0,500): ep.write(b'\x16\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF') it respond with 500 17's and prints a black bar! So it looks like whatever concern you had with using encode was coming to fruition. > > That's the easy one -- \x in a string introduces an 8-bit byte value > > -- so only two hex digits well be read. The "A" is interpreted as > > regular text. Interesting, so what if I only wanted to send 4bits as a hex value? Also can I somehow throw in some binary alongside of hex? At some point in my program I'm going to need to send some commands preferably in hex along with the binary image data. -- http://mail.python.org/mailman/listinfo/python-list
using urllib on a more complex site
I'm trying to write a simple script to scrape http://www.vudu.com/movies/#tag/99centOfTheDay/99c%20Rental%20of%20the%20day in order to send myself an email every day of the 99c movie of the day. However, using a simple command like (in Python 3.0): urllib.request.urlopen('http://www.vudu.com/movies/#tag/99centOfTheDay/99c%20Rental%20of%20the%20day').read() I don't get the all the source I need, its just the navigation buttons. Now I assume they are using some CSS/javascript witchcraft to load all the useful data later, so my question is how do I make urllib "wait" and grab that data as well? -- http://mail.python.org/mailman/listinfo/python-list
Re: using urllib on a more complex site
On Sunday, February 24, 2013 7:30:00 PM UTC-5, Dave Angel wrote: > On 02/24/2013 07:02 PM, Adam W. wrote: > > > I'm trying to write a simple script to scrape > > http://www.vudu.com/movies/#tag/99centOfTheDay/99c%20Rental%20of%20the%20day > > > > > > in order to send myself an email every day of the 99c movie of the day. > > > > > > However, using a simple command like (in Python 3.0): > > > urllib.request.urlopen('http://www.vudu.com/movies/#tag/99centOfTheDay/99c%20Rental%20of%20the%20day').read() > > > > > > I don't get the all the source I need, its just the navigation buttons. > > Now I assume they are using some CSS/javascript witchcraft to load all the > > useful data later, so my question is how do I make urllib "wait" and grab > > that data as well? > > > > > > > The CSS and the jpegs, and many other aspects of a web "page" are loaded > > explicitly, by the browser, when parsing the tags of the page you > > downloaded. There is no sooner or later. The website won't send the > > other files until you request them. > > > > For example, that site at the moment has one image (prob. jpeg) > > highlighted, > > > > http://images2.vudu.com/poster2/179186-m"; > > alt="Sex and the City: The Movie (Theatrical)"> > > > > if you want to look at that jpeg, you need to download the file url > > specified by the src attribute of that img element. > > > > Or perhaps you can just look at the 'alt' attribute, which is mainly > > there for browsers who don't happen to do graphics, for example, the > > ones for the blind. > > > > Naturally, there may be dozens of images on the page, and there's no > > guarantee that the website author is trying to make it easy for you. > > Why not check if there's a defined api for extracting the information > > you want? Check the site, or send a message to the webmaster. > > > > No guarantee that tomorrow, the information won't be buried in some > > javascript fragment. Again, if you want to see that, you might need to > > write a javascript interpreter. it could use any algorithm at all to > > build webpage information, and the encoding could change day by day, or > > hour by hour. > > > > -- > > DaveA The problem is, the image url you found is not returned in the data urllib grabs. To be clear, I was aware of what urllib is supposed to do (ie not download image data when loading a page), I've used it before many times, just never had to jump through hoops to get at the content I needed. I'll look into figuring out how to find XHR requests in Chrome, I didn't know what they called that after the fact loading, so now my searching will be more productive. -- http://mail.python.org/mailman/listinfo/python-list
Re: using urllib on a more complex site
On Sunday, February 24, 2013 7:27:54 PM UTC-5, Chris Rebert wrote: > On Sunday, February 24, 2013, Adam W. wrote: > I'm trying to write a simple script to scrape > http://www.vudu.com/movies/#tag/99centOfTheDay/99c%20Rental%20of%20the%20day > > > > > in order to send myself an email every day of the 99c movie of the day. > > > > However, using a simple command like (in Python 3.0): > > urllib.request.urlopen('http://www.vudu.com/movies/#tag/99centOfTheDay/99c%20Rental%20of%20the%20day').read() > > > > > I don't get the all the source I need, its just the navigation buttons. Now > I assume they are using some CSS/javascript witchcraft to load all the useful > data later, so my question is how do I make urllib "wait" and grab that data > as well? > > > > > > urllib isn't a web browser. It just requests the single (in this case, HTML) > file from the given URL. It does not parse the HTML (indeed, it doesn't care > what kind of file you're dealing with); therefore, it obviously does not > retrieve the other resources linked within the document (CSS, JS, images, > etc.) nor does it run any JavaScript. So, there's nothing to "wait" for; > urllib is already doing everything it was designed to do. > > > > Your best bet is to open the page in a web browser yourself and use the > developer tools/inspectors to watch what XHR requests the page's scripts are > making, find the one(s) that have the data you care about, and then make > those requests instead via urllib (or the `requests` 3rd-party lib, or > whatever). If the URL(s) vary, reverse-engineering the scheme used to > generate them will also be required. > > > > Alternatively, you could use something like Selenium, which let's you drive > an actual full web browser (e.g. Firefox) from Python. > > > Cheers, > Chris > > > -- > Cheers, > Chris > -- > http://rebertia.com Huzzah! Found it: http://apicache.vudu.com/api2/claimedAppId/myvudu/format/application*2Fjson/callback/DirectorSequentialCallback/_type/contentSearch/count/30/dimensionality/any/followup/ratingsSummaries/followup/totalCount/offset/0/tag/99centOfTheDay/type/program/type/season/type/episode/type/bundle Thanks for the tip about XHR's -- http://mail.python.org/mailman/listinfo/python-list
stmplib MIMEText charset weirdness
Can someone explain to me why I can't set the charset after the fact and still have it work. For example: >>> text = MIMEText('❤¥'.encode('utf-8'), 'html') >>> text.set_charset('utf-8') >>> text.as_string() Traceback (most recent call last): File "", line 1, in text.as_string() File "C:\Python32\lib\email\message.py", line 168, in as_string g.flatten(self, unixfrom=unixfrom) File "C:\Python32\lib\email\generator.py", line 91, in flatten self._write(msg) File "C:\Python32\lib\email\generator.py", line 137, in _write self._dispatch(msg) File "C:\Python32\lib\email\generator.py", line 163, in _dispatch meth(msg) File "C:\Python32\lib\email\generator.py", line 192, in _handle_text raise TypeError('string payload expected: %s' % type(payload)) TypeError: string payload expected: As opposed to: >>> text = MIMEText('❤¥'.encode('utf-8'), 'html', 'utf-8') >>> text.as_string() 'Content-Type: text/html; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: base64\n\n4p2kwqU=\n' Side question: >>> text = MIMEText('❤¥', 'html') >>> text.set_charset('utf-8') >>> text.as_string() 'MIME-Version: 1.0\nContent-Transfer-Encoding: 8bit\nContent-Type: text/html; charset="utf-8"\n\n❤¥' Why is it now 8-bit encoding? -- http://mail.python.org/mailman/listinfo/python-list
Re: stmplib MIMEText charset weirdness
On Tuesday, February 26, 2013 2:10:28 AM UTC-5, Steven D'Aprano wrote: > On Mon, 25 Feb 2013 20:00:24 -0800, Adam W. wrote: > > The documentation for MIMEText is rather terse, but it implies that the > > parameter given should be a string, not bytes: > > > > http://docs.python.org/3.2/library/email.mime#email.mime.text.MIMEText > > > > If I provide a string, it seems to work fine: > > Ok, working under the assumption you need to provide it a string, it still leaves the question why adding the header after the fact (to a string input) does not produce the same result as declaring the encoding type inline. > > > As opposed to: > > > > > >>>> text = MIMEText('❤¥'.encode('utf-8'), 'html', 'utf-8') > > >>>> text.as_string() > > > 'Content-Type: text/html; charset="utf-8"\nMIME-Version: > > > 1.0\nContent-Transfer-Encoding: base64\n\n4p2kwqU=\n' > > > > > > My wild guess is that it is an accident (possibly a bug) that the above > > works at all. I think it shouldn't; MIMEText is expecting a string, and > > you provide a bytes object. The documentation for the email package > > states: > > > > > > [quote] > > Here are the major differences between email version 5.0 and version 4: > > > > All operations are on unicode strings. Text inputs must be strings, > > text outputs are strings. Outputs are limited to the ASCII character set > > and so can be encoded to ASCII for transmission. Inputs are also limited > > to ASCII; this is an acknowledged limitation of email 5.0 and means it > > can only be used to parse email that is 7bit clean. > > [end quote] > > > > http://docs.python.org/3.2/library/email.html > I find this limitation hard to believe, why bother with encoding flags if it can only ever accept ASCII anyway? The reason this issue came up was because I was adding the header after like in my examples and it wasn't working, so I Google'd around and found this Stackoverflow: http://stackoverflow.com/questions/10295530/how-to-set-a-charset-in-email-using-smtplib-in-python-2-7 Which seemed to be doing exactly what I wanted, with the only difference is the inline deceleration of utf-8, with that change it started working as desired... -- http://mail.python.org/mailman/listinfo/python-list
Re: Do you feel bad because of the Python docs?
I think learning a language from the documentation is an unreasonable expectation and burden for the authors. Buy a book, take a class, they are designed to provide you with a path from start to finish in a sensible manner, the documentation in my opinion is supposed to be a reference and a refresher with an assumed level of basic fundamentals. I'm currently taking a class in ARM assembly, the notion that I should expect to plop the thousand+ page reference manual on my desk and just "get to it" is absurd. -- http://mail.python.org/mailman/listinfo/python-list
Who told str() to round my int()'s!!!
After a fair amount of troubleshooting of why my lists were coming back a handful of digits short, and the last digit rounded off, I determined the str() function was to blame: >>> foonum 0.0071299720384678782 >>> str(foonum) '0.00712997203847' >>> Why in the world does str() have any business rounding my numbers, and how do I get around this? -- http://mail.python.org/mailman/listinfo/python-list
Re: Who told str() to round my int()'s!!!
On Aug 11, 12:53 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > If `str()` would not round you would get very long numbers because of the > inaccuracies of floating point values. I know Python is lying when 0.1 > prints as 0.1, but do you really want to see > 0.1555111512312578270211815834045410156250 instead? I want str() to convert whatever I give it to a string and do nothing else. I will worry about long FP values in previous steps. I still find it very disturbing that str() is doing this AND it is undocumented in all of my books. > Use string formatting to tell the number of digits you want to see: > > In [16]: '%.56f' % 0.1 > Out[16]: '0.1555111512312578270211815834045410156250' The book I used to learn Python never introduced string formatting, I suppose I will have to use another and learn it if that is the only way... -- http://mail.python.org/mailman/listinfo/python-list
Easy question: More items in a For loop?
I'm trying to write a script that will parse IRC chat logs and color code them if it finds certain characters. I was able to make this work with one character, but to make it even more accurate I would like to use two identifying characters. Here is my code : import urllib2 response = urllib2.urlopen("http://192.168.1.100:81/%23pi.log";) tuna = response.readlines()[-10:] for j in tuna: for e,n in j: if e,n == "*"," ": j = "This: " + str.strip(j) + " will be Pink" elif e,n == "<","%": j = "This: " + str.strip(j) + " will be yellow" elif e,n == "<","@": j = "This: " + str.strip(j) + " will be dark pink" print(str.strip(j)) Obviously the "for e,n" business doesnt work, but I think it makes for some decent pseudocode for what I'm trying to accomplish. Here is some sample tuna: ['[7:55pm] My teachings goes back to the last iceage.\r\n', '[7:55pm] <%Zack> ahh now it does\r\n', '[7:55pm] <%Zack> ok\r\n', '[7:55pm] Or it is down just for you.\r\n', '[7:55pm] <@FC3> which one? that -12000 ice age or the one before\r\n', '[7:55pm] the earliest..\r\n', '[7:56pm] so.. 12000 quite long..\r \n', '[7:56pm] <@FC3> the one created by the meteor then\r\n', '[7:57pm] did not know that.. this is just a new teory I am folding.\r\n', '[7:57pm] * P0ke test test test\r\n'] -- http://mail.python.org/mailman/listinfo/python-list
Urllib keyerror, confused
I took this script: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/83208 And decided to try it out, it works when I first download a file, and when I try to resume a downloaded file, but if the file is already downloaded, and I expect to see the print "File already downloaded" message come up, I get a keyerror instead: Traceback (most recent call last): File "C:\Users\Adam\Desktop\ddd.py", line 26, in if int(webPage.headers['Content-Length']) == existSize: File "C:\Python25\lib\rfc822.py", line 384, in __getitem__ return self.dict[name.lower()] KeyError: 'content-length' Why did the key disappear? Here is the code I used (a little modified but functionally the same): import urllib, os class myURLOpener(urllib.FancyURLopener): """Create sub-class in order to overide error 206. This error means a partial file is being sent, which is ok in this case. Do nothing with this error. """ def http_error_206(self, url, fp, errcode, errmsg, headers, data=None): pass loop = 1 dlFile = "Okidata_Digital_B4600_Black_and_White_Laser_PrinterlacDetail.jpg" existSize = 0 myUrlclass = myURLOpener() if os.path.exists(dlFile): outputFile = open(dlFile,"ab") existSize = os.path.getsize(dlFile) #If the file exists, then only download the remainder myUrlclass.addheader("Range","bytes=%s-" % (existSize)) else: outputFile = open(dlFile,"wb") webPage = myUrlclass.open("http://s3-external-1.amazonaws.com/ wootsaleimages/%s" % dlFile) #If the file exists, but we already have the whole thing, don't download again print "flyby" if int(webPage.headers['Content-Length']) == existSize: loop = 0 print "File already downloaded" numBytes = 0.0 numBytes += existSize while loop: data = webPage.read(8192) if not data: break outputFile.write(data) numBytes += len(data) print (float(numBytes/int(webPage.headers['Content-Length']))*100) webPage.close() outputFile.close() for k,v in webPage.headers.items(): print k, "=",v print "copied", numBytes, "bytes from", webPage.url raw_input("Cat") -- http://mail.python.org/mailman/listinfo/python-list
Broke my IDLE!
I did a stupid thing and "wrote in" under the advance key bindings section, and after hitting apply I got a load of exceptions. Now my shell wont open and my IDEL wont start anymore I uninstalled and reinstalled Python with no luck, the whacked settings must be lingering around somewhere. Its python 2.5.1 and its on Vista if that helps. -- http://mail.python.org/mailman/listinfo/python-list
Re: Broke my IDLE!
Tried running IDEL from the command prompt to get this: Traceback (most recent call last): File "c:\Python25\Lib\idlelib\idle.pyw", line 21, in idlelib.PyShell.main() File "c:\Python25\lib\idlelib\PyShell.py", line 1404, in main shell = flist.open_shell() File "c:\Python25\lib\idlelib\PyShell.py", line 275, in open_shell self.pyshell = PyShell(self) File "c:\Python25\lib\idlelib\PyShell.py", line 813, in __init__ OutputWindow.__init__(self, flist, None, None) File "c:\Python25\lib\idlelib\OutputWindow.py", line 16, in __init__ EditorWindow.__init__(self, *args) File "c:\Python25\lib\idlelib\EditorWindow.py", line 125, in __init__ self.apply_bindings() File "c:\Python25\lib\idlelib\EditorWindow.py", line 900, in apply_bindings text.event_add(event, *keylist) File "c:\Python25\lib\idlelib\MultiCall.py", line 345, in event_add widget.event_add(self, virtual, seq) File "c:\Python25\lib\lib-tk\Tkinter.py", line 1357, in event_add self.tk.call(args) _tkinter.TclError: extra characters after detail in binding What do I need to edit and change? -- http://mail.python.org/mailman/listinfo/python-list
Re: Broke my IDLE!
I finally found away around it myself, I commented out line 1357 in lib \lib-tk\Tkinter.py that told it to call the settings, after I did that it fired right up, I went into the bindings and selected the default, closed out, uncommented that line, and I was back in buisness. On Feb 5, 2:27 pm, Chris <[EMAIL PROTECTED]> wrote: > On Feb 5, 7:05 pm, "Adam W." <[EMAIL PROTECTED]> wrote: > > > > > > > Tried running IDEL from the command prompt to get this: > > > Traceback (most recent call last): > > File "c:\Python25\Lib\idlelib\idle.pyw", line 21, in > > idlelib.PyShell.main() > > File "c:\Python25\lib\idlelib\PyShell.py", line 1404, in main > > shell = flist.open_shell() > > File "c:\Python25\lib\idlelib\PyShell.py", line 275, in open_shell > > self.pyshell = PyShell(self) > > File "c:\Python25\lib\idlelib\PyShell.py", line 813, in __init__ > > OutputWindow.__init__(self, flist, None, None) > > File "c:\Python25\lib\idlelib\OutputWindow.py", line 16, in __init__ > > EditorWindow.__init__(self, *args) > > File "c:\Python25\lib\idlelib\EditorWindow.py", line 125, in > > __init__ > > self.apply_bindings() > > File "c:\Python25\lib\idlelib\EditorWindow.py", line 900, in > > apply_bindings > > text.event_add(event, *keylist) > > File "c:\Python25\lib\idlelib\MultiCall.py", line 345, in event_add > > widget.event_add(self, virtual, seq) > > File "c:\Python25\lib\lib-tk\Tkinter.py", line 1357, in event_add > > self.tk.call(args) > > _tkinter.TclError: extra characters after detail in binding > > > What do I need to edit and change? > > Python25\Lib\idlelib\config-keys.def- Hide quoted text - > > - Show quoted text - -- http://mail.python.org/mailman/listinfo/python-list
Easy PIL question
I know there is an easy way to do this, but I can't figure it out, how do I get the color of a pixel? I used the ImageGrab method and I want to get the color of a specific pixel in that image. If you know how to make it only grab that pixel, that would also be helpful. Basically I'm trying to make a: if pixel == color: do_this() else: pass And have it do this as fast as my pc can handle (that is why only grabbing 1px would be helpful) -- http://mail.python.org/mailman/listinfo/python-list
How do I use SendInput in Python?
I'm at the last stage of my project and the only thing left to do is trigger a mouse click. I did some searching around for example code and stumped upon SendInput http://msdn2.microsoft.com/en-us/library/ms646310.aspx . However I was not able to find example code for python USING SendInput, and I have zero ability to make C work (or whatever that is written in). Can someone help me use SendInput in python, or point me to an alternative method? -- http://mail.python.org/mailman/listinfo/python-list
Dont know what my class is called...
I am using the xml.sax package, and I'm running into a little problem. When I use the parse(url, ContentHandler()) method, I don't know what parse() is naming the instance of ContentHandler. I have a sub-class of ContentHandler make a dictionary of what it parses, but the problem is I don't know the name of instance for me to get at it. The only way I have gotten at my dict is to declare it a global value, and I know that is not the right way to do it. I though I would be clever and put "print self" inside the __int__ method of the ContentHandler sub-class, in hopes it would display its given name, but it returned a rather useless: <__main__.FeedHandler instance at 0x02D8B5D0> So, any ideas on how to figure this out would be great. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dont know what my class is called...
On Feb 17, 6:12 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > It's a bit hard to get what you are after, but maybe this solves your > problem? > > handler = FeedHandler() > > parse(handler) > > print handler.my_instance_variable_of_choice > > The above assumes that my_instance_variable_of_choice is created + > filled within the handler of course. > > Diez Doh! I never thought to try that because I assumed parse needed to initialize it itself or else it would go haywire, probably stemming from my belief that classes are comprised mostly of smoke and mirrors and are never to be fully understood ;) Thanks for tip. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python seems to be ignoring my except clause...
On Feb 19, 8:49 am, Duncan Booth <[EMAIL PROTECTED]> wrote: > The example you posted isn't complete and while I can easily expand it to a > working example it will unfortunately be a working example. > > Try cutting it down yourself to a minimal self-contained example that you > can post. 99% of the time you'll find the problem when you do that and > avoid having to post at all. > > In this case, judging by the stack backtrace quoting the wrong line, I'd > guess you only just added the try..except and for some reason are still > executing the old code without the exception handling.- Hide quoted text - > > - Show quoted text - You hit the nail on the head with the old code, I found it funny myself it was quoting the try statement and not the code within. So I deleted my .pyc files and reran, same thing, but then I closed all open windows and reran it, and it recompiled the pyc and the code "worked". But now there is a new problem. I added a print statement to the except clause to make sure it was executing, and something funny happen, it printed 3 times and then spat this out: File "C:\Users\Adam\Desktop\XMLWorkspace.py", line 72, in parsexml parse(url, FeedHandlerInst) File "C:\Python25\lib\xml\sax\__init__.py", line 33, in parse parser.parse(source) File "C:\Python25\lib\xml\sax\expatreader.py", line 107, in parse xmlreader.IncrementalParser.parse(self, source) File "C:\Python25\lib\xml\sax\xmlreader.py", line 123, in parse self.feed(buffer) File "C:\Python25\lib\xml\sax\expatreader.py", line 211, in feed self._err_handler.fatalError(exc) File "C:\Python25\lib\xml\sax\handler.py", line 38, in fatalError raise exception SAXParseException: http://revision3.com/systm/feed/wmv-large/:78:83: undefined entity Huh? Why did it not raise this BEFORE it attempted to append the string, why did my print statment print 3 times before this error? I think I got past the hump I was hitting, and found a new one, 3 items later, I will investigate. But now I know I have to keep deleting my pyc files or else I will run into trouble. -- http://mail.python.org/mailman/listinfo/python-list
Python seems to be ignoring my except clause...
I am trying to handle a Unicode error but its acting like the except clause is not even there. Here is the offending code: def characters(self, string): if self.initem: try: self.data.append(string.encode()) except: self.data.append('No habla la Unicode') And the exception: File "C:\Users\Adam\Desktop\XMLWorkspace.py", line 65, in characters try: UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in position 83: ordinal not in range(128) Its got to be something really dumb I'm missing, this make no sence. -- http://mail.python.org/mailman/listinfo/python-list
Unicode characters, XML/RSS
So I wrote a little video podcast downloading script that checks a list of RSS feeds and downloads any new videos. Every once in a while it find a character that is out of the 128 range in the feed and my script blows up: Traceback (most recent call last): File "C:\Users\Adam\Desktop\Rev3 DL\Rev3.py", line 88, in mainloop() File "C:\Users\Adam\Desktop\Rev3 DL\Rev3.py", line 75, in mainloop update() File "C:\Users\Adam\Desktop\Rev3 DL\Rev3.py", line 69, in update couldhave = getshowlst(x[1],episodecnt) File "C:\Users\Adam\Desktop\Rev3 DL\Rev3.py", line 30, in getshowlst masterlist = XMLWorkspace.parsexml(url) File "C:\Users\Adam\Desktop\Rev3 DL\XMLWorkspace.py", line 54, in parsexml parse(url, FeedHandlerInst) File "C:\Python25\lib\xml\sax\__init__.py", line 33, in parse parser.parse(source) File "C:\Python25\lib\xml\sax\expatreader.py", line 107, in parse xmlreader.IncrementalParser.parse(self, source) File "C:\Python25\lib\xml\sax\xmlreader.py", line 123, in parse self.feed(buffer) File "C:\Python25\lib\xml\sax\expatreader.py", line 207, in feed self._parser.Parse(data, isFinal) File "C:\Users\Adam\Desktop\Rev3 DL\XMLWorkspace.py", line 51, in characters self.data.append(string) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 236: ordinal not in range(128) Now its my understanding that XML can contain upper Unicode characters as long as the encoding is specified, which it is (UTF-8). The feed validates every validator I've ran it through, every program I open it with seems to be ok with it, except my python script. Why? Here is the URL of the feed in question: http://revision3.com/winelibraryreserve/ My script is complaining of the fancy e in Mourvèdre At first glance I though it was the data.append(string) that was un accepting of the Unicode, but even if I put a return in the Character handler loop, it still breaks. What am I doing wrong? -- http://mail.python.org/mailman/listinfo/python-list
two's complement bytes
I'm dabbling with AVR's for a project I have and that means I have to use C (ageist my will). Because my AVR will be tethered to my laptop, I am writing most of my logic in python, in the hopes of using at little C as possible. In my quest I came across a need to pass a pair of sign extended two's complement bytes. After painfully reading the wikipedia article on what two's complement was, I then thought of how I would handle this in python. I don't really recall ever having to work in binary with python, so I really am clueless on what to do. I can feed python either two hex bytes or binary, but how do I convert it into an int, and more importantly how do I make sure it handles the sign properly? -- http://mail.python.org/mailman/listinfo/python-list
Re: two's complement bytes
On Aug 24, 12:23 am, castironpi <[EMAIL PROTECTED]> wrote: > Try this out. Does it come close to what you want? > > import struct > struct.pack( 'i', ~10 ) > ~struct.unpack( 'i', _ )[ 0 ] > > > > > > >>> import struct > >>> struct.pack( 'i', ~10 ) > '\xf5\xff\xff\xff' > >>> ~struct.unpack( 'i', _ )[ 0 ] > 10- Hide quoted text - > > - Show quoted text - Humm, so how do you use it :P Let me give you some examples and then you can run it through: 0b11001001 or 0xFC90 Should equal -880 0b0101 or 0x07D0 Should equal +2000 -- http://mail.python.org/mailman/listinfo/python-list
Re: two's complement bytes
On Aug 24, 1:11 am, castironpi <[EMAIL PROTECTED]> wrote: > On Aug 23, 11:52 pm, "Adam W." <[EMAIL PROTECTED]> wrote: > > > > > > > On Aug 24, 12:23 am, castironpi <[EMAIL PROTECTED]> wrote: > > > > Try this out. Does it come close to what you want? > > > > import struct > > > struct.pack( 'i', ~10 ) > > > ~struct.unpack( 'i', _ )[ 0 ] > > > > >>> import struct > > > >>> struct.pack( 'i', ~10 ) > > > '\xf5\xff\xff\xff' > > > >>> ~struct.unpack( 'i', _ )[ 0 ] > > > 10- Hide quoted text - > > > > - Show quoted text - > > > Humm, so how do you use it :P Let me give you some examples and then > > you can run it through: > > > 0b11001001 or 0xFC90 Should equal -880 > > 0b0101 or 0x07D0 Should equal +2000 > > In this case I look at: > > >>> struct.unpack( '>h', '\xfc\x90' )[0] > -880 > >>> struct.unpack( '>h', '\x07\xd0' )[0] > > 2000- Hide quoted text - > > - Show quoted text - Perfect, thank you! I will have to read up on struct to see how you did that. -- http://mail.python.org/mailman/listinfo/python-list
Classes and threading
I thought I knew how classes worked, but this code sample is making my second guess myself: import threading class nThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self,args): print self.name print self.args pants = nThread(args=('fruit'),name='charlie') pants.start() Traceback (most recent call last): File "C:\Users\Adam\Desktop\PyTiVo\task_master.py", line 13, in pants = nThread(args=('fruit'),name='charlie') TypeError: __init__() got an unexpected keyword argument 'args' Shouldn't __init__ still handle these (as per http://docs.python.org/library/threading.html#thread-objects ), even if its subclassed? I thought this was the whole idea of inheritance and overdriving. And sort of related, why does this crash IDLE GUI but not the command line?: import threading class nThread(threading.Thread): def run(self): print 2+2 pants = nThread() pants.start() -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes and threading
On May 19, 12:04 am, Erik Max Francis wrote: > Adam W. wrote: > > I thought I knew how classes worked, but this code sample is making my > > second guess myself: > > > import threading > > > class nThread(threading.Thread): > > def __init__(self): > > threading.Thread.__init__(self) > > > def run(self,args): > > print self.name > > print self.args > > > pants = nThread(args=('fruit'),name='charlie') > > pants.start() > > > Traceback (most recent call last): > > File "C:\Users\Adam\Desktop\PyTiVo\task_master.py", line 13, in > > > > pants = nThread(args=('fruit'),name='charlie') > > TypeError: __init__() got an unexpected keyword argument 'args' > > > Shouldn't __init__ still handle these (as per > >http://docs.python.org/library/threading.html#thread-objects), even > > if its subclassed? I thought this was the whole idea of inheritance > > and overdriving. > > You've overridden the __init__ method to _not_ take any arguments, and > explicitly call its parent constructor not passing anything. So it > shouldn't be a wonder that it won't accept any arguments. > > If you don't intend to override the constructor in the parent class, > simply don't define it. Hummm, so lets say I wanted it pass all the variables to the parent constructor, how would I do that? I wouldn't have to list every variable it could possible receive would I? This is like the opposite behavior I remember. When working with PyQt GUI classes, I swear I just sub classed the few things I wanted to change, and everything else would refer back to the parent... What I really just want to do is pass run() some args, which is what I assumed the default __init__'s args was for, but I give it args without sub classing __init__ and it has no idea what to do with them. I subclass __init__ to take args, and I break everything else? Is this really how this is supposed to work? -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes and threading
On May 19, 4:30 am, Gregory Ewing wrote: > Or if you do need to override it for some reason, you > need to accept the extra args and pass them on: > > class nThread(threading.Thread): > > def __init__(self, *args, **kwds): > threading.Thread.__init__(self, *args, **kwds) > # your other stuff here > Amazing, I've never seen *args used before outside of documentation, I didn't think it was "real" :P One problem down, still looking for why printing inside a thread crashes IDLE. -- http://mail.python.org/mailman/listinfo/python-list
urllib, can't seem to get form post right
I'm trying to scrape some historical data from NOAA's website, but I can't seem to feed it the right form values to get the data out of it. Heres the code: import urllib import urllib2 ## The source page http://www.erh.noaa.gov/bgm/climate/bgm.shtml url = 'http://www.erh.noaa.gov/bgm/climate/pick.php' values = {'month' : 'July', 'year' : '1988'} user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' headers = { 'User-Agent' : user_agent } data = urllib.urlencode(values) req = urllib2.Request(url, data, headers) response = urllib2.urlopen(req) the_page = response.read() print the_page -- http://mail.python.org/mailman/listinfo/python-list