繁体   English   中英

当许多 python 脚本正在运行时,如何终止一个 python 脚本?

[英]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.

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