Python-Atexit |中文在进程退出时计算函数关键字参数中的全局时间

时间:2019-06-25 17:12:11

标签: python python-3.x 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()

1 个答案:

答案 0 :(得分:1)

关键字参数的默认值是根据函数定义而不是执行时计算的。

time.time最多具有基础操作系统的精度。它正在尝试计算分配列表和定义函数所花费的时间,该时间预计会四舍五入为零(需要微秒)。

只需将默认值更改为None,函数内部的if就会计算调用它的时间差。