【问题标题】:Python subprocess shell scripts still runs in backgroundPython 子进程 shell 脚本仍然在后台运行
【发布时间】:2021-09-01 13:39:15
【问题描述】:

我正在使用子进程运行两个 python 脚本,其中一个仍在运行。

import subprocess
subprocess.run("python3 script_with_loop.py & python3 scrip_with_io.py", shell=True)

script_with_loop 仍然在后台运行。

如果其中一个脚本死亡,如何杀死两个脚本?

【问题讨论】:

  • "如果其中一个死了",如果认为更正确的说法是其中之一finishes its taskis done
  • 所以你想在script_with_io完成后杀死script_with_loop
  • @alexzander 是的,这是真的......线程解决方案和使用下面的语句对我有用。

标签: python python-3.x subprocess


【解决方案1】:

所以,你在这里基本上不是在使用 python,而是在使用你的 shell。

a & b 运行 a,拒绝它,然后运行 ​​b。由于您使用的是 shell,如果您想终止后台任务,则必须使用 shell 命令来执行此操作。

当然,既然你用的是python,那还有更好的办法。

with subprocess.Popen(["somecommand"]) as proc:
  try:
    subprocess.run(["othercommand"])
  finally:
    proc.terminate()

查看您的代码 - python3 script_with_loop.pypython3 script_with_io.py - 我猜您最好使用 asyncio 模块,因为它基本上完成了这两个文件的名称所描述的内容。

【讨论】:

    【解决方案2】:

    你应该对这类事情使用线程。试试这个。

    import threading
    
    def script_with_loop():
        
        try:
            # script_with_loop.py code goes here
        except:
             _exit()
    
    
    def script_with_io():
        
        try:
            # script_with_io.py code goes here
        except:
             _exit()
    
    
    threading.Thread(target=script_with_loop, daemon=True).start()
    threading.Thread(target=script_with_io, daemon=True).start()
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 2015-08-19
      • 2013-10-14
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多