How can pythoncom.PumpMessages() restart after PostQuitMessage? - python

I use a hook to check for Mouse Event and Keyboard Event, and I create a new thread for the hook because I have some other work to do.
The hook thread consumes CPU all the time, so I want to pause it occasionally (for efficiency). I tried using PostQuitMessage() to stop it and then wait to restart the thread and PumpMessages() at the right time. but it doesn't work.
I am looking forward to receiving your answers!
The following is the main part of the code,you can run it then will get the problem.
ps. Excuse my broken English~_~
# -*- coding: utf-8 -*- #
#Python version:3.5.4
from win32 import win32process
import time
import threading
#import win32
import psutil
import PyHook3 as pyHook
import pythoncom
import win32gui, win32ui, win32con, win32api
def OnMouseEvent(event):
print('-----Mouse-----', event)
return True
def OnKeyboardEvent(event):
print('-----key-----', event)
if str(event.Key)=='F12':
win32api.PostQuitMessage()
return True
def InputScan():
print('-----InputScan-----')
hm.MouseLeftDown = OnMouseEvent
hm.HookMouse()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
#first time is worked normally,but re-execution not working
pythoncom.PumpMessages()
return True
print('start program...')
threads = []
nowThreadsName=[]
hm = pyHook.HookManager()
try:
ThreadIS = threading.Thread(target=InputScan, name='ThreadIS', args=())
ThreadIS.setDaemon(True)
threads.append(ThreadIS)
ThreadIS.start()
except:
print("Error:--")
while 1:
#some other works
time.sleep(5)
open_str = input("whether restart(anykey): \n")
nowthread = threading.enumerate()
nowThreadsName.clear()
print("nowThreadsNameclear=",nowThreadsName)
for i in nowthread:
nowThreadsName.append(i.getName())
print("nowThreadsName=",nowThreadsName)
if 'ThreadIS' in nowThreadsName:
pass
else:
t = threading.Thread(target=InputScan, name='ThreadIS', args=())
t.setDaemon(True)
t.start() #why it dosen't work??
pass
pass

Related

pynput keyboard listener causes delays

I am making a program that toggles on and off by a certain key on the keyboard (using pynput). I placed the keyboard listener loop in the first thread, and the action loop in the second.
The problem is that after I start the code, it doesn't listen to the keyboard immediately, only after 9-10 seconds have passed. And sometimes it refuses to react to Esc button, and sometimes it works. How to fix the lag? Is the code ok?
from threading import Thread
from pynput import keyboard
import time
flag = False
kill = False
def on_press(key):
global flag
global kill
if key == keyboard.KeyCode.from_char('a'):
print('pressed A')
flag = not flag
if key == keyboard.Key.esc:
kill = True
return False
def thr2():
print('joining...')
with keyboard.Listener(on_press=on_press) as listen:
listen.join()
def thr1():
while True:
if kill:
break
if flag:
print('looping....')
time.sleep(0.4)
if __name__ == "__main__":
thread1 = Thread(target=thr1)
thread2 = Thread(target=thr2)
thread1.start()
thread2.start()
It looks like the actual delay is coming from the pynput keyboard.Listener context handler itself. I can't tell you whats happening under the hood but the delay is not coming from the way you are managing your threads.
# pynput library creating keyboard.Listener thread causes the delay
with keyboard.Listener(on_press=on_press) as listen:
print('listen thread created') # This does not happen until after the delay
listen.join()
You may want to rephrase the question so that it is specific to pynput keyboard.Listener
Here is a solution that works nicely with multiprocessing:
import sys
from pynput import keyboard
from time import sleep
from multiprocessing import Process, Event
from functools import partial
def thr2(kill_event, flag_event):
def on_press(kill_event, flag_event, key):
if key == keyboard.KeyCode.from_char('a'):
print('pressed A')
if flag_event.is_set():
flag_event.clear()
else:
flag_event.set()
if key == keyboard.Key.esc:
print('esc')
kill_event.set()
sys.exit(0)
with keyboard.Listener(on_press=partial(on_press, kill_event, flag_event)) as listen:
listen.join()
def thr1(kill_event, flag_event):
while True:
if kill_event.is_set():
print('kill')
sys.exit(0)
if flag_event.is_set():
print('looping....')
sleep(0.4)
if __name__ == "__main__":
kill_event = Event()
flag_event = Event()
thread1 = Process(target=thr1, args=(kill_event, flag_event))
thread2 = Process(target=thr2, args=(kill_event, flag_event))
thread1.start()
thread2.start()
thread1.join() # Join processes here to avoid main process exit
thread2.join()

Unable to remove lockfile

I'm trying to use zc.lockfile. I see that a lockfile is created in the same directory as my python script, but when I press ctrl+C, the file is NOT removed. I have a callback registered and have even tested given a long time (not sure if zc.lockfile spawns a new thread and needed time to complete).
import os
import sys
import signal
import time
import zc.lockfile
program_lock = None
def onExitCodePressed(signal, frame):
"""Callback run on a premature user exit."""
global program_lock
print '\r\nYou pressed Ctrl+C'
program_lock.close()
time.sleep(5)
sys.exit(0)
def main():
signal.signal(signal.SIGINT, onExitCodePressed)
if os.path.exists('myapp_lock'):
print "\nAnother instance of the program is already running.\n"
sys.exit(0)
else:
program_lock = zc.lockfile.LockFile('myapp_lock')
while True:
continue
if __name__ == '__main__':
main()

I want to stop pythoncom working

I was writing a code about keylogging by pyHook. The following codes are example:
import pythoncom as pc, pyHook as ph
def KeyboardHook(event):
print chr(event.Ascii)
return True
hm = ph.HookManager()
hm.KeyDown = KeyboardHook
hm.HookKeyboard()
pc.PumpMessages()
I want to stop pythoncom's PumpMessages method for a while later (for example five seconds). But I couldn't find any answer to it.
I use: Windows 7, Python2.7
Thanks for answer.
You will have to use pythoncom.PumpWaitingMessages which is not blocking.
import pythoncom as pc, pyHook as ph
import time
def KeyboardHook(event):
print chr(event.Ascii)
return True
hm = ph.HookManager()
hm.KeyDown = KeyboardHook
hm.HookKeyboard()
while time.clock() < 5:
pc.PumpWaitingMessages()

Python threading with pyhook

import win32api
import win32console
import win32gui
import pythoncom, pyHook , sys, time , os , threading
import shutil ,socket ,datetime
from ftplib import FTP
from threading import Thread
def fi():
while True:
dr = socket.gethostname()
if not os.path.exists(dr):
os.makedirs(dr)
else:
pass
now = datetime.datetime.now()
p = now.strftime("%Y-%m-%d %H-%M")
temp_path = dr + '/' + p
fil = temp_path + '.txt'
sys.stdout = open(fil,'w')
statinfo = os.stat(fil)
fils = statinfo.st_size
if(fils > 20):
now = datetime.datetime.now()
p = now.strftime("%Y-%m-%d %H-%M")
temp_path = dr + '/' + p
fil = temp_path + '.txt'
sys.stdout = open(fil,'w')
else:
pass
lastWindow = None
lastWindow=win32gui.GetWindowText (win32gui.GetForegroundWindow())
print lastWindow
def OnKeyboardEvent(event):
global lastWindow
window = event.WindowName
key = chr(event.Ascii)
if window != lastWindow:
start = '-----------------------------------'
print str(start)
print window
lastWindow = window
print key
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
if __name__ == '__main__':
Thread(target = fi).start()
Thread(target = OnKeyboardEvent(event)).start()
The first block of code def fi() is making a new file when the file size goes more than 20KB . The second block is a keylogger and logs the key in the file. I am new to python and multi-threading. Now when i run this code. i can only get the keylogger working and no file is formed and no logs are created. Please help me with this one.
All i need from this code is to create a log file named on the current time and log all the keywords into the file. and then if the file becomes more than 20KB then it should upload the old file to the server and make a new file with the new current time. I am new to python thats why i am not sure of what this code is wrong in and what it is not doing .*
First problem
You do create two Threads - but the target of the second is the return value of OnKeyboardEvent(event). This has no return-statement, so the return value is None, so the Thread has no target.
Second problem
Your code never reaches the if __name__ == "__main__":-part. It blocks on pythoncom.PumpMessages(), at least for me.
Third problem
At first I was confused how your code could run without throwing an exception - event in the last line isn't defined earlier in this scope. But problem 2 prevents problem 3 from becoming effective at the moment, but if you fix this, you'll have to face number 3 as well.
Solution
Honestly, I do not really understand what you are trying to do. You should definitely fix each of the problems.
Don't call the target of a thread, give the thread a function-object. If you need arguments, use the args-argument of Thread, e.g. Thread(target = OnKeyboardEvent, args=(event)).start()
I do not know the usage of pythoncom too well. Maybe pythocom.PumpWaitingMessages() is what you want?
I have no idea what you're trying to do here. Why do you want to call a callback-function in a Thread? This function has no loop or anything, so it will run once and stop. I guess it was just a desperate try?
General remarks
I'd not recommend redefining sys.stdout unless you really have to do so.
Please close() files you open. Maybe consider using the with-statement.
Even better: make use of the logging-module. It offers a lot of different possibilities.
When you create a Thread, think about the end. When will it stop? How can you stop it from another Thread?
import win32api
import win32console
import win32gui
import pythoncom, pyHook , sys, time , os , threading
import shutil ,socket ,datetime
from ftplib import FTP
from threading import Thread
def OnKeyboardEvent(event):
# Now you can access your hookmanager, and change which keys you want
# to watch. Using 'event' and 'hm', you can do some fun stuff in here.
global hm
global lastWindow
window=win32gui.GetWindowText(win32gui.GetForegroundWindow())
####window = event.WindowName
####I'm not sure, but these last two functions may not return the "exact"
####name values. I would call the same function you trying to compare against.
key = chr(event.Ascii)
if window != lastWindow: ## Now you know these at least come from same function
start = '-----------------------------------'
print str(start)
print window
lastWindow = window
print key
def fi(): #This is your "worker loop"
while True:
dr = socket.gethostname()
if not os.path.exists(dr):
os.makedirs(dr)
else:
pass
now = datetime.datetime.now()
p = now.strftime("%Y-%m-%d %H-%M")
temp_path = dr + '/' + p
fil = temp_path + '.txt'
sys.stdout = open(fil,'w')
statinfo = os.stat(fil)
fils = statinfo.st_size
if(fils > 20):
now = datetime.datetime.now()
p = now.strftime("%Y-%m-%d %H-%M")
temp_path = dr + '/' + p
fil = temp_path + '.txt'
sys.stdout = open(fil,'w')
else:
pass
if __name__ == '__main__':
"""This stuff only executes once"""
global lastWindow
lastWindow = None
lastWindow=win32gui.GetWindowText(win32gui.GetForegroundWindow())
print lastWindow
global hm #if we make this global, we can access inside OnKeyboardEvent
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
Thread(target = fi).start() #This is your worker loop
# We don't need this. OnKeyboardEvent will get callbacks from system
# thanks to Hookmanager and PumpMessages
##Thread(target = OnKeyboardEvent(event)).start()
# You wouldn't want to do it with the way we are set up, but this is a "polite"
# way to get PumpMessages to return...
#ctypes.windll.user32.PostQuitMessage(0) # stops pumpMessages
try:
pythoncom.PumpMessages() #This call will block forever unless interrupted
except (KeyboardInterrupt, SystemExit) as e: #We will exit cleanly if we are told
print(e)
os._exit()
I noticed your edit/comment on the original message. If you are still working on this, here is what I suggest.
Forget about the logging, threading, and other stuff you are trying to do. Focus on getting PyHook to work in its most simple state. From the original code, it seems you are struggling to get pyHook set up correctly (note, i do not currently have pyhook installed, so this is not tested code):
import pyHook
def OnKeyboardEvent(event):
print(event)
if __name__ == '__main__':
global hm #if we make this global, we can access inside OnKeyboardEvent
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
try:
pythoncom.PumpMessages() #This call will block forever unless interrupted,
# so get everything ready before you execute this.
except (KeyboardInterrupt, SystemExit) as e: #We will exit cleanly if we are told
print(e)
os._exit()
This code aims to simply hook any keypress event, print the event instance to the console. Technically you should not do much work INSIDE the event callback (it should return as quickly as possible), but for the sake of testing, you might be able to put some of your worker-functions in the event loop. THis would only be temporary, until you are ready to mix in your threaded worker loop. (and don't be surprised if file-access functions cause errors).
Get this working first. Then try storing stdout to a file. (forget about the 20Kb file limit for the time being).

disable or lock mouse and keyboard in Python?

Is there a way of disabling or locking mouse and keyboard using python? I want to freeze the mouse and disable the keyboard.
I haven't tested (actually I've tested the mouse part, and it annoyingly works) but something like this using pyhook would do what you want:
import pythoncom, pyHook
def uMad(event):
return False
hm = pyHook.HookManager()
hm.MouseAll = uMad
hm.KeyAll = uMad
hm.HookMouse()
hm.HookKeyboard()
pythoncom.PumpMessages()
I have extended Fábio Diniz's answer to a class which provides both a block() and an unblock() function which block (selectively) mouse/keyboard inputs. I also added a timeout functionality which (hopefully) addresses the annoyance of locking oneself out.
import pyHook
from threading import Timer
import win32gui
import logging
class blockInput():
def OnKeyboardEvent(self,event):
return False
def OnMouseEvent(self,event):
return False
def unblock(self):
logging.info(" -- Unblock!")
if self.t.is_alive():
self.t.cancel()
try: self.hm.UnhookKeyboard()
except: pass
try: self.hm.UnhookMouse()
except: pass
def block(self, timeout = 10, keyboard = True, mouse = True):
self.t = Timer(timeout, self.unblock)
self.t.start()
logging.info(" -- Block!")
if mouse:
self.hm.MouseAll = self.OnMouseEvent
self.hm.HookMouse()
if keyboard:
self.hm.KeyAll = self.OnKeyboardEvent
self.hm.HookKeyboard()
win32gui.PumpWaitingMessages()
def __init__(self):
self.hm = pyHook.HookManager()
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
block = blockInput()
block.block()
import time
t0 = time.time()
while time.time() - t0 < 10:
time.sleep(1)
print(time.time() - t0)
block.unblock()
logging.info("Done.")
You can have a look at the main routine for example usage.
For me, just two lines of programming solved the problem:
from ctypes import *
ok = windll.user32.BlockInput(True) #enable block
#or
ok = windll.user32.BlockInput(False) #disable block
Totally different take since all the solutions mentioned above use a quiet outdated library(pyhook) and this pyhook method personally didnt work for me.
import keyboard
from pynput.mouse import Controller
from time import sleep
def blockinput():
global block_input_flag
block_input_flag = 1
t1 = threading.Thread(target=blockinput_start)
t1.start()
print("[SUCCESS] Input blocked!")
def unblockinput():
blockinput_stop()
print("[SUCCESS] Input unblocked!")
def blockinput_start():
mouse = Controller()
global block_input_flag
for i in range(150):
keyboard.block_key(i)
while block_input_flag == 1:
mouse.position = (0, 0)
def blockinput_stop():
global block_input_flag
for i in range(150):
keyboard.unblock_key(i)
block_input_flag = 0
blockinput()
print("now blocking")
sleep(5)
print("now unblocking")
I just slightly modified the #Robert code and instead of the time I used external interrupt to close the program i.e. if you connect any external drive then the program gets close and your mouse and keyboard will be working perfectly.
import pyHook
from threading import Timer
import win32gui
import logging
import win32file
def locate_usb():#this will check any external Drives
drive_list = []
drivebits = win32file.GetLogicalDrives()
# print(drivebits)
for d in range(1, 26):
mask = 1 << d
if drivebits & mask:
# here if the drive is at least there
drname = '%c:\\' % chr(ord('A') + d)
t = win32file.GetDriveType(drname)
if t == win32file.DRIVE_REMOVABLE:
drive_list.append(drname)
return drive_list
class blockInput():
def OnKeyboardEvent(self,event):
return False
def OnMouseEvent(self,event):
return False
def unblock(self):
try: self.hm.UnhookKeyboard()
except: pass
try: self.hm.UnhookMouse()
except: pass
def block(self ,keyboard = True, mouse = True):
while(1):
if mouse:
self.hm.MouseAll = self.OnMouseEvent
self.hm.HookMouse()
if keyboard:
self.hm.KeyAll = self.OnKeyboardEvent
self.hm.HookKeyboard()
win32gui.PumpWaitingMessages()
cg= locate_usb()
if cg:
break
def __init__(self):
self.hm = pyHook.HookManager()
if __name__ == '__main__':
block = blockInput()
block.block()
block.unblock()
I hope this code will help you
Since 2018, you can now use pynput (v1.4+) to suppress keyboard and mouse events on Windows, Mac, and Linux.
import pynput
# Disable mouse and keyboard events
mouse_listener = pynput.mouse.Listener(suppress=True)
mouse_listener.start()
keyboard_listener = pynput.keyboard.Listener(suppress=True)
keyboard_listener.start()
# Enable mouse and keyboard events
mouse_listener.stop()
keyboard_listener.stop()
This also disables mouse scrolling and clicking.
However, this does not stop users from pressing Ctrl+Alt+Del on Windows. But you can run the script in an elevated command prompt, and the mouse and keyboard will still be disabled, even if they opened Task Manager using Ctrl+Alt+Delete, so there is no harm done (apparently there are way to actually prevent Ctrl+Alt+Delete, but do your own research for that)
You can use pyautogui to do this. Though I recommend adding keyboard for making a stopping key. First, you want to install pyautogui and keyboard.
Please note: this only disables the mouse not the keyboard, that is a very bad idea.
pip install pyautogui
pip install keyboard
Ok, with that sorted, we have to actually make the disabler.
import pyautogui
import keyboard
stopKey = "s" #The stopKey is the button to press to stop. you can also do a shortcut like ctrl+s
maxX, maxY = pyautogui.size() #get max size of screen
While True:
if keyboard.is_pressed(stopKey):
break
else:
pyautogui.moveTo(maxX/2, maxY/2) #move the mouse to the center of the screen
Ok, but there is 2 ways to get out of this. pressing S, and also quickly moving the mouse to one of the corners of the screen (that is a pyautogui failsafe, but we can disable that). If you want to disable the failsafe, add this after the imports:
pyautogui.FAILSAFE = False
Please note that disabling the failsafe is NOT recommended!
Ok, so now the only way to exit is the S key. If you want to stop this somewhere else in your program, do this:
pyautogui.press(stopKey)
Ok, so its not perfect, but it will stop you from doing basically anything with your mouse.

Categories

Resources