アプリケーションが終了したら、プロセスを適切に強制終了する方法はありますか?はいの場合、これをPythonスクリプトに統合して、終了した場合に自動的にジョブを実行するにはどうすればよいですか?アプリが壊れたときにアプリを再起動するためにこのコードを取得しましたが、プロセスがまだバックグラウンドで実行されているため、機能しません。乾杯
proccess = 'app'
def checkIfProcessRunning(process):
'''
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 process.lower() in proc.name().lower():
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return False
def ex():
os.system('TASKKILL /F /IM Trailling.exe')
#atexit.register(ex)
def start_process():
return os.system(cmd)
try:
start_process()
atexit.register(ex)
while True:
if checkIfProcessRunning('process'):
print("Process is running")
time.sleep(5)
else:
print("Process is not running")
start_process()
except Exception as e:
print(e)
プログラムの任意の終了ポイントで、プロセスを強制終了する関数を追加するだけです。プロセスが実行されているかどうかはすでに確認しており、同じインターフェイスを使用してプロセスを強制終了できます。
またはを返すcheckIfProcessRunning
代わりに、に変更することをお勧めします。プロセスが存在する場合はそれを返し、そうでない場合は戻ります。True
False
None
def checkIfProcessRunning(process):
'''
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 process.lower() in proc.name().lower():
return proc
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return None
これは引き続きif
チェックで機能するはずであり(デフォルトでは、None
オブジェクト以外のレジスタはすべてtrueとして登録されます)、プロセスの.kill()
メソッドを使用してkillメソッドを作成するのがはるかに簡単になります。
def killProcessIfRunning(process):
'''
Kill the process, if it's running.
'''
proc = checkIfProcessRunning(process)
if proc:
proc.kill()
# alternatively, use proc.terminate() if you want to be more hardcore and are not on Windows
# or proc.send_signal() with SIGSTOP or something
次に、プログラムの任意の出口ポイントでkillメソッドを呼び出すだけです(使用したatexit
ので、これはex()
関係なくメソッドである必要があります)。
def ex():
killProcessIfRunning('process') # replace with the name of the same process you started with
os.system('TASKKILL /F /IM Trailling.exe')
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加