KeyboardInterrupt Exception - python

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.

Related

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.

Pynput with pyinstaller 1.7.0

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.

How to use pywinauto to set_text in python IDLE editor?

I want to control python IDLE with pywinauto.
I can start IDLE but cannot input text.
Here is my code:
import pywinauto
app = pywinauto.application.Application(backend="uia").start(r"C:\Python37\pythonw.exe C:\Python37\Lib\idlelib\idle.pyw")
app2 = pywinauto.application.Application().connect(process=app.process)
I tried to use app2.Property.print_control_identifiers() but it returns:
Traceback (most recent call last):
File "C:\Python37\lib\site-packages\pywinauto\application.py", line 256, in __resolve_control
criteria)
File "C:\Python37\lib\site-packages\pywinauto\timings.py", line 458, in wait_until_passes
raise err
pywinauto.timings.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
app2.Property.print_control_identifiers()
File "C:\Python37\lib\site-packages\pywinauto\application.py", line 595, in print_control_identifiers
this_ctrl = self.__resolve_control(self.criteria)[-1]
File "C:\Python37\lib\site-packages\pywinauto\application.py", line 259, in __resolve_control
raise e.original_exception
File "C:\Python37\lib\site-packages\pywinauto\timings.py", line 436, in wait_until_passes
func_val = func(*args, **kwargs)
File "C:\Python37\lib\site-packages\pywinauto\application.py", line 201, in __get_ctrl
dialog = self.backend.generic_wrapper_class(findwindows.find_element(**criteria[0]))
File "C:\Python37\lib\site-packages\pywinauto\findwindows.py", line 84, in find_element
elements = find_elements(**kwargs)
File "C:\Python37\lib\site-packages\pywinauto\findwindows.py", line 303, in find_elements
elements = findbestmatch.find_best_control_matches(best_match, wrapped_elems)
File "C:\Python37\lib\site-packages\pywinauto\findbestmatch.py", line 533, in find_best_control_matches
raise MatchError(items = name_control_map.keys(), tofind = search_text)
pywinauto.findbestmatch.MatchError: Could not find 'Property' in 'dict_keys(['*Python 3.7.2 Shell*TkTopLevel', '*Python 3.7.2 Shell*', 'TkTopLevel'])'
How to solve the problem?
Thank you.
app = pywinauto.application.Application(backend="uia").start(r"C:\Python37\pythonw.exe C:\Python37\Lib\idlelib\idle.pyw")
app2 = pywinauto.application.Application().connect(process=app.process)
app3 = app2.top_window()
app3.print_control_identifiers()
I doubt that you can do whatever it is that you are trying to do. The pywinauto site says "pywinauto is a set of python modules to automate the Microsoft Windows GUI. At its simplest it allows you to send mouse and keyboard actions to windows dialogs and controls." IDLE uses tkinter, which uses the tcl/tk gui framework. While that ultimately uses Windows graphics, it may not be at the level that pywinauto accesses.
You can use pyautogui which is best for windows GUI automation
I converted RDP connection to automation using pyautogui
import pyautogui
import time
import os
os.system("C:\\Users\Administrator\\Desktop\\RDC.bat")
print(pyautogui.position())
time.sleep(5)
pyautogui.click(490,404)
pyautogui.typewrite("Bitwise$123")
pyautogui.typewrite(["Enter"])

Transferring code from pygst to pyGi

I wanted to build a program which streams radio from address. I wrote the following code:
try:
from gi.repository import Gst
except AttributeError as e:
pass
def on_tag(bus, msg):
taglist = msg.parse_tag()
print 'on_tag:'
for key in taglist.keys():
print '\t%s = %s' % (key, taglist[key])
music_stream_uri = 'http://213.8.143.168/91fmAudio'
player = Gst.element_factory_make("playbin", "player")
player.set_property('uri', music_stream_uri)
player.set_state(Gst.STATE_PLAYING)
It worked well when I did
import pygst
pygst.require("0.10")
import gst
but since It gave me several AttributeError and warning claims the module is deprecating I switched to pyGi and imported
from pi.repository import Gst
but then I got the error
Traceback (most recent call last):
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0.1\helpers\pydev\pydevd.py", line 2222, in <module>
globals = debugger.run(setup['file'], None, None)
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0.1\helpers\pydev\pydevd.py", line 1648, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:/Danis/radio/radio.py", line 20, in <module>
player = Gst.element_factory_make("playbin", "player")
File "C:\Python27\lib\site-packages\gi\module.py", line 320, in __getattr__
return getattr(self._introspection_module, name)
File "C:\Python27\lib\site-packages\gi\module.py", line 139, in __getattr__
self.__name__, name))
AttributeError: 'gi.repository.Gst' object has no attribute 'element_factory_make'
I wonder which command in pi.Gst is equivalent to the commands of the pygst? Does anybody know how to transfer this piece of code to PyGi?
I recommend you install an interpreter with tab completion such as ipython to look up methods. You will find documentation for introspected libs in python at http://lazka.github.io/pgi-docs/
Regarding your specific problem, the call to make is Gst.ElementFactory.make ()
Cheers!

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