如何从另一个python代码中终止bash代码中的无限while循环?

问题描述 投票:0回答:1

想象下面的无限循环:

#!/bin/bash
i=0
while true; do
   echo $i
   i=$((i+1))
done

我从这样的python代码运行此代码:

def start(self):
  filepath = '/home/sysop/.seiscomp3/program.sh'
  if os.path.exists(filepath):
     Command = "gnome-terminal -e '/home/alireza/.seiscomp3/program.sh'"
     proc = subprocess.Popen(['bash','-c', Command])
  else:
     print ("The executable file is missing. Check ~/.seiscomp3 directory ...")
def stop(self):
   proc.terminate()

上面的python代码适用于另一个程序(让我们称之为SC3)并在新终端中启动/停止上述bash代码。当我运行SC3程序时,它应该在上面的python代码中运行“start”函数。(工作正常)。但问题在于stop函数应该杀死在子进程中运行的bash代码。我的问题是如何终止这个新终端及其流程?

python-3.x infinite-loop terminate
1个回答
0
投票

您目前正在开始额外的流程,这会阻碍Popen返回正确的流程。

如果可能,跑步

proc = subprocess.Popen(['bash', '/home/alireza/.seiscomp3/program.sh'])

应该更直接,让你捕捉正确的过程,这将使答案的其余部分有用。


鉴于您将self传递给启动和停止函数,它使我相信这些是对象上的方法。如果您可以在新字段下存储在该对象中创建的进程的句柄,则可以将其拉出以用于stop函数。


def start(self):
    filepath = '/home/sysop/.seiscomp3/program.sh'

    # Just in case the path doesn't exist
    self.proc = None

    if os.path.exists(filepath):
        Command = "gnome-terminal -e '/home/alireza/.seiscomp3/program.sh'"

        # Assign to the internal field proc
        self.proc = subprocess.Popen(['bash','-c', Command])
    else:
        print ("The executable file is missing. Check ~/.seiscomp3 directory ...")

def stop(self):
    # Make sure that the object has the proc field (It should if it has been started.)
    # AND
    # Only try to terminate if there is a process running
    if('proc' in dir(self) and self.proc):
        self.proc.terminate()

如果它们不是方法,则可以从start函数返回proc并将其传递给stop函数。


start():
    # Do stuff
    return proc

stop(proc):
    proc.terminate()
© www.soinside.com 2019 - 2024. All rights reserved.