I would like to receive a signal in Windows OS + Python (3.7.5) environment, but the process will fail without receiving it.
If anyone knows the cause and how to deal with it, could you please let me know?
receiver_test.py
import time
import signal
def received (signum, stack):
print("RECEIVED!")
signal.signal(signal.SIGINT, received)
print("Start sleep...")
while True:
time.sleep(1)
killer_test.py
importos
import signal
Specify the process ID for pid=XXX#receiver_test.py
os.kill (pid, signal.SIGINT)
I launched two command prompts, receive_test.py and killer_test.py, respectively.
Results:
↓ US>After running killer_test.py, the process terminates without RECEIVED!
>python receive_test.py
Start sleep...
>
For os.kill,
Windows: signal.CTRL_C_EVENT and signal.CTRL_BREAK_EVENT are special signals that can only be sent to console processes that share the same console window (for example, child processes).If you give sig any other value, the TerminateProcess API kills the process unconditionally and sets the exit code to sig.
Because it is described as , only signal.CTRL_C_EVENT and signal.CTRL_BREAK_EVENT can be used, and they must share the same console.
Note that TerminateProcess is equivalent to kill-9 and cannot handle any process received.
I tried the article introduced in the comments.Windows 10 64bit, Python 3.7.6.
I am using keyboard 0.13.4 and pywin32227 in Module win32gui.
Use this answer for focus on the target window
Python Window Activation
Use this question for key press notification
Python "keyboard" module:Release keys to allow copy/Ctrl+C
The receiving script has not changed anything.
Notifier scripts are as follows: CTRL+C Notification
import win32gui
import re
import keyboard
class WindowMgr:
"""Encapsulates some calls to the winapi for window management"""
def__init__(self):
US>"Constructor"
self._handle=None
def find_window(self, class_name, window_name=None):
"""find a window by its class_name"""
self._handle=win32gui.FindWindow(class_name, window_name)
def_window_enum_callback(self, hwnd, wildcard):
"""Pass to win32gui.EnumWindows() to check all the opened windows"""
if re.match(wildcard, str(win32gui.GetWindowText(hwnd)))is not None:
self._handle=hwnd
defind_window_wildcard(self, wildcard):
"""find a window which title matches the wildcard regex"""
self._handle=None
win32gui.EnumWindows(self._window_enum_callback, wildcard)
default_foreground(self):
"""put the window in the foreground"""
win32gui.SetForegroundWindow(self._handle)
w = WindowMgr()
w.find_window_wildcard(".*receiver_test.*")#Window title to search for is script name
w.set_foreground()
keyboard.press_and_release('ctrl+c')
CTRL+BREAK changes the end of the above to the following
keyboard.press_and_release('ctrl+break')
As a result, ctrl+c
is notified, SIGINT
is processed, and RECEIVED!
is displayed to continue, and ctrl+break
is displayed to exit the script:
I don't know if I can use this or not, but I can do this.
© 2024 OneMinuteCode. All rights reserved.