简体   繁体   English

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

[英]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.大家好,我已经打开了 3 个同时运行的 python 脚本。 I want to terminate(Kill) one of them with other python file.我想用其他 python 文件终止(杀死)其中一个。 It means if we run many python scripts at the same time how to terminate or kill one of them or two of them?这意味着如果我们同时运行许多 python 脚本,如何终止或杀死其中一个或两个? Is it possible with os or subprocess modules?是否可以使用 os 或 subprocess 模块? I try to use them but they kill all python scripts with killing python.exe我尝试使用它们,但它们杀死了所有 python 脚本并杀死了 python.exe

FirstSc.py 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 SecondSc.py

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

ThirdSc.py第三个Sc.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.现在,如果我们有一个像 SecBatch.bat 而不是 SecondSc.py 这样的批处理文件,该怎么做。 It means we have these and run FirstSc.py and SecBatch.bat at the same time:这意味着我们拥有这些并同时运行 FirstSc.py 和 SecBatch.bat:

FirstSc.py in this directory D:\MyFiles\FirstSc.py此目录中的 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 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这个目录下的ThirdSc.py 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.我会将每个脚本的 PID 存储在标准位置。 Assuming you are running on Linux I would put them in /var/run/ .假设您在 Linux 上运行,我会将它们放在/var/run/中。 Then you can use os.kill(pid, 9) to do what you want.然后你可以使用os.kill(pid, 9)做你想做的事。 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:后来在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).您可以使用taskkill等系统命令(或 Linux 系统上的pkill )通过脚本文件的名称终止 Python 进程。 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() .但是,完成此操作的更好方法是(如果可能)让FirstSc.py或任何执行杀戮的脚本使用subprocess.Popen()启动其他脚本。 Then you can call terminate() on it to end the process:然后你可以在它上面调用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.

相关问题 一个接一个地运行许多 python 脚本 - running many python scripts one after another Python 从一个运行多个脚本 - Python running many scripts from one 如何停止/终止 python 脚本的运行? - How to stop/terminate a python script from running? Python,多个脚本,每个都运行多个线程,一个脚本如何判断其他脚本中的线程何时结束? - Python, multiple scripts, each with multiple threads running, how can one script determine when threads in other scripts are finished? 用python脚本终止正在运行的应用程序 - To terminate the running application in python script 如何使用 python 同时多次运行 python 脚本并在完成后全部终止 - How to run a python script multiple times simultaneously using python and terminate all when one has finished 如何停止/终止 python 脚本与 APScheduler 的 BackgroundScheduler() 一起运行 - How to stop/terminate a python script from running with BackgroundScheduler() of APScheduler 如何停止/终止运行的python脚本? (再来一次) - How to stop/terminate a python script from running? (once again) 如何在python中终止正在运行的线程? - How to terminate a running Thread in python? 运行python脚本的Bash脚本 - Bash script running python scripts
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM