简体   繁体   中英

How to terminate one python script when many python scripts are running?

Hello guys I have opened 3 python scripts that they are running at the same time. I want to terminate(Kill) one of them with other python file. It means if we run many python scripts at the same time how to terminate or kill one of them or two of them? Is it possible with os or subprocess modules? I try to use them but they kill all python scripts with killing 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 ...")

ThirdSc.py

while True:
    print("Third app is running ...")

Thanks guys I get good answers. Now if we have a Batch file like SecBatch.bat instead of SecondSc.py how to do this. It means we have these and run FirstSc.py and SecBatch.bat at the same time:

FirstSc.py in this directory 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 in this directory C:\pyFiles\ThirdSc.py

from time import sleep
while True:
    print("Third app is running ...")
    sleep(2)

I would store the PID of each script in a standard location. Assuming you are running on Linux I would put them in /var/run/ . Then you can use os.kill(pid, 9) to do what you want. Some example helper funcs would be:

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)

Later in FirstSc:

if UserName == "Alex":
    kill_by_script_name("SecondSc")
    kill_by_script_name("ThirdSc")

NOTE: The code is not tested:) but should point to you to the correct direction (at least for one common way to solve this problem)

You may be able to terminate a Python process by the name of the script file using system commands such as taskkill (or pkill on Linux systems). However, a better way to accomplish this would be (if possible) to have FirstSc.py or whatever script that's doing the killing launch the other scripts using subprocess.Popen() . Then you can call terminate() on it to end the process:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM