python - Python - atexit | 在进程退出时计算函数关键字参数内的全局时间
问题描述
我用def foo(time = calculate_time()): ...
的时候,参数( time
)是0
我想,关键字参数分配或 atexit 是与主进程不同的进程,所以时间无关紧要
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)
请查看代码中的注释行,这是我的 KeyLogger 脚本:
示例问题案例:
- 运行python脚本
- 立即点击END按钮
- 执行时被零异常浮动
atexit.register(save_to_file)
- 线:
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()
解决方案
关键字参数的默认值是根据函数定义计算的,而不是在执行时计算的。
time.time
最多具有底层操作系统的精度。它正在尝试计算分配列表和定义函数所花费的时间,预计会向下舍入为零(需要微秒)。
只需将默认值更改为None
,函数内部的 if 将计算调用时的时间差。
推荐阅读
- missing-data - 纵向数据中缺失数据并通过线性混合模型拟合
- c++ - C2679 - 在函数中使用模板错误
- python - 如何检查数据框列中的值是否在另一个数据框的列中,分组依据
- java - 我如何“在特定位置返回该数据(如果存在)”
- java-stream - 可从可迭代观察到的 RxJava 并行执行
- css - 移动视图上的引导断点问题
- python - 在我的笔记本电脑屏幕上获取元素的坐标
- javascript - 为什么状态变量不更新 - React
- sql-server - 将按日期较早/较晚的最近相邻行返回到另一个表的日期
- excel - 如何在 Vba 中处理新窗口并切换到它