制作一个.py可执行文件,但是os库不起作用

时间:2020-05-25 15:11:41

标签: python python-3.x windows cmd pyinstaller

我用Pyinstaller创建Python脚本的.exe,这是一个在输入时间到时关闭您的PC的程序,但是当时间到时,他打印“计算机”将关闭但什么都没发生

import os
import sys
from datetime import datetime
from msvcrt import getch, kbhit
from time import sleep
def get_down(time):
    print('press ENTER to cancel \n')
    while True:
        if kbhit(): 
            key = ord(getch()) 
            if key == 13:
                print('You cancel the operation ')
                break

        if time == datetime.now().strftime('%H:%M'):
            print("The system is gonna turn off")
            os.system("shutdown /s /t 1")

print('Now is: {}'.format(datetime.now().strftime('%H:%M')))

1 个答案:

答案 0 :(得分:0)

我最初的理解是,您想运行一个脚本,该脚本将在指定时间关闭计算机,但是如果您选择在此之前不关机,则可以取消该脚本。

基于此,我对您的代码进行了一些修改。 所做的修改是,当您希望系统关闭时,您为关闭功能指定了一个日期时间。该功能可以计算出将来的秒数,然后休眠该时间。如果要取消,请按Ctrl + C取消。睡眠完成后,应该是计划的关机时间,因此我们执行shutdown命令。

我在函数中添加了grace_time参数,以便在测试PC时不会立即关机(这会使调试变慢)!

import os
from datetime import datetime, timedelta
from time import sleep


def shutdown_system(time: datetime, grace_time: int = 30):
    """
    :param time: time the system should be shut down
    :param grace_time: grace time before the shutdown command executes
    """
    # calculate the scheduled shutdown time in seconds
    sleep_time = (time - datetime.now()).total_seconds()

    print("System scheduled to shutdown at {}".format(time.isoformat()))
    print("Press Ctrl+C to cancel")

    try:
        # sleep the program for the time until the shutdown is scheduled
        sleep(sleep_time)
    except KeyboardInterrupt:
        # a Ctrl+C will trigger this
        print("You cancelled the shutdown!")
        # return so shutdown doesn't continue
        return

    # Execute the shutdown command
    print("The system is going to shutdown in {} seconds".format(grace_time))
    os.system("shutdown /s /t {}".format(grace_time))

if __name__ == "__main__":
    now = datetime.now()
    shutdown_system(now + timedelta(seconds=1))