Break time.sleep() After Collecting Data - python

Here's my code:
from threading import Thread
from time import sleep
from msvcrt import getch
key = 0
def ProcessKey(key):
if key == 97:
return 1
elif key == 32:
return 2
elif key == 13:
return 3
else:
return 0
def Check():
sleep(2)
if key != 0:
return
Thread(target = Check()).start()
key = ord(getch())
print(ProcessKey(key))
The timed input works fine in cutting someone off from entering input but if someone enters input in time I have to wait the full 2 seconds before the next line of code is executed. How can I skip the rest of the 2 seconds after someone enters input?

from threading import Thread
from time import sleep
from msvcrt import getch
key = 0
def ProcessKey(key):
if key == 97:
return 1
elif key == 32:
return 2
elif key == 13:
return 3
else:
return 0
def Check():
sleep(2)
if key != 0:
return
Thread(target = Check).start() ##Dont call the function just enter the name I think this will solve
key = ord(getch())
print(ProcessKey(key))

Related

Keylogger not logging keys to txt file

I recently started coding using Python and I'm trying to create a simple keylogger.
However the keys I pressed do not get logged into the actual txt file.
Heres the code :
import pynput
from pynput.keyboard import Key, Listener
count = 0
keys = []
def pressed(key):
global keys, count
keys.append(key)
count += 1
print("{0} pressed".format(key))
if count >= 10:
count = 0
write_file(keys)
keys = []
def write_file(keys):
with open ('Keylogger\log.txt', 'a') as f:
for key in keys:
k = str(key).replace("'","")
if k.find("space") > 0:
f.write('\n')
elif k.find("Key") == -1:
f.write(k)
def released(key):
if key == Key.esc:
return False
with Listener(on_press=pressed, on_release=released) as listener:
listener.join()
I would greatly appreciate any help!

Keylogger no longer saves test in textfile

I made my first keylogger in Python and it was showing each keystroke to the designated text log awhile back, but now it isn't working for some reason. I want to understand why?
import pynput
from pynput.keyboard import Key, Listener
count = 0
keys = []
def on_press(key):
global keys, count
keys.append(str(key))
count += 1
print("{0} pressed".format(key))
if count >= 10:
count = 0
write_file(keys)
keys = []
def write_file(keys):
with open("alltexts", "a") as f:
for key in keys:
k = str(key).replace("'"," ")
if k.find("space") > 0:
f.write('\n')
elif k.find("Key") == -1:
f.write(k)
def on_release(key):
if key == Key.esc:
return False
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()

How can I check for a key press at any point during a loop?

I am trying to make a timer that counts down to 0, then starts counting up. I am using the time and keyboard modules.
The keyboard module from PyPi.
Everything works as expected, and I am able to press a button to close the program, but it only works at the beginning of each iteration. Is there a way for it to check for a key press at any point while the loop is running? Do I need to be using a different module?
This is my code:
import time
import keyboard
m = 2
s = 0
count_down = True
while True:
if keyboard.is_pressed('q'):
break
print(f"{m} minutes, {s} seconds")
if count_down:
if s == 0:
m -= 1
s = 60
s -= 1
elif not count_down:
s += 1
if s == 60:
m += 1
s = 0
if m == 0 and s == 0:
count_down = False
time.sleep(1)
Using callback is common approach in such case, here is solution:
import time
import keyboard
m = 2
s = 0
count_down = True
break_loop_flag = False
def handle_q_button():
print('q pressed')
global break_loop_flag
break_loop_flag = True
keyboard.add_hotkey('q', handle_q_button)
while True:
if break_loop_flag:
break
print(f"{m} minutes, {s} seconds")
if count_down:
if s == 0:
m -= 1q
s = 60
s -= 1
elif not count_down:
s += 1
if s == 60:
m += 1
s = 0
if m == 0 and s == 0:
count_down = False
time.sleep(1)
If you want to do any two things in parallel, independently of another, you need to consider using multiprocessing. However, even if you do, your loop will either still need to check if a key has been registered in the other process, or you need to terminate the process running the loop forcefully, which may result in unexpected outcomes.
However, in your case, since there are no side effects like files being written, this would work:
import time
import keyboard
from multiprocessing import Process
def print_loop():
m = 2
s = 0
count_down = True
while True:
print(f"{m} minutes, {s} seconds")
if count_down:
if s == 0:
m -= 1
s = 60
s -= 1
elif not count_down:
s += 1
if s == 60:
m += 1
s = 0
if m == 0 and s == 0:
count_down = False
time.sleep(1)
def main():
p = Process(target=print_loop)
p.start()
# this loop runs truly in parallel with the print loop, constantly checking
while True:
if keyboard.is_pressed('q'):
break
# force the print loop to stop immediately, without finishing the current iteration
p.kill()
if __name__ == '__main__':
main()

Terminate loop at any given time

I have the following code which turns an outlet on/off every 3 seconds.
start_time = time.time()
counter = 0
agent = snmpy4.Agent("192.168.9.50")
while True:
if (counter % 2 == 0):
agent.set("1.3.6.1.4.1.13742.6.4.1.2.1.2.1.1",1)
else:
agent.set("1.3.6.1.4.1.13742.6.4.1.2.1.2.1.1", 0)
time.sleep(3- ((time.time()-start_time) % 3))
counter = counter + 1
Is there a way I can have the loop terminate at any given point if something is entered, (space) for example... while letting the code above run in the mean time
You can put the loop in a thread and use the main thread to wait on the keyboard. If its okay for "something to be entered" can be a line with line feed (e.g., type a command and enter), then this will do
import time
import threading
import sys
def agent_setter(event):
start_time = time.time()
counter = 0
#agent = snmpy4.Agent("192.168.9.50")
while True:
if (counter % 2 == 0):
print('agent.set("1.3.6.1.4.1.13742.6.4.1.2.1.2.1.1",1)')
else:
print('agent.set("1.3.6.1.4.1.13742.6.4.1.2.1.2.1.1", 0)')
if event.wait(3- ((time.time()-start_time) % 3)):
print('got keyboard')
event.clear()
counter = counter + 1
agent_event = threading.Event()
agent_thread = threading.Thread(target=agent_setter, args=(agent_event,))
agent_thread.start()
for line in sys.stdin:
agent_event.set()

python memory leak listening to /dev/input

This is a loop I'm using to listen in on a barcode scanner.
I have up to 8 instances of this program running at the same time one for each scanner. Although I'm getting the desired results for a while, each process eventually uses up a ton of cpu and memory. Any ideas why?
#!/usr/bin/env python
import os, sys
from evdev import InputDevice
from select import select
...
self.dev = InputDevice(self.devRoot + self.scanner['by-id'])
...
def process(self):
badge = ''
while True:
r,w,x = select([self.dev], [], [])
try:
for event in self.dev.read():
if event.type == 1 and event.value != 4:
if event.code < 11 and event.code > 0:
# for numbers 1 to 9
code = event.code - 1
badge = badge + str(code)
elif event.code == 11:
# for number 0
badge = badge + '0'
elif event.code == 28:
theBadge = badge[::2].strip()
if len(theBadge) == 5:
fn = self.genFileName(theBadge)
self.touch(fn)
# reset the badge
badge = ''
else:
# grab a letter or character from the key dictionary
code = int(event.code)
badge += self.deviceDict.keyDict[code]
except Exception as e:
continue
def genFileName(self, badge):
return str(self.scannerNum) + '-' + badge
def touch(self, filename):
TESTING = True
if len(filename) <= 2:
return 1
filePath = self.scanDir + filename
touchCommand = 'touch ' + filePath
os.system(touchCommand)
return

Categories