【问题标题】:Running else loop once运行 else 循环一次
【发布时间】:2021-04-13 14:55:53
【问题描述】:

所以我有一个带有代码的脚本

import os
import subprocess
import psutil

def checkIfProcessRunning(processName):
'''
Check if there is any running process that contains the given name processName.
'''
#Iterate over the all the running process
for proc in psutil.process_iter():
    try:
        # Check if process name contains the given name string.
        if processName.lower() in proc.name().lower():
            return True
    except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
        pass
return False;

然后在执行之后

while True:
if checkIfProcessRunning('TDR'):
    print('TDR (tdr.exe) is running')
else:
    print('TDR (tdr.exe) is not running')
    subprocess.call("cmd /c data.vbs") # Executes other code

整个脚本检测进程 tdr.exe 是否打开,当代码检测到它未打开时,我希望它打开一些其他代码,但我希望它只做它一次而不是循环。

【问题讨论】:

  • 请修正你的代码缩进

标签: python loops psutil


【解决方案1】:

帮助我理解,这里的问题是在调用你的“其他代码”a.k.a data.vbs 之后继续执行它?在 subprocess.call("cmd /c data.vbs") 之后添加一个中断。 或者像这样构造它:

while True:
    if not checkIfProcessRunning('TDR'):
        break
    print('TDR (tdr.exe) is running')

# Once we find TDR is dead, we execute our other code
print('TDR (tdr.exe) is not running')
subprocess.call("cmd /c data.vbs") # Executes other code

我希望这会有所帮助:D

【讨论】:

  • 我尝试了你的技巧并替换了代码,但运行后我得到了错误TypeError: checkIfProcessRunning() missing 1 required positional argument: 'processName'
  • 看来您确实在没有传递任何参数的情况下调用了 checkIfProcessRunning。
猜你喜欢
  • 2018-05-02
  • 2014-12-18
  • 1970-01-01
  • 2018-06-25
  • 1970-01-01
  • 2011-11-02
  • 2013-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多