When I used def foo(time = calculate_time()): ...
, the parameters (time
) is 0
I suppose that, keyword argument assignment or atexit is different process than main process, so time is irrelevant
from time import time as get_time()
start_time = get_time() # Calculated at the time the application starts
def calculate_time():
global start_time
return get_time() - start_time
...
# Set the function which executed on exit
atexit.register(save_to_file)
Plese look at comment lines in the code which is my KeyLogger script:
Sample problematic case:
- Run python script
- Immediatly click END button
- Floated by zero exception while executing
atexit.register(save_to_file)
- Line:
lines.append(f"Saniye başı tuş basımı (key/s): {len(pressedKeys) / passing_time}")
from pynput import keyboard
import atexit
from time import time as get_time
from datetime import datetime
LOG_FILE = "keyLog.txt"
DELIM = "|"
TIME_LIMIT = 20 * 60
start_time = get_time()
pressedKeys = []
def calculate_time():
global start_time
return get_time() - start_time
# Why calculate_time() returns 0 🤔
def save_to_file(passing_time = calculate_time()):
global pressedKeys
if passing_time is None:
passing_time = calculate_time() # Why calculate_time() doesn't return 🤔
with open(LOG_FILE, "a+", encoding="utf-8") as file:
lines = []
lines.append(f"\n\n\n\n")
lines.append(f"Tarih (Yıl-Ay-Gün Saat-Dakika-Saniye.): {datetime.now()}")
lines.append(f"Geçen süre (s): {passing_time}")
lines.append(f"Basılan karakter: {len(pressedKeys)}")
lines.append(f"Saniye başı tuş basımı (key/s): {len(pressedKeys) / passing_time}")
lines.append(f"\n")
lines.append("|".join(pressedKeys))
file.write("\n".join(lines))
# Set the function which executed on exit
atexit.register(save_to_file)
# Kill process when 'END' is clicked
def on_press(key):
global pressedKeys
char = None
try:
char = key.char
except AttributeError:
char = str(key)
pressedKeys.append(char)
time = calculate_time()
if time > TIME_LIMIT:
save_to_file(time)
def on_release(key):
print("")
if key == keyboard.Key.end:
# Stop listener
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
The default value of a keyword argument is calculated upon function definition, not when it is executed.
time.time
have, at most, the precision of the underlying OS. It is trying to calculate the time it took to assign a list and define a function, this is expectedly rounded down to zero (takes microseconds).
Just change the default value to None
and the if inside your function will calculate the time difference for when it is called.