pynput.keyboard Listener fails on macOS - python

I'm just trying to make a simple keyboard listener that prints whatever key I press (pynput.keyboard.Listener). Here is my code:
from pynput.keyboard import Listener
def on_press(k):
print(k)
with Listener(on_press=on_press) as lis:
lis.join()
But, when I run it just does nothing. So I press CTRL+C and it shows up these errors:
Traceback (most recent call last):
File "/Users/me/Desktop/py/KeyLogger/keylogger.py", line 8, in <module>
lis.join()
File "/usr/local/lib/python3.7/site-packages/pynput/_util/__init__.py", line 252, in join
super(AbstractListener, self).join(*args)
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 1044, in join
self._wait_for_tstate_lock()
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 1060, in _wait_for_tstate_lock
elif lock.acquire(block, timeout):
KeyboardInterrupt
Here with anaconda/Python3.8 instead of Python3.7:
Traceback (most recent call last):
File "/Users/me/Desktop/py/KeyLogger/keylogger.py", line 8, in <module>
lis.join()
File "/Users/me/opt/anaconda3/lib/python3.8/site-packages/pynput/_util/__init__.py", line 252, in join
super(AbstractListener, self).join(*args)
File "/Users/me/opt/anaconda3/lib/python3.8/threading.py", line 1011, in join
self._wait_for_tstate_lock()
File "/Users/me/opt/anaconda3/lib/python3.8/threading.py", line 1027, in _wait_for_tstate_lock
elif lock.acquire(block, timeout):
KeyboardInterrupt
It seems the error is when I tell the listener to start. I've been searching for similar issues (threading and join() issues, mostly) but I haven't found the answer to my problem. ¿Could it be a pynput problem?
Thanks.

Related

Vpython on Raspberry Pi 4b

i bought a rapberry pi 4 to code, i know is not the best platform, but recently my computer got stolen and its all i can afford right know.
im trying to get vpython to run.
these is the code that im trying to run
import vpython
ball=vpython.sphere()
while True:
pass
but it gives me these error.
Traceback (most recent call last):
File "/home/maviles/Documents/py-course/Vputhon/vppython.py", line 2, in <module>
ball=vpython.sphere()
File "/home/maviles/.local/lib/python3.9/site-packages/vpython/vpython.py", line 1172, in __init__
super(sphere, self).setup(args)
File "/home/maviles/.local/lib/python3.9/site-packages/vpython/vpython.py", line 599, in setup
super(standardAttributes, self).__init__()
File "/home/maviles/.local/lib/python3.9/site-packages/vpython/vpython.py", line 259, in __init__
from .no_notebook import _
File "/home/maviles/.local/lib/python3.9/site-packages/vpython/no_notebook.py", line 12, in <module>
from autobahn.asyncio.websocket import WebSocketServerProtocol, WebSocketServerFactory
File "/home/maviles/.local/lib/python3.9/site-packages/autobahn/asyncio/__init__.py", line 32, in <module>
from autobahn.asyncio.websocket import \
File "/home/maviles/.local/lib/python3.9/site-packages/autobahn/asyncio/websocket.py", line 36, in <module>
from autobahn.util import public, hltype
File "/home/maviles/.local/lib/python3.9/site-packages/autobahn/util.py", line 49, in <module>
from OpenSSL import SSL
File "/usr/lib/python3/dist-packages/OpenSSL/__init__.py", line 8, in <module>
from OpenSSL import crypto, SSL
File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 1556, in <module>
class X509StoreFlags(object):
File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 1577, in X509StoreFlags
CB_ISSUER_CHECK = _lib.X509_V_FLAG_CB_ISSUER_CHECK
AttributeError: module 'lib' has no attribute 'X509_V_FLAG_CB_ISSUER_CHECK'
exit
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "/home/maviles/.local/lib/python3.9/site-packages/vpython/vpython.py", line 22, in Exit
a = 1.0/zero
ZeroDivisionError: float division by zero
Exception ignored in: <function standardAttributes.__del__ at 0x7f93664550>
Traceback (most recent call last):
File "/home/maviles/.local/lib/python3.9/site-packages/vpython/vpython.py", line 1159, in __del__
super(standardAttributes, self).__del__()
File "/home/maviles/.local/lib/python3.9/site-packages/vpython/vpython.py", line 340, in __del__
cmd = {"cmd": "delete", "idx": self.idx}
AttributeError: 'sphere' object has no attribute 'idx'
please help.
i could not find anything on these topic for the raspberry 4b
i try to run the code and expec it to open a window with a sphere

Multiprocessing Process.join() hangs

I have a worker process that goes like this:
class worker(Process):
def __init__(self):
# init stuff
def run(self):
# do stuff
logging.info("done") # to confirm that the process is done running
And I start 3 processes like this:
processes = 3
aproc = [None for _ in processes]
bproc = [None for _ in processes]
for i in range(processes):
aproc[i] = worker(foo, bar)
bproc[i] = worker2(foo, bar) # different worker class
aproc[i].start()
bproc[i].start()
However, at the end of my code, I .join each of the processes, but they just hang and the script never ends.
for i in range(processes):
aproc[i].join()
bproc[i].join()
Hitting CTRL+C gives me this traceback:
Traceback (most recent call last):
File "[REDACTED]", line 571, in <module>
sproc[0].join()
File "/usr/lib/python3.9/multiprocessing/process.py", line 149, in join
res = self._popen.wait(timeout)
File "/usr/lib/python3.9/multiprocessing/popen_fork.py", line 43, in wait
return self.poll(os.WNOHANG if timeout == 0.0 else 0)
File "/usr/lib/python3.9/multiprocessing/popen_fork.py", line 27, in poll
pid, sts = os.waitpid(self.pid, flag)
I've heard of the typical deadlock, but this shouldn't be the case since all the processes print the logging statement that they are done running. Why is .join() still waiting on them? Any ideas? Thank you!
Edit: Unfortunately I can't get a minimal example working to share. Also, they do communicate with each other through multiprocessing.Queue()s, if that is relevant.
Edit 2:
Traceback of another test:
Traceback (most recent call last):
File "/usr/lib/python3.9/multiprocessing/util.py", line 300, in _run_finalizers
finalizer()
File "/usr/lib/python3.9/multiprocessing/util.py", line 224, in __call__
res = self._callback(*self._args, **self._kwargs)
File "/usr/lib/python3.9/multiprocessing/queues.py", line 201, in _finalize_join
thread.join()
File "/usr/lib/python3.9/threading.py", line 1033, in join
self._wait_for_tstate_lock()
File "/usr/lib/python3.9/threading.py", line 1049, in _wait_for_tstate_lock
elif lock.acquire(block, timeout):

How to raise index error in Pandas on a Windows machine?

I am using pandas_dedupe library. I get this error when I try to run on a Windows machine, but this same code runs fine on a Mac.
import pandas as pd
import pandas_dedupe as pdd
df=pd.read_csv('sample.csv')
df=pdd.dedupe_dataframe(df,['firstname','lastname','gender','zipcode','address'])
df.to_csv('sample_deduped.csv')
df=df[df['cluster id'].isnull() | ~df[df['cluster id'].notnull()].duplicated(subset='cluster id',keep='first')]
df.to_csv('sample_deuped_removed.csv')
Here are the logs in case you want to have a look:
Traceback (most recent call last):
File "C:/Users/vikas.mittal/Desktop/python projects/untitled2/deduplication.py", line 10, in <module>
df=pdd.dedupe_dataframe(df,['firstname','lastname','gender','zipcode','address'])
File "C:\Users\vikas.mittal\Desktop\python projects\untitled2\venv\lib\site-packages\pandas_dedupe\dedupe_dataframe.py", line 213, in dedupe_dataframe
sample_size)
File "C:\Users\vikas.mittal\Desktop\python projects\untitled2\venv\lib\site-packages\pandas_dedupe\dedupe_dataframe.py", line 72, in _train
dedupe.consoleLabel(deduper)
File "C:\Users\vikas.mittal\Desktop\python projects\untitled2\venv\lib\site-packages\dedupe\convenience.py", line 36, in consoleLabel
uncertain_pairs = deduper.uncertainPairs()
File "C:\Users\vikas.mittal\Desktop\python projects\untitled2\venv\lib\site-packages\dedupe\api.py", line 714, in uncertainPairs
return self.active_learner.pop()
File "C:\Users\vikas.mittal\Desktop\python projects\untitled2\venv\lib\site-packages\dedupe\labeler.py", line 323, in pop
raise IndexError("No more unlabeled examples to label")
IndexError: No more unlabeled examples to label
Process finished with exit code 1

Inspecting local variables in threads in Python (pyrasite)?

I have a script that uses threads, that simply freezes after running for an hour or so, which makes it pretty difficult to debug.
Eventually, I found pyrasite, and basically, I could "hook" into the script as soon as I waited it out and it froze. It looks somewhat like this in terminal:
$ pyrasite-shell 3437
Pyrasite Shell 2.0
Connected to 'python3 code/MyTestScript.py'
Python 3.5.3 (default, Sep 27 2018, 17:25:39)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
(DistantInteractiveConsole)
>>> import sys, traceback
>>> for thread_id, frame in sys._current_frames().items():
... print('Stack for thread {}'.format(thread_id))
... traceback.print_stack(frame)
... print('')
...
Stack for thread 1888482416
File "/usr/lib/python3.5/threading.py", line 882, in _bootstrap
self._bootstrap_inner()
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "<string>", line 167, in run
File "/usr/lib/python3.5/code.py", line 228, in interact
more = self.push(line)
File "/usr/lib/python3.5/code.py", line 250, in push
more = self.runsource(source, self.filename)
File "/usr/lib/python3.5/code.py", line 75, in runsource
self.runcode(code)
File "/usr/lib/python3.5/code.py", line 91, in runcode
exec(code, self.locals)
File "<console>", line 3, in <module>
Stack for thread 1898968176
File "/usr/lib/python3.5/threading.py", line 882, in _bootstrap
self._bootstrap_inner()
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "/home/pi/code/my_test_lib.py", line 187, in sendData
self.evexit.wait(sleep_time_s)
File "/usr/lib/python3.5/threading.py", line 549, in wait
signaled = self._cond.wait(timeout)
File "/usr/lib/python3.5/threading.py", line 297, in wait
gotit = waiter.acquire(True, timeout)
Stack for thread 1996019264
File "code/MyTestScript.py", line 1355, in <module>
main(sys.argv[1:])
File "code/MyTestScript.py", line 1245, in main
myObject.waitForJoin() # seems to work fine...
File "/home/pi/code/my_test_lib.py", line 251, in waitForJoin
self.myThread.join()
File "/usr/lib/python3.5/threading.py", line 1054, in join
self._wait_for_tstate_lock()
File "/usr/lib/python3.5/threading.py", line 1070, in _wait_for_tstate_lock
elif lock.acquire(block, timeout):
Stack for thread 1908950128
File "/usr/lib/python3.5/threading.py", line 882, in _bootstrap
self._bootstrap_inner()
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "/home/pi/code/my_testB_lib.py", line 511, in UpdateMyThread
time.sleep(_update_interval_sec)
This looks great, but what I cannot tell is, whether the script including all its threads is now paused (as if a breakpoint in gdb hass been set), or does the script keep running in the background?
Anyways, I know that in gdb, I could have just issued say thread 1, and then I'd end up in the corresponding stack frame, and then I could print local variables etc.
Here, however, I cannot tell how to change stack frames, nor how to switch threads, so that I could inspect variables.
Is this possible with pyrasite? And if not, is there any other library for Python3, that would allow me the same (that is, ability to hook into an uninstrumented script with threads that freezes), while allowing me to inspect any/all threads and stackframes for local variable values?
Starting from Pyrasite's included dump_stacks.py payload, I created the snippet below which dumps local variable names and values after each stack trace. However it doesn't seem to work correctly as a Pyrasite payload -- it looks like the globals get displayed instead for some reason? I'm new to Pyrasite myself so I'm not sure if this is a bug or if I'm not using it correctly. If I run pyrasite-shell instead and paste the code in directly, it works as expected (ignoring the extra trace from the shell thread itself).
If you need to see different info, you can either modify the code and re-paste it or just explore interactively within the pyrasite shell.
import sys, traceback
for thread, frame in sys._current_frames().items():
print('Thread 0x%x' % thread)
print('=' * 25)
traceback.print_stack(frame)
print('-' * 25)
for name, value in frame.f_locals.items():
print(f"{name}: {value}")
print()
This script might be what you are looking for:
import sys, traceback
for thread_id, frame in sys._current_frames().items():
print('Stack for thread {}'.format(thread_id))
stack = traceback.StackSummary.extract(traceback.walk_stack(frame), capture_locals=True)
stack.reverse()
traceback.print_list(stack)
print('')
It basically does the same thing as traceback.print_stack(frame), but it also supplies the capture_locals=True, which is false in the print_stack convenience method.

Python shelve key error from threading?

** Importantly, this error does not occur all the time. It pops up every now and then, so I don't believe my code is at fault here.**
Hello, I am using threading along with Python 3.7 shelves. I have a dictionary object inside my shelf. Is this an error caused by threading/simultaneous access? (Using python's Threading library).
Relevant code is merely:
requestLibrary[requestID]
I am certain that this works, the key has been placed inside the library. But for some instances, the I get this key error. I suspect it has to do with the threading.
Exception in thread Thread-14:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: '4fGdb'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/lme/Workflow/Source/busDriver.py", line 189, in busDriver
while 'workflowEndingPoint'.lower() not in str(requestLibrary[requestID]).lower():
File "/usr/local/lib/python3.6/shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
KeyError: b'4fGdb'

Categories