PyAutoGUI Script no longer working - "windll.gdi32.getpixel failed" - python

My script has been working fine for the past month or so (up til yesterday), but as of today when I run it, it returns the following:
Traceback (most recent call last):
File "C:\...\main.py", line 39, in <module>
pxFish = pyautogui.pixelMatchesColor(int(fishLocX[i]), int(fishLocY[i]), (76, 76, 76), tolerance=50)
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\pyscreeze\__init__.py", line 589, in pixelMatchesColor
pix = pixel(x, y)
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\pyscreeze\__init__.py", line 610, in pixel
raise WindowsError("windll.gdi32.GetPixel failed : return {}".format(color))
OSError: windll.gdi32.GetPixel failed : return -1
I haven't made any changes to the code or to my system, so I have no idea why it'd just suddenly stop working. Help would be appreciated.
Also, somewhat bizarrely, my other functionally identical script still works (i.e. uses pixelMatchesColor, pyautogui click etc.).
Cheers.
Edit: It started working again out of nowhere. Didn't do anything at all. Epic. Very cool.

Related

PyAutoGui module not working in PyCharm IDE

I am trying to use PyAutoGui's locateCenterOnScreen() function in PyCharm. However, it always throws an error even though it works in VS Code. I am running on an M1 Macbook Air w/ macOS Monterey. I have PyAutoGui version 0.9.53 installed. Does anyone know why it does this?
Traceback (most recent call last):
File "/Users/username/Desktop/Files/Programming/Projects/Auto Mining Tool/main.py", line 3, in <module>
x, y = pyautogui.locateCenterOnScreen('image.png')
File "/Users/username/Library/Python/3.8/lib/python/site-packages/pyautogui/__init__.py", line 175, in wrapper
return wrappedFunction(*args, **kwargs)
File "/Users/username/Library/Python/3.8/lib/python/site-packages/pyautogui/__init__.py", line 207, in locateCenterOnScreen
return pyscreeze.locateCenterOnScreen(*args, **kwargs)
File "/Users/andrewwalker/Library/Python/3.8/lib/python/site-packages/pyscreeze/__init__.py", line 413, in locateCenterOnScreen
coords = locateOnScreen(image, **kwargs)
File "/Users/andrewwalker/Library/Python/3.8/lib/python/site-packages/pyscreeze/__init__.py", line 372, in locateOnScreen
screenshotIm = screenshot(region=None) # the locateAll() function must handle cropping to return accurate coordinates, so don't pass a region here.
File "/Users/andrewwalker/Library/Python/3.8/lib/python/site-packages/pyscreeze/__init__.py", line 477, in _screenshot_osx
im = Image.open(tmpFilename)
NameError: name 'Image' is not defined
I can tell you why, but I'm not smart enough to know how to fix it.
The reason seems to stem from updates. I just ran into this problem today myself, I typically build projects and then never update modules etc.
Did you update modules prior to this happening?
It seems they've changed function names, and other modules that were built by other people either were not updated, or have import errors, resulting in pyscreeze and pyautogui not playing nice together.

pyautogui.pixel works perfectly for a while, and then randomly stops working and gives errors

I have been implementing pyautogui.pixel in many forms of code, I will get a normal desirable output for a random short while, and at some point, the function will stop working, and I will get error messages.
Simple example code:
while True:
print(pyautogui.pixel(1766, 1539))
Output:
(30, 30, 30)
The eventual error message:
Traceback (most recent call last):
File "c:\Users\zyoli\Desktop\scrap_bot\gathering.py", line 14, in <module>
print(pyautogui.pixel(1766, 1539))
File "C:\Users\zyoli\AppData\Local\Programs\Python\Python39\lib\site-packages\pyscreeze\__init__.py", line 584, in pixel
return (r, g, b)
File "C:\Users\zyoli\AppData\Local\Programs\Python\Python39\lib\contextlib.py", line 124, in __exit__
next(self.gen)
File "C:\Users\zyoli\AppData\Local\Programs\Python\Python39\lib\site-packages\pyscreeze\__init__.py", line 113, in __win32_openDC
raise WindowsError("windll.user32.ReleaseDC failed : return 0")
OSError: windll.user32.ReleaseDC failed : return 0
I suppose you are switching some windows/app while running the code. Maybe because of the animation(while opening a new window), Pyautogui raises an error. get_pixel from the screen is slow. Maybe this thread can help you:
Quickly getting the color of some pixels on the screen in Python on Windows 7

Using VS Code to debug python files. Exception thrown on breakpoint and breakpoint is ignored

Tried with multiple different python files. Every time I try to use the debugger in vs code and set breakpoints the breakpoint gets ignored and exception gets raised and the script continues on. I've been googling and tinkering for over 2 hours and can't seem to figure out what's going on here. Tried rebooting PC, running vs code as admin, uninstall/reinstall the python extension for vs code. Tried to dig into the files mentioned in the traceback and pinpointed the function that seems to be raising the exception but I can't figure out where it's being called from or why it's raising the exception. I'm still new-ish to Python. Debugging works properly on my laptop but for whatever reason my desktop is having this issue.
Traceback (most recent call last):
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 529, in _original_file_to_client
return cache[filename]
KeyError: 'c:\\users\\joel\\local settings\\application data\\programs\\python\\python37-32\\lib\\runpy.py'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_comm.py", line 330, in _on_run
self.process_net_command_json(self.py_db, json_contents)
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_process_net_command_json.py", line 190, in process_net_command_json
cmd = on_request(py_db, request)
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_process_net_command_json.py", line 771, in on_stacktrace_request
self.api.request_stack(py_db, request.seq, thread_id, fmt=fmt, start_frame=start_frame, levels=levels)
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_api.py", line 214, in request_stack
if internal_get_thread_stack.can_be_executed_by(get_current_thread_id(threading.current_thread())):
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_comm.py", line 661, in can_be_executed_by
py_db, self.seq, self.thread_id, frame, self._fmt, must_be_suspended=not timed_out, start_frame=self._start_frame, levels=self._levels)
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_net_command_factory_json.py", line 213, in make_get_thread_stack_message
py_db, frames_list
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_net_command_factory_xml.py", line 175, in _iter_visible_frames_info
new_filename_in_utf8, applied_mapping = pydevd_file_utils.norm_file_to_client(filename_in_utf8)
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 531, in _original_file_to_client
translated = _path_to_expected_str(get_path_with_real_case(_AbsFile(filename)))
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 221, in _get_path_with_real_case
return _resolve_listing(drive, iter(parts))
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 184, in _resolve_listing
dir_contents = cache[resolved_lower] = os.listdir(resolved)
PermissionError: [WinError 5] Access is denied: 'C:\\Users\\Joel\\Local Settings'
So I get this traceback every time a breakpoint is hit. Taking a peek at the "_original_file_to_client" function in "pydevd_file_utils.py" we get this:
def _original_file_to_client(filename, cache={}):
try:
return cache[filename]
except KeyError:
translated = _path_to_expected_str(get_path_with_real_case(_AbsFile(filename)))
cache[filename] = (translated, False)
return cache[filename]
I wasn't able to figure out where this function was being called from or what the expected output was supposed to be. Any help with this would be greatly appreciated!
Edit: Forgot to mention I'm using Windows 10 if it wasn't obvious from the trace
This is a similar question. The spaces in the filename cause this problem:
"Local Settings", "application data"

Python speech recognition 'module' object has no attribute 'VARIANT'

I'm trying to get started using speech recognition in python. First I tried PySpeech (https://code.google.com/p/pyspeech/) using this code:
def listen():
while 1:
said = speech.input()
print said
if said == "off":
break
and got the following traceback:
Traceback (most recent call last):
File "C:/Users/REDACTED/Documents/Python Projects/listen.py", line 59, in <module> useful.listen()
File "C:/Users/REDACTED/Documents/Python Projects/listen.py", line 48, in listen
said = speech.input()
File "C:\Python27\lib\site-packages\speech.py", line 162, in input
listener = listenforanything(response)
File "C:\Python27\lib\site-packages\speech.py", line 193, in listenforanything
return _startlistening(None, callback)
File "C:\Python27\lib\site-packages\speech.py", line 223, in _startlistening
grammar = context.CreateGrammar()
File "C:\Users\REDACTED\AppData\Local\Temp\gen_py\2.7\C866CA3A-32F7-11D2-9602-00C04F8EE628x0x5x4.py", line 2298, in CreateGrammar
ret = self._oleobj_.InvokeTypes(14, LCID, 1, (9, 0), ((12, 49),),GrammarId
AttributeError: 'module' object has no attribute 'VARIANT'
Then I tried dragonfly per the suggestion at the top of the GoogleCode page for PySpeech using the following example code commonly found on dragonfly docs:
from dragonfly.all import Grammar, CompoundRule
# Voice command rule combining spoken form and recognition processing.
class ExampleRule(CompoundRule):
spec = "do something computer" # Spoken form of command.
def _process_recognition(self, node, extras): # Callback when command is spoken.
print "Voice command spoken."
# Create a grammar which contains and loads the command rule.
grammar = Grammar("example grammar") # Create a grammar to contain the command rule.
grammar.add_rule(ExampleRule()) # Add the command rule to the grammar.
grammar.load() # Load the grammar.
and got this very similar traceback:
Traceback (most recent call last):
File "C:/Users/REDACTED/Documents/Python Projects/listen.py", line 14, in <module>
grammar.load() # Load the grammar.
File "C:\Python27\lib\site-packages\dragonfly\grammar\grammar_base.py", line 302, in load
self._engine.load_grammar(self)
File "C:\Python27\lib\site-packages\dragonfly\engines\engine_sapi5.py", line 79, in load_grammar
handle = self._compiler.compile_grammar(grammar, context)
File "C:\Python27\lib\site-packages\dragonfly\engines\compiler_sapi5.py", line 68, in compile_grammar
grammar_handle = context.CreateGrammar()
File "C:\Users\REDACTED\AppData\Local\Temp\gen_py\2.7\C866CA3A-32F7-11D2-9602-00C04F8EE628x0x5x4.py", line 2298, in CreateGrammar
ret = self._oleobj_.InvokeTypes(14, LCID, 1, (9, 0), ((12, 49),),GrammarId
AttributeError: 'module' object has no attribute 'VARIANT'
Both modules were installed using PIP and run using python 2.7 interpreter. It seems like a python version issue to me given that the same error is thrown for two different modules implementing the same thing but I'm pretty stuck on how to proceed.
Any help is greatly appreciated and I'm happy to provide more code/info as its requested. Thanks!
EDIT 1: For anyone experiencing a similar problem who happens to stumble across this post, try https://pypi.python.org/pypi/SpeechRecognition/ as an alternative on py2.7. If it runs without error but behaves inconsistently or infinite loops, try modifying the init method of the recognizer class in init.py around line 100. The energy threshold required some tinkering for me (100->300) which is likely due to the specifics of your mic setup. I also increased my quiet duration (0.5->0.7) because it would cut me off sometimes. After these changes it works fairly well for me, returning very accurate text of the input speech in ~2 seconds after capture ends.

Using numdisplay, "An existing connection was forced to close by the remote host"

I've been learning to use python in astronomy and for that I'm following this notes. In the very beginning the author does the following example:
>>> im = pyfits.getdata('http://das.sdss.org/www/cgi-bin/drC?RUN=3630&RERUN=40&CAMCOL=3&FIELD=83&FILTER=r')
>>> numdisplay.display(im,z1=1000,z2=1500)
I try to replicate it and I get:
>>> numdisplay.display(im,z1=1000,z2=1500)
Image displayed with Z1: 1000 Z2: 1500
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
numdisplay.display(im,z1=1000,z2=1500)
File "C:\Mine\Python\lib\site-packages\numdisplay\__init__.py", line 446, in display
_d.writeImage(bpix,_wcsinfo)
File "C:\Mine\Python\lib\site-packages\numdisplay\displaydev.py", line 513, in writeImage
self.writeData(_lx,_ydisp,_fpix[block,:])
File "C:\Mine\Python\lib\site-packages\numdisplay\displaydev.py", line 379, in writeData
self._writeHeader(opcode,self._MEMORY, -nbytes, x, y, frame, 0)
File "C:\Mine\Python\lib\site-packages\numdisplay\displaydev.py", line 542, in _writeHeader
self._write(a.tostring())
File "C:\Mine\Python\lib\site-packages\numdisplay\displaydev.py", line 580, in _write
nwritten = self._socket.send(s[-n:])
error: [Errno 10054] An existing connection was forced to close by the remote host
I don't understand what I'm doing wrong. I mean if I write numdisplay.open() everything is fine... I'm thinking that it might be my antivirus or something that doesn't let python to communicate with ds9... Can somebody help me?
Edit: Well it doesn't seem to be the antivirus. I stopped it and run the script and I got the same error.
I was getting similar error messages, and I just tried adding a non-'None' argument to the bufname argument and it works (my image is about 4096.4096):
numdisplay.display(data,bufname='imt4096')

Categories

Resources