尝试制作简单的计时器以在 python 中关闭 windows

Trying to make simple timer to shutdown windows in python

试图让简单的定时器在 python 中关闭 windows(只是为了好玩)但是我有一个小问题找不到答案,脚本只是询问是否用户想要使用分钟或秒来使用 if 关闭,使用秒的部分工作正常,问题是分钟,脚本以分钟为单位获取时间并转换为秒,然后运行:subprocess.call([ "shutdown" "-s", "-t", ntime])

但它不起作用,如果我双击 file.py 并尝试这部分,脚本就会关闭,但如果在 IDLE 中执行,我会收到此错误:

Traceback (most recent call last):
  File "C:\Users\User\Desktop\shutdown.py", line 17, in <module>
    subprocess.call(["shutdown" "-s", "-t", ntime])
  File "F:\Programs\python\lib\subprocess.py", line 267, in call
    with Popen(*popenargs, **kwargs) as p:
  File "F:\Programs\python\lib\subprocess.py", line 709, in __init__
    restore_signals, start_new_session)
  File "F:\Programs\python\lib\subprocess.py", line 997, in  _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
>>>


Code:
import subprocess
print('0:Seconds')
print('1:Minutes')
minorsec = input('Want to use minutes or seconds? ')
if minorsec == '0':
    time = input('Type the time to shutdown in seconds: ')
    subprocess.call(["shutdown", "-s", "-t", time])
elif minorsec == '1':
    time = input('Type the time to shutdown in minutes: ')
    ntime = int(time) * 60
    subprocess.call(["c:\windows\system32\shutdown.exe" "-s", "-t", str(ntime)])
else:
    print('Error, Press just 0 or 1')
input('Press Enter to close: ') 

问题 #1:这一行

ntime = time * 60

并不像您认为的那样。 time,从之前的 input 调用返回的值是一个字符串,而不是一个整数。因此,如果用户键入“15”作为他的输入,ntime 会变成疯狂的东西,例如:“1515151515151515151515.....15”。这可能是您的核心问题:

将用户的输入从字符串转换回整数:

 ntime = int(time) * 60

问题 #2,这是修复 #1 的副作用:subprocess.call 的参数列表中的所有值都必须是字符串:

time = input('Type the time to shutdown in minutes: ')
ntime = int(time) * 60
subprocess.call(["shutdown" "-s", "-t", str(ntime)])

问题 #3:不要使用参数列表:

subprocess.call("shutdown.exe -s -t " + str(ntime))