首页 > 解决方案 > Python While循环在一段时间后挂起,按下(Enter)时继续?

问题描述

我编写了一个 python 脚本并转换为 python exe,它每秒打印应用程序名称和时间。还添加了一个每 30 秒运行一次的计划功能。

一小时后,当我再次检查时,它工作得很好,python 脚本被暂停(或挂起)。当我按下 [Enter] 时,它又像往常一样开始执行。该脚本运行良好 1 小时。暂停的原因是什么?

我的代码

    from win32gui import GetForegroundWindow
    import psutil
    import time, os, datetime, requests, json, schedule
    import win32process
    import csv
    import getpass

data = {}
process_time = {}
timestamp = {}

data['User'] = getpass.getuser()
data['Date'] = datetime.datetime.now().strftime("%d/%m/%Y")
data['Time'] = datetime.datetime.now().strftime("%I:%M %p")


def show_name():
    l = []
    for a, t in process_time.items():
        e = {}
        e['AppName'] = a
        e['Time'] = t
        l.append(e)
    data["Data"] = l
    
    data=json.dumps(data))
    print(data)



schedule.every(30).seconds.do(show_name)

while True:
    try:
        current_app = psutil.Process(win32process.GetWindowThreadProcessId(GetForegroundWindow())[1]).name().replace(".exe", "")
        timestamp[current_app] = int(time.time())
        time.sleep(1)
        if current_app not in process_time.keys():
            process_time[current_app] = 0
        process_time[current_app] = process_time[current_app]+int(time.time())-timestamp[current_app]

        print(process_time)

        schedule.run_pending()
        time.sleep(1)

        service_directory = os.path.abspath(os.path.dirname(__file__)) + '/test1.csv'
        with open(service_directory, 'w', encoding='UTF8', newline='') as f:
            for key in process_time.keys():
                f.write("%s,%s\n"%(key, process_time[key]))
    except:
        pass

标签: pythonpowershellwhile-loop

解决方案


推荐阅读