class Camera(): url = 'http://192.168.0.100:8080/shot.jpg' counter = 0 breakPlease = False def __init__(self, dir: str, reshape=(640, 480)): self.setReshape(reshape) self.setDir(dir) self.setKeyListner() def setKeyListner(self): self.keyListner = Listener(on_press=self.keyPressed, on_release=self.keyReleased) def keyPressed(self, key): if key == Key.esc: self.breakPlease = True if key == Key.space: image = self.image reshaped = resize(image, self.reshape, INTER_AREA) save = f"{self.dir}/{int(time())}.jpg" imwrite(save, reshaped) print(save) def keyReleased(self, key): pass def startCamera(self): print(''' IP Webcam camera save !! esc: - Exit space: - Take photo ''') self.keyListner.start() while True: if self.breakPlease: break imgResp = urlopen(self.url) imgNp = array(bytearray(imgResp.read()), dtype=uint8) self.image = imdecode(imgNp, IMREAD_UNCHANGED) self.keyListner.stop() print(''' Exiting !!! ''') def setDir(self, dir): Path(dir).mkdir(exist_ok=True) self.dir = dir def setReshape(self, reshape): if len(reshape) != 2: raise AttributeError("reshape shold be of len 2") self.reshape = reshape
class KEYMONITOR(): def __init__(self): self.listener = Listener(on_press=self.__press) self.listener.start() self._pressed = False self.key = '' def get_key(self): if self._pressed: self._pressed = False return self.key else: return None def __press(self, key): if key in Key: self.key = key.name self._pressed = True elif type(key) == pynput.keyboard._win32.KeyCode: self.key = key.char self._pressed = True else: pass def __del__(self): self.release() def release(self): self.listener.stop()
class KeyboardController: def __init__(self, degree=80): self.action = [0, 0, 0, 0, 0] self.degree = degree self.listener = Listener(on_press=self.on_press, on_release=self.on_release) self.start() def on_press(self, key): if key == Key.space: self.action[2] = 1 if key == Key.ctrl: self.action[3] = 1 if key == Key.shift: self.action[4] = 1 if key == Key.right: self.action[0] = self.degree if key == Key.left: self.action[0] = -1 * self.degree def on_release(self, key): if key == Key.space: self.action[2] = 0 if key == Key.ctrl: self.action[3] = 0 if key == Key.shift: self.action[4] = 0 if key == Key.right: self.action[0] = 0 if key == Key.left: self.action[0] = 0 def start(self): self.listener.start() def stop(self): self.listener.stop()
class keylogger: def __init__(self): path = "keylog.txt" if os.path.exists(path): os.remove(path) logging.basicConfig( handlers=[logging.FileHandler('keylog.txt', 'w', 'utf-8')], level=logging.DEBUG, format='%(message)s') logging.StreamHandler.terminator = " " self.listener = None def start(self): def on_press(key): key = str(key) if (key.startswith("Key.")): key = key[4:] else: key = key.strip('\'') logging.info(key) self.listener = Listener(on_press=on_press) logging.info("\n") self.listener.start() def stop(self): self.listener.stop()
class Keylog: def __init__(self, sk): self.sk = sk self.keystring = None self.is_hook = None self.keys = "" def hook(self): if self.is_hook: return self.is_hook = True self.listener = Listener(on_press=self.on_press) self.listener.start() def on_press(self, key): #self.sk.client.sendall(bytes("press",'utf8')) self.keys += str(format(key)) def un_hook(self): if not self.is_hook: return self.listener.stop() self.is_hook = False def send_keys(self): self.sk.sendall(bytes(str(len(self.keys)), 'utf8')) self.sk.sendall(bytes(str(self.keys), "utf8")) def delete_keys(self): self.keys = ""
class KeyMonitor(QtCore.QObject): keyPressed = QtCore.pyqtSignal(object) def __init__(self, parent=None): super().__init__(parent) self.listener = Listener(on_press=self.on_press, on_release=self.on_release) self.currentKey = None self.released = False print("Monitor init!") def on_press(self, key): self.released = False self.currentKey = key self.keyPressed.emit(key) def on_release(self, key): self.currentKey = None self.released = True def stop_monitoring(self): self.listener.stop() self.deleteLater() def start_monitoring(self): self.listener.start()
def main(): global pause, nxt, vol, exit, key_listener try: pause = '' nxt = '' vol = '' exit = '' tracks = [] path = os.getcwd() re_track = re.compile(r'^.+\.(?:mp3|mp4|wav)') for dirpath, dirnames, filenames in os.walk(path + '\\tracks'): [tracks.append(file) for file in filenames if re_track.match(file)] display() key_listener = Listener(on_press=on_press) player = Thread(target=media_player, args=(tracks, path)) key_listener.start() player.start() key_listener.join() player.join() except KeyboardInterrupt: print('Program exiting ..') if key_listener.is_alive(): key_listener.stop()
class KeyController: def __init__(self): self.listener = Listener( on_press=self.on_press, on_release=self.on_release) self.key_pressed = [] self.thread = Thread(target=self.run, args=()) self.thread.start() def on_press(self, key: KeyCode): # print('{0} release'.format(key)) keychar = str(key).replace("\'", "").lower() if keychar not in self.key_pressed: self.key_pressed.append(keychar) def on_release(self, key: KeyCode): # print('{0} release'.format(key)) keychar = str(key).replace("\'", "").lower() if keychar in self.key_pressed: self.key_pressed.remove(keychar) if key == KeyCode.from_char('t'): # Stop listenerd return False def run(self): with self.listener: self.listener.join() self.stop() def stop(self): self.listener.stop() def get_key_pressed(self) -> list: return self.key_pressed
class KeyController: def __init__(self): self.listener = Listener(on_press=self.on_press, on_release=self.on_release) self.key_pressed = [] self.run() def on_press(self, key): # print('{0} pressed'.format(key)) if key not in self.key_pressed: self.key_pressed.append(key) def on_release(self, key): # print('{0} released'.format(key)) if key in self.key_pressed: self.key_pressed.remove(key) if key == KeyCode.from_char('t'): self.listener.stop() return False def run(self): self.listener.start() def stop(self): self.listener.stop() def get_key_pressed(self) -> list: return self.key_pressed
class KeyMonitor(QtCore.QObject): keyPressed = QtCore.pyqtSignal(KeyCode) def __init__(self, parent=None): super().__init__(parent) self.listener = Listener(on_release=self.on_release) def on_release(self, key): try: self.keyPressed.emit(key) keyObjToChar = key.char if keyObjToChar == 'w': self.publish("/", "w") elif keyObjToChar == 's': self.publish("/", "s") elif keyObjToChar == 'a': self.publish("/", "a") elif keyObjToChar == 'd': self.publish("/", "d") except: pass @staticmethod def publish(topic, message): print(manualClient.publish(topic, message), " Action: ", message) def stop_monitoring(self): self.listener.stop() def start_monitoring(self): self.listener.start()
class KeyboardController(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.pressed = set([]) self.functions = {} self.start() def on_press(self, key): self.pressed.add(key) if key in self.functions: self.functions[key]() def on_release(self, key): try: self.pressed.remove(key) except: pass def add(self, key, function): self.functions[key] = function def run(self): self.listener = Listener(on_press=self.on_press, on_release=self.on_release) self.listener.start() self.listener.join() def callback(self): self.listener.stop()
class Player: """ This class handles the input from the user """ def __init__(self, env): """ initialize class parameters """ # initialize player action self.action = None # run keyboard listener self.listener = Listener(on_press=self.set_action) self.env = env def start(self): self.listener.start() def stop(self): self.listener.stop() def set_action(self, key): print(key) if key == key.up: self.action = [1, 0, 0, 0] elif key == key.right: self.action = [0, 1, 0, 0] elif key == key.down: self.action = [0, 0, 1, 0] elif key == key.left: self.action = [0, 0, 0, 1] self.env.act(self.action)
class Keyboard: def __init__(self): self._logger = getLogger(__name__) self._logger.addHandler(NullHandler()) self._logger.setLevel(DEBUG) self._logger.propagate = True self.listener = Listener( on_press=self.on_press, on_release=self.on_release) def listen(self): self.listener.start() self._logger.debug('Keyboard control start') def stop(self): self.listener.stop() self._logger.debug('Keyboard control stop') def on_press(self, key): try: print('alphanumeric key {0} pressed'.format(key.char)) except AttributeError: print('special key {0} pressed'.format(key)) def on_release(self, key): print('{0} released'.format(key))
def on_press(key): # print("Key pressed: {0}".format(key)) if key == Key.esc: print("Key pressed: {0}".format(key)) # return False KeyboardListener.stop() MouseListener.stop()
def scan(self): # Scan for 0.5s, scanner dumps legi number as keystrokes in a short time interval. # Not perfect because if the actual scanning doesn't completely happen during time.sleep it will split # the scanned data (sanity of data is checked at a later step, nontheless user will have to scan twice.) listener = Listener(on_press=self.log_keystroke) listener.start() time.sleep(0.5) listener.stop()
def run(self): listener = Listener(on_press=self.on_press).start() while True: if not self.communication_queue.empty(): message = self.communication_queue.get() if message == "end": listener.stop() break
class KeyboardLogger(): class Event(enum.Enum): Press = 1 Release = 2 def __init__(self, file_name=None, debug=False, handler=None) -> None: super().__init__() self.listener = None self.data = [] self.debug = debug self.handler = handler self.file_name = file_name self.last_pressed_key = None self.last_released_key = None def on_press(self, key): if self.handler is not None and callable(self.handler): self.handler(key) if key != self.last_pressed_key and hasattr(key, 'vk'): timestamp = time() self.data.append( [timestamp, key.vk, KeyboardLogger.Event.Press.value]) self.last_released_key = None self.last_pressed_key = key if self.debug: print('{0} pressed at {1}'.format(key, timestamp)) def on_release(self, key): if key != self.last_released_key and hasattr(key, 'vk'): timestamp = time() self.data.append( [timestamp, key.vk, KeyboardLogger.Event.Release.value]) self.last_released_key = key self.last_pressed_key = None if self.debug: print('{0} released at {1}'.format(key, timestamp)) def start_thread(self): if self.debug: print("Logger started") self.listener = Listener(on_press=self.on_press, on_release=self.on_release) with self.listener: self.listener.join() def start(self): listener_thread = threading.Thread(target=self.start_thread) listener_thread.start() def stop(self): if self.debug: print("Logger stopped") if self.file_name is None: return if self.listener is not None: self.listener.stop() numpy.savetxt(self.file_name + KEYS_SUFFIX, self.data)
def on_press(key): if key == start_stop_key: if click_thread.running: click_thread.stop_clicking() else: click_thread.start_clicking() elif key == exit_key: click_thread.exit() Listener.stop()
def on_press(key): if str(key) == photo_key: take_a_photo() elif str(key) == stop_key: Listener.stop() destroy() else: print('nichts') pass
def scan(self): #Scan for 0.5 secs and return listener = Listener(on_press=self.log_keystroke) listener.start() time.sleep(0.5) try: listener.stop() except: listener.stop()
class KeyboardListener(): def calculate_duration(self): old_time, self.last_time = self.last_time, time.time() duration = self.last_time - old_time return duration def for_cannoncial(self, func): return lambda key: func(self.listener.canoncial(key)) def on_press(self, key): # TODO: If key is Hotkey, don't save it to events self.append_to_event(key, True) def on_release(self, key): self.append_to_event(key, False) pass def append_to_event(self, key, pressed): duration = self.calculate_duration() event = KeyboardEvent(key, pressed, duration) self.events.append(event) logger.debug(f"{event} kaydediledi") def __init__(self): self.listener = Listener(on_press=self.on_press, on_release=self.on_release) logger.debug("Listener tanımlandı") def record(self, duration=0): self.last_time = time.time() self.events = [] self.listener.start() logger.info("Dinleyici başlatıldı") if duration > 0: do_delayed(self.stop_record, duration) def stop_record(self): self.listener.stop() logger.info("Dinleyici sonlandırıldı") def play_record(self): controller = KeyboardController() controller.replay(self.events) @background def play_record_async(self): controller = KeyboardController() controller.replay(self.events)
class KeyLogger: def __init__(self, log_dir: str, log_id=None, callback_list=None): self.history = [] self.callback_list = callback_list if callback_list is not None else [] self.listen_thread = None self.listening = False self.key_listener = Listener(on_press=self.on_press) start_time = time.time() if not os.path.isdir(log_dir): os.makedirs(log_dir) if log_id: self.log_fname = os.path.join(log_dir, f'log_{log_id}_{start_time}.txt') else: self.log_fname = os.path.join(log_dir, f'log_{start_time}.txt') return def on_press(self, key): self.history.append(key) logging.info(str(key)) read_time = time.time() for each_callback in self.callback_list: if callable(each_callback): each_callback({'timestamp': read_time, 'data': key}) return def start_listener(self): self.listen_thread = threading.Thread(target=self.__listen, daemon=True) self.listen_thread.start() return def __listen(self): self.listening = True logging.basicConfig(filename=self.log_fname, level=logging.DEBUG, format='%(asctime)s: %(message)s') self.key_listener.start() while self.listening: pass return def stop_listener(self): self.listening = False return def cleanup(self): self.stop_listener() self.listen_thread.join() self.key_listener.stop() self.listen_thread.join() return
def Prac_Controller(): global run, listener, Listener run = True listener = Listener(on_press=lambda event: on_press(event)) listener.start() while run: quest() #stop the listener... listener.stop() select1()
def main(): global running listener = Listener( on_press=on_press, on_release=on_release) listener.start() while running: time.sleep(0.1) listener.stop()
def timer(): global run, listener, Listener run = True listener = Listener(on_press=lambda event: on_press(event)) listener.start() while run: learn() time.sleep(2) #stop the listener... listener.stop() select1()
def start_record(self): self.log = open(self.replay_file, "w") self.init_time = time.time() * 1000 # To make microseconds keyboard_listener = KeyboardListener(on_press=self.__on_press, on_release=self.__on_release) mouse_listener = MouseListener(on_click=self.__on_click, on_scroll=self.__on_scroll) keyboard_listener.start() mouse_listener.start() keyboard_listener.join() mouse_listener.stop() keyboard_listener.stop() self.log.flush() self.log.close()
def main(): delay = choose_delay() print(f"delay = {str(delay)}sec\n") display_controls() listener = Listener(on_press=key_press) listener.start() while running: if not pause: pyautogui.click(pyautogui.position()) pyautogui.PAUSE = delay listener.stop()
class Listener: def __init__(self): self.keyboard_listener = KeyboardListener(on_press=on_press, on_release=on_release) self.mouse_listener = MouseListener(on_click=on_click, on_scroll=on_scroll, on_move=on_move) def start(self): self.keyboard_listener.start() self.mouse_listener.start() def stop(self): self.keyboard_listener.stop() self.mouse_listener.stop()
class KeyMonitor(QtCore.QObject): keyPressed = QtCore.pyqtSignal(KeyCode) def __init__(self, parent=None): super().__init__(parent) self.listener = Listener(on_release=self.on_release) def on_release(self, key): self.keyPressed.emit(key) def stop_monitoring(self): self.listener.stop() def start_monitoring(self): self.listener.start()
def getdir(self): self.dir_ = None # 如果是不是上下左右则返回None def on_press(key): if key == Key.up: self.dir_ = Direction.UP elif key == Key.down: self.dir_ = Direction.DOWN elif key == Key.left: self.dir_ = Direction.LEFT elif key == Key.right: self.dir_ = Direction.RIGHT return False listener = Listener(on_press=on_press) # 创建监听器 listener.start() # 开始监听,每次获取一个键 listener.join() # 加入线程 listener.stop() # 结束监听 return self.dir_
class DelayParser(Thread): """Parser that checks Regeneration Delays and controls an overlay""" DELAYS = { "Power_Shield_Regen_Delay": "Shield", "Power_Weapon_Regen_Delay": "Weapon", "Power_Engine_Regen_Delay": "Engine" } POOLS = ["Weapon", "Shield", "Engine"] STATS = { "Delay": "Power_{}_Regen_Delay", "Regen": "Power_{}_Regen_Rate", "Recent": "Power_{}_Regen_Rate_(when_Recently_Consumed)" } def __init__(self): """Initialize as Thread and create attributes""" Thread.__init__(self) self._stats = {p: {k: 0.0 for k in self.STATS} for p in self.POOLS} self._lock = Lock() self._exit_queue = Queue() self.primary = "PrimaryWeapon" self.__delays = dict() self._internal_q = Queue() self._match = False self._ms_listener = MSListener(on_click=self._on_click) self._kb_listener = KBListener(on_press=self._on_press) self._mouse = False self._string = str() print("[DelayParser] Initialized") def set_ship_stats(self, ship: ShipStats): """Update the ship statistics used for delay tracking""" self._lock.acquire() self._stats = { p: {k: ship["Ship"][v.format(p)] for k, v in self.STATS.items()} for p in self.POOLS } self.primary = "PrimaryWeapon" self._lock.release() print("[DelayParser] Updated ship to: {}".format(ship.ship.name)) def primary_weapon_swap(self): """Swap the primary weapon key""" self.primary = "PrimaryWeapon2" if self.primary == "PrimaryWeapon" else "PrimaryWeapon" print("[DelayParser] Swapped Primary Weapons") def match_end(self): """Match ended callback""" self._internal_q.put("end") def match_start(self): """Match start callback""" self._internal_q.put("start") def update(self): """Update the state of the DelayParser""" self._lock.acquire() stats, key = self._stats.copy(), self.primary self._lock.release() while not self._internal_q.empty(): v = self._internal_q.get() if v == "start": self._match = True elif v == "end": self._match = False elif v == "mouse": self._mouse = not self._mouse else: pool, time = v self.__delays[pool] = time if self._match is False: return if self._mouse is True: self.__delays["Weapon"] = datetime.now() string, time = "\n", datetime.now() for pool, start in self.__delays.items(): elapsed = (time - start).total_seconds() remaining = max(stats[pool]["Delay"] - elapsed, 0.0) rate = stats[pool]["Regen"] if remaining == 0.0 else stats[pool]["Recent"] string += "{}: {:.1f}s, {:.1f}pps\n".format(pool[0], remaining, rate) self._lock.acquire() self._string = string self._lock.release() sleep(0.1) def process_event(self, event: dict, active_ids: list): """Process an event to check for shield power pool usage""" ctg = Parser.get_event_category(event, active_ids) if event["self"] is True and ctg == "engine": self._internal_q.put(("Engine", event["time"])) return if event["self"] is True or Parser.compare_ids(event["target"], active_ids) is False: return if "Damage" not in event["effect"]: return # event: Damage dealt to self self._internal_q.put(("Shield", event["time"])) def cleanup(self): """Clean up everything in use""" self._ms_listener.stop() self._kb_listener.stop() def run(self): """Run the Thread""" self._ms_listener.start() self._kb_listener.start() print("[DelayParser] Keyboard and Mouse Listeners started") while True: if not self._exit_queue.empty(): break self.update() self.cleanup() def stop(self): """Stop activities and join Thread""" if not self.is_alive(): return self._exit_queue.put(True) self.join(timeout=1) def _on_click(self, x: int, y: int, button: Button, state: bool): """Process a click to check for weapon power usage""" if button == Button.left: self._internal_q.put("mouse") def _on_press(self, key: (Key, KeyCode)): """Process a key press to check for engine power usage""" if key == Key.space: self._internal_q.put(("Engine", datetime.now())) @property def string(self): """String to show in the Overlay""" self._lock.acquire() string = self._string self._lock.release() return string