Pynput with pyinstaller 1.7.0 - python

I have a pynput error "COMBINING APOSTROPHY" when inputting a single quote into the listener with the international keyboard. I realize most people won't have this problem, but I want to handle that case.
I've looked it up and it seems to be an issue with pynput==1.6.8 and it's fixed in pynput==1.7.0^.
The problem is that I'm using pyinstaller to convert my script into an executable, and I like pyinstaller because it can also make executables for macOS and Linux, but pyinstaller doesn't work with pynput==1.7.0, the latest version it works with is pynput==1.6.8.
When using pynput==1.7.0, the generated .exe gives the descriptive error: Failed to execute script logger
Is there a way I can skip the combining apostrophe and not have the whole script crash with pynput==1.6.8?
Is there a way I can use pynput==1.7.0^ with pyinstaller?
Are there alternatives to pyinstaller that are better that can still generate executables for other OSs?
Maybe alternatives to pynput? Although I've had a hard time finding something as simple as pynput
I've been doing pyinstaller --onefile -w logger.py to convert my scripts.
The code for my script:
def on_press(key):
global keys, count
print(f"key = {key}")
keys.append(key)
count += 1
# reset
if count >= 1:
count = 0
write_file(keys)
keys = []
def on_release(key):
if key == Key.esc:
return False
if __name__ == "__main__":
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
The error I receive is:
Unhandled exception in listener callback
Traceback (most recent call last):
File "...\Programs\Python\Python39\lib\site-packages\pynput\_util\__init__.py", line 162, in inner
return f(self, *args, **kwargs)
File "...\Programs\Python\Python39\lib\site-packages\pynput\keyboard\_win32.py", line 275, in _process
key = self._event_to_key(msg, vk)
File "...\Programs\Python\Python39\lib\site-packages\pynput\keyboard\_win32.py", line 314, in _event_to_key
return KeyCode(**self._translate(
File "...\Programs\Python\Python39\lib\site-packages\pynput\keyboard\_base.py", line 52, in __init__
self.combining = unicodedata.lookup(
KeyError: "undefined character name 'COMBINING APOSTROPHE'"
Traceback (most recent call last):
File "...\logger.py", line 54, in <module>
listener.join()
File "...\Programs\Python\Python39\lib\site-packages\pynput\_util\__init__.py", line 210, in join
six.reraise(exc_type, exc_value, exc_traceback)
File "...\Programs\Python\Python39\lib\site-packages\six.py", line 702, in reraise
raise value.with_traceback(tb)
File "...\Programs\Python\Python39\lib\site-packages\pynput\_util\__init__.py", line 162, in inner
return f(self, *args, **kwargs)
File "...\Programs\Python\Python39\lib\site-packages\pynput\keyboard\_win32.py", line 275, in _process
key = self._event_to_key(msg, vk)
File "...\Programs\Python\Python39\lib\site-packages\pynput\keyboard\_win32.py", line 314, in _event_to_key
return KeyCode(**self._translate(
File "...\Programs\Python\Python39\lib\site-packages\pynput\keyboard\_base.py", line 52, in __init__
self.combining = unicodedata.lookup(
KeyError: "undefined character name 'COMBINING APOSTROPHE'"

There won't be any way to fix this without updating to a more recent version of pynput. If pyinstaller does not work for this then you will need to use something else. I don't know any linux executable compilers, but you could try dmgbuild for mac.
You could also try an alternative like pyautogui but it does not have all of the same functionalities as pynput. This just seems to be an issue between pyinstaller and pynput and unfortunately I don't see a lot you could do to fix this.

Related

No module named keyboard after converting py to exe

I am making an application which automatically enters your username and password. Everything works fine but when I try to convert it to .exe using auto-py-to-exe I get this error when I launch main.exe. I have added the modules in the hidden-import menu but it doesn't seem to work. I'm pretty new to this so please keep the answers more simple :D Here is the code of the actual program:
from pynput.mouse import Button
import keyboard
from pynput.keyboard import Key, Controller, Listener, KeyCode
mouse = Controller()
keyboards = Controller()
f = open("parolochetach.txt", "r")
list_of_lists = []
for line in f:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
f.close()
while True:
if keyboard.is_pressed('1') or keyboard.is_pressed('2') or keyboard.is_pressed('3') or keyboard.is_pressed('4') or\
keyboard.is_pressed('5') or keyboard.is_pressed('6') or keyboard.is_pressed('7') or keyboard.is_pressed('8')\
or keyboard.is_pressed('9'):
number = int(keyboard.read_key())
if number-1 <= len(list_of_lists):
mouse.position = (404, 415)
mouse.press(Button.left)
mouse.release(Button.left)
keyboards.type(list_of_lists[number-1][0])
mouse.position = (404, 465)
mouse.press(Button.left)
mouse.release(Button.left)
keyboards.type(list_of_lists[number-1][1])
keyboards.press(Key.enter)
keyboards.release(Key.enter)
I also tried to avoid using the keyboard module but I can't make it work. When I do something simple like:
def on_press(key):
if key==KeyCode.from_char('1'):
print("yes")
it works with no errors but when I add the click and type functions:
number = int(key)
if number - 1 <= len(list_of_lists):
mouse.position = (404, 415)
mouse.press(Button.left)
mouse.release(Button.left)
keyboards.type(list_of_lists[number - 1][0])
mouse.position = (404, 465)
mouse.press(Button.left)
mouse.release(Button.left)
keyboards.type(list_of_lists[number - 1][1])
keyboards.press(Key.enter)
keyboards.release(Key.enter)
it stops working and I get multiple errors:
Unhandled exception in listener callback
File"myfile", line 211, ni inner return f(self,*args, **kwargs)
File "", line 284, in _process
self.on_press(key)
File "", line 127, in inner
if f(*args) is False:
File "", line 17, in on_press
number = int(key)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'KeyCode'
Traceback (most recent call last):
File "", line 31, in <module>
listener.join()
File "", line 259, in join
six.reraise(exc_type, exc_value, exc_traceback)
File "", line 718, in reraise
raise value.with_traceback(tb)
File "", line 211, in inner
return f(self, *args, **kwargs)
File "", line 284, in _process
self.on_press(key)
File "", line 127, in inner
if f(*args) is False:
File "", line 17, in on_press
number = int(key)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'KeyCode'
This is my answer for another question here and it did work in that case.
Try using pyinstaller and if it can't find modules try this:
From Documentation
Helping PyInstaller Find Modules
Extending the Path If Analysis recognizes that a module is needed, but
cannot find that module, it is often because the script is
manipulating sys.path. The easiest thing to do in this case is to use
the --paths option to list all the other places that the script might
be searching for imports:
pyi-makespec --paths=/path/to/thisdir
--paths=/path/to/otherdir myscript.py
These paths will be noted in the spec file in the pathex argument.
They will be added to the current sys.path during analysis.

Pyperclip: "When using gi.repository you must not import static modules like "gobject"

I am making a program that will allow my phone to share its clipboard with my PC. I am using Pyperclip as it appears to be the easiest and most cross-platform solution. However, when I run the code below:
...
elif "incoming_clipboard:" in server_command:
print(server_command)
pyperclip.copy(server_command.replace("incoming_clipboard: ", ""))
...
I get the error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner
self.run()
File "/usr/lib/python3.9/threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "/home/chris/Documents/Programming/Synchrony/Desktop/Phone.py", line 30, in do_sync
self.handle_commands(bluetooth_socket)
File "/home/chris/Documents/Programming/Synchrony/Desktop/Phone.py", line 65, in handle_commands
pyperclip.copy(server_command.replace("incoming_clipboard: ", ""))
File "/usr/lib/python3.9/site-packages/pyperclip/__init__.py", line 659, in lazy_load_stub_copy
return copy(text)
File "/usr/lib/python3.9/site-packages/pyperclip/__init__.py", line 158, in copy_gtk
cb = gtk.Clipboard()
File "/usr/lib/python3.9/site-packages/gi/__init__.py", line 69, in __getattr__
raise AttributeError(_static_binding_error)
AttributeError: When using gi.repository you must not import static modules like "gobject". Please change all occurrences of "import gobject" to "from gi.repository import GObject". See: https://bugzilla.gnome.org/show_bug.cgi?id=709183
I know its not due to the string being invalid or anything, because 1) I am explicitly converting it from bytes to a string, and 2) it prints perfectly fine. I don't know if this is relevant, but I am using Linux, so perhaps that is affecting Pyperclip?
Do you guys have any solutions?
https://github.com/dynobo/normcap/issues/100
After going to the Github page for PyperClip, I found a similar issue that someone else had that suggested switching to PyClip. After installing PyClip and implementing it in project, I can confirm that it works perfectly without any issues.

KeyboardInterrupt Exception

I'm having a hard time handling Exceptions in pycharm 3.8:
When I press ctrl+c running my program, it doesn't work, so I've been told to use pycharm console to test it, and it does work, interrupting the keyboard input.
def readFloat(msg):
while True:
try:
return float(input(f'{msg}'))
except (ValueError, TypeError):
print(f'\033[31mError. Not valid.\033[m')
continue
except KeyboardInterrupt:
print('\033[31mYou didn\'t type a number.\033[m')
return 0
b = readFloat('Your Number: ')
print(f'\nThat\'s your number: {b}')
But now, when I try to Control+C, it doesn't catch my except and print my custom error report, returning 0. It gives me some huge and red error lines:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/User/PycharmProjects/Curso/Aula 23/ex113.py", line 35, in <module>
b = readFloat('Your Number: ')
File "C:/Users/User/PycharmProjects/Curso/Aula 23/ex113.py", line 26, in readFloat
return float(input(f'{msg}'))
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_stdin.py", line 64, in readline
requested_input = self.rpc_client.requestInput()
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_comm\pydev_transport.py", line 226, in _req
return super(TSyncClient, self)._req(_api, *args, **kwargs)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\third_party\thriftpy\_shaded_thriftpy\thrift.py", line 160, in _req
return self._recv(_api)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\third_party\thriftpy\_shaded_thriftpy\thrift.py", line 192, in _recv
raise v
console_thrift.KeyboardInterruptException: KeyboardInterruptException()
So I tried to add a generic exception just to print the error class, and I got this:
Error found: <class 'console_thrift.KeyboardInterruptException'>
So I can't manage to detect an except keyboardInterrupt and work with it, just using a generic exception, any ideas?
Edit
The only plugin that I added was a Theme UI to run pycharm totally black, the rest of them came with the instalation, I think. I ran the .py file using CMD and it works just fine, detecting the keyboard interrupt.
Try this:
try:
from console_thrift import KeyboardInterruptException as KeyboardInterrupt
except ImportError:
pass
Ref: Why doesn't this python keyboard interrupt work? (in pycharm)
The thing about IDEs is that they are not quite the same as running normally, especially when it comes to handling of keyboard characters. The way you press ctrl-c, your IDE thinks you want to copy text. The python program never sees the character. Perhaps it brings up a separate window when running? Then you would select that window before ctrl-c.

Mouse control with python

I'm running Ubuntu 12.04 and working with python 2. I would like to be able to control my mouse, and I have found several different python modules intended to do this, but cannot get them to work.
I installed dogtail, but when I try:
dogtail.rawinput.click(x,y)
I get:
AttributeError: 'module' object has no attribute 'rawinput'
I then tried pymouse and although I used pip to install it when I import pymouse:
from pymouse import PyMouse
I get:
TypeError: Object value must be tuple, dictionary or DictWrapper: 0
I tried the uinput module as well but the mouse commands only seemed to work when placed in a loop, which is frustrating/ridiculous.
If anyone knows how to fix either of those problems/what I'm doing wrong/better or easier to use modules I would much appreciate the help.
I'll assume that my problem is the same as yours, given the limited error information. The full exception and traceback I got was:
>>> import pymouse
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/pymouse/__init__.py", line 95, in <module>
from unix import PyMouse, PyMouseEvent
File "/usr/local/lib/python2.7/dist-packages/pymouse/unix.py", line 53, in <module>
class PyMouseEvent(PyMouseEventMeta):
File "/usr/local/lib/python2.7/dist-packages/pymouse/unix.py", line 66, in PyMouseEvent
'client_died': False,
File "/usr/local/lib/python2.7/dist-packages/Xlib/ext/record.py", line 121, in create_context
ranges = ranges)
File "/usr/local/lib/python2.7/dist-packages/Xlib/protocol/rq.py", line 1403, in __init__
self._binary = apply(self._request.to_binary, args, keys)
File "/usr/local/lib/python2.7/dist-packages/Xlib/protocol/rq.py", line 1088, in to_binary
return apply(self.to_binary, varargs, keys)
File "<string>", line 3, in to_binary
File "/usr/local/lib/python2.7/dist-packages/Xlib/protocol/rq.py", line 523, in pack_value
data.append(self.type.pack_value(v))
File "/usr/local/lib/python2.7/dist-packages/Xlib/protocol/rq.py", line 1102, in pack_value
return apply(self.to_binary, (), value)
File "/usr/local/lib/python2.7/dist-packages/Xlib/protocol/rq.py", line 1088, in to_binary
return apply(self.to_binary, varargs, keys)
File "<string>", line 4, in to_binary
File "/usr/local/lib/python2.7/dist-packages/Xlib/protocol/rq.py", line 573, in check_value
vals.append(f.check_value(val[i]))
File "/usr/local/lib/python2.7/dist-packages/Xlib/protocol/rq.py", line 582, in check_value
raise TypeError('Object value must be tuple, dictionary or DictWrapper: %s' % val)
TypeError: Object value must be tuple, dictionary or DictWrapper: 0
Note the exception occurs in Xlib. I had version 0.15rc1 installed. Downgrading to 0.14 fixed the problem.
use pynput .
It can control mouse, keyboard, etc.
examples:
mouse = Controller()
# Set pointer position
mouse.position = (10, 20)
# Press and release
mouse.press(Button.left)
mouse.release(Button.left)
this is my piece of code
from pymouse import PyMouse
m = PyMouse()
m.click(654, 169,1)
the first two arguments ar for X,Y
the last argument to define wich click 1=left click 2=right
i wish it helps
m.click(x,y,click)
I recomend you install pyautogui. You can control mouse and write.
Example:
import pyautogui as py
py.move(x,y) #it moves the mouse
py.click(x,y) #click the mouse on a position
py.write('write this') #Write
py.press('enter') #press a key (enter in this case)

How do I do threading in python?

I am trying to learn how to use threads with python. this is the code I have been studying:
import time
from threading import Thread
def myfunc(i):
print "sleeping 5 sec from thread %d" % i
time.sleep(5)
print "finished sleeping from thread %d" % i
for i in range(10):
t = Thread(target=myfunc, args=(i,))
t.start()
the program runs fine in command prompt but when I try to run it in idle I get errors like this:
Traceback (most recent call last):
File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__
return self.func(*args)
File "C:\Python24\lib\idlelib\ScriptBinding.py", line 165, in run_module_event
interp.runcode(code)
File "C:\Python24\lib\idlelib\PyShell.py", line 726, in runcode
self.tkconsole.endexecuting()
File "C:\Python24\lib\idlelib\PyShell.py", line 901, in endexecuting
self.showprompt()
File "C:\Python24\lib\idlelib\PyShell.py", line 1163, in showprompt
self.resetoutput()
File "C:\Python24\lib\idlelib\PyShell.py", line 1178, in resetoutput
self.text.insert("end-1c", "\n")
File "C:\Python24\lib\idlelib\Percolator.py", line 25, in insert
self.top.insert(index, chars, tags)
File "C:\Python24\lib\idlelib\PyShell.py", line 315, in insert
UndoDelegator.insert(self, index, chars, tags)
File "C:\Python24\lib\idlelib\UndoDelegator.py", line 81, in insert
self.addcmd(InsertCommand(index, chars, tags))
File "C:\Python24\lib\idlelib\UndoDelegator.py", line 116, in addcmd
cmd.do(self.delegate)
File "C:\Python24\lib\idlelib\UndoDelegator.py", line 216, in do
if text.compare(self.index1, ">", "end-1c"):
File "C:\Python24\lib\lib-tk\Tkinter.py", line 2784, in compare
return self.tk.getboolean(self.tk.call(
TclError: expected boolean value but got ""
Is python threading just not stable or am I doing something grossly wrong? The example came from : http://www.saltycrane.com/blog/2008/09/simplistic-python-thread-example/
It sounds like a bug in IDLE, not a problem with Python. The error is coming from Tkinter, which is a Python GUI toolkit, and which IDLE probably uses. I would report it to whoever maintains IDLE.
Not everything runs properly under IDLE. This is because IDLE is a Python program in itself and has its own attributes and state that can sometimes get messed up by your own code. You can tell this is a problem with IDLE because you can see idlelib in the call stack. Also, you're not using TCL/TK at all in your application, but IDLE is, and the call stack shows that too.
I would advise switching to a more 'inert' text editor for working with Python code!

Categories