[英]How to terminate one python script when many python scripts are running?
大家好,我已經打開了 3 個同時運行的 python 腳本。 我想用其他 python 文件終止(殺死)其中一個。 這意味着如果我們同時運行許多 python 腳本,如何終止或殺死其中一個或兩個? 是否可以使用 os 或 subprocess 模塊? 我嘗試使用它們,但它們殺死了所有 python 腳本並殺死了 python.exe
FirstSc.py
UserName = input("Enter your username = ")
if UserName == "Alex":
#Terminate or Kill the PythonFile in this address C:\MyScripts\FileTests\SecondSc.py
SecondSc.py
while True:
print("Second app is running ...")
第三個Sc.py
while True:
print("Third app is running ...")
謝謝大家,我得到了很好的答案。 現在,如果我們有一個像 SecBatch.bat 而不是 SecondSc.py 這樣的批處理文件,該怎么做。 這意味着我們擁有這些並同時運行 FirstSc.py 和 SecBatch.bat:
此目錄中的 FirstSc.py D:\MyFiles\FirstSc.py
UserName = input("Enter your username = ")
if UserName == "Alex":
#1)How to print SecBatch.bat syntax it means print:
#CALL C:\MyProject\Scripts\activate.bat
#python C:\pyFiles\ThirdSc.py
#2)Terminate or kill SecBatch.bat
#3)Terminate or kill ThirdSc.py
SecBatch.bat in this directory C:\MyWinFiles\SecBatch.bat that it run a Python VirtualEnvironment then run a python script in this directory C:\pyFiles\ThirdSc.py
CALL C:\MyProject\Scripts\activate.bat
python C:\pyFiles\ThirdSc.py
這個目錄下的ThirdSc.py C:\pyFiles\ThirdSc.py
from time import sleep
while True:
print("Third app is running ...")
sleep(2)
我會將每個腳本的 PID 存儲在標准位置。 假設您在 Linux 上運行,我會將它們放在/var/run/
中。 然后你可以使用os.kill(pid, 9)做你想做的事。 一些示例輔助函數將是:
import os
import sys
def store_pid():
pid = os.getpid()
# Get the name of the script
# Example: /home/me/test.py => test
script_name = os.path.basename(sys.argv[0]).replace(".py", "")
# write to /var/run/test.pid
with open(f"/var/run/{script_name}.pid", "w"):
f.write(pid)
def kill_by_script_name(name):
# Check the pid file is there
pid_file = f"/var/log/{name}.pid"
if not os.path.exists(pid_file):
print("Warning: cannot find PID file")
return
with open(pid_file) as f:
# The following might throw ValueError if pid file has characters
pid = int(f.read().strip())
os.kill(pid, 9)
后來在FirstSc:
if UserName == "Alex":
kill_by_script_name("SecondSc")
kill_by_script_name("ThirdSc")
注意:代碼未經測試:)但應該指向正確的方向(至少對於解決此問題的一種常用方法)
您可以使用taskkill
等系統命令(或 Linux 系統上的pkill
)通過腳本文件的名稱終止 Python 進程。 但是,完成此操作的更好方法是(如果可能)讓FirstSc.py
或任何執行殺戮的腳本使用subprocess.Popen()
啟動其他腳本。 然后你可以在它上面調用terminate()
來結束進程:
import subprocess
# Launch the two scripts
# You may have to change the Python executable name
second_script = subprocess.Popen(["python", "SecondSc.py"])
third_script = subprocess.Popen(["python", "ThirdSc.py"])
UserName = input("Enter your username = ")
if UserName == "Alex":
second_script.terminate()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.