【问题标题】:Stopping a Process in Python在 Python 中停止进程
【发布时间】:2014-08-12 07:38:55
【问题描述】:

我正在运行一个我希望在按下某个按钮时停止的程序。

我正在考虑在后台运行该进程,以便在此过程中的任何时间都可以按下按钮并停止它。

我从文档中阅读了有关 subprocess 的内容,但我是初学者,我不知道如何使用它,感谢任何帮助。

def put(command):
        os.system(command)

        if direct == "":
            time.sleep(.5)
            arg1 = put("sudo ffmpeg -i \"" + q3 + "\" -f s16le -ar 22.05k -ac 1 - | sudo ./pifm - " + str(freq)) 
            subprocess.Popen(arg1)
            while True:
                if RPIO.input(25) == GPIO.LOW: #if button is pushed, kill process (arg1)
                    Popen.terminate()

【问题讨论】:

  • 你是想让python程序杀死其他进程,还是让它自己杀死?
  • Kill process by name in python 的可能重复项
  • @aruisdante 我正在尝试终止运行的 arg1 命令,运行它需要一段时间,并且我希望能够在按下按钮时停止它。感谢您的回复!

标签: python python-2.7 subprocess popen os.system


【解决方案1】:

您需要在 instance od Popen 上调用终止:

if direct == "":
    time.sleep(.5)
    arg1 = put("sudo ffmpeg -i \"" + q3 + "\" -f s16le -ar 22.05k -ac 1 - | sudo ./pifm - " + str(freq)) 
    myproc = subprocess.Popen(arg1)
    while True:
        if RPIO.input(25) == GPIO.LOW: #if button is pushed, kill process (arg1)
            myproc.terminate()

【讨论】:

    【解决方案2】:

    如果你想控制你的子进程,你最好使用subprocess 模块。如果您通过Popen 创建它,您将能够通过kill()terminate() 方法停止它。

    例子

    import subprocess
    # ...
    sub = subprocess.Popen(command)
    # ...
    sub.kill()
    

    而且你确定你是在杀死你自己的孩子,即使有许多command同时运行

    【讨论】:

      猜你喜欢
      • 2020-09-19
      • 2016-12-15
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多