我有一个在Windows中运行的使用psutil的Python 3.x程序。该程序的工作很简单-定期检查是否正在运行其他程序。如果找到程序,则不执行任何操作。如果找不到该程序,它将启动该程序。然后程序进入睡眠状态,并再次循环执行相同的操作。这是代码的最低版本:
import psutil, os, time
found = 0
theprogram = 'hiimaprogram.exe'
while True:
for process in psutil.process_iter():
if process.name() == theprogram: # this is line 14
found = 1
print ('process found, doing nothing')
if found == 0:
print ('process not found, starting the process')
filepath = theprogram
os.startfile(filepath)
found = 0
time.sleep(10)
print ('sleeping')
continue
该代码可以很好地完成工作。但是,它有时也会随机失败,永远不会立即消失,通常会在8小时大关出现,尽管有时它会存活更长的时间。这是回溯:
Traceback (most recent call last):
File "site-packages\psutil\_pswindows.py", line 707, in wrapper
File "site-packages\psutil\_pswindows.py", line 791, in exe
PermissionError: [WinError 5] Access is denied
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "site-packages\psutil\_pswindows.py", line 782, in name
File "site-packages\psutil\_pswindows.py", line 709, in wrapper
psutil.AccessDenied: psutil.AccessDenied (pid=31216)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "site-packages\psutil\_pswindows.py", line 707, in wrapper
File "site-packages\psutil\_pswindows.py", line 784, in name
ProcessLookupError: [Errno 3] No such process
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "programchecker.py", line 14, in <module>
File "site-packages\psutil\__init__.py", line 731, in name
File "site-packages\psutil\_pswindows.py", line 709, in wrapper
psutil.NoSuchProcess: psutil.NoSuchProcess process no longer exists (pid=31216)
代码中标记了进程死亡的第14行。对于我来说,编写一个try / except来忽略该错误足够容易,但是我真的很想知道为什么会这样。尝试/除外代码:
while True:
for process in psutil.process_iter():
try:
if process.name() == theprogram: # this is line 14
found = 1
print ('process found')
except:
print ('error')
time.sleep(100)
continue
阅读psutil和其他有相同错误(但由于不同原因)的人,我发现适合我的情况是我需要处于管理员模式,但在管理员模式下运行程序似乎没有帮助完全不同,并且仍然显示相同的错误。我想到的另一件事是,由于睡眠/休眠,某些自动Windows进程可能会在八个小时的时间受到干扰,但是我已确保计算机处于“始终开启”的电源方案,其中不应有任何干扰(至少理论上)。任何帮助表示赞赏,谢谢!
我找到了解决方案,这完全是荒谬的,但事实确实如此。
我的程序正在检查其是否存在的实际程序具有内置的“安全功能”,即使该程序处于活动状态并正在使用,它也会在8小时标记后强制自己超时。这直接来自该程序的开发人员。疯了,我知道。添加上述try / except可以解决此问题,睡眠超时100足以使主程序停止关心并重置时钟。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句