0

我正在寻找相当于以下内容的python:

until python program.py; do 
    echo "Crashed...Restarting..." >&2
    sleep 1
done

另外,当父程序被杀死时,我需要杀死 program.py。有什么建议么?

4

3 回答 3

0

模块subprocesspsutil应该提供您需要的大部分(如果不是全部)。

import sys, subprocess
while True :
    retCode= subprocess.call(["python","program.py"])
    if retCode == 0 : break
    print('Crashed...Restarting...', file=sys.stderr )
于 2013-08-22T21:58:57.203 回答
0
#!/usr/bin/python

import os
import signal
import subprocess
import sys
import time

Proc = None

def signal_handler(sig, frame):
   ''' Kill the program '''
   os.kill(Proc.pid, sig)
   sys.exit(0)

def main():
   global Proc
   ''' Handle signal on parent program ''' 
   signal.signal(signal.SIGTERM, signal_handler)
   signal.signal(signal.SIGINT, signal_handler)

   Proc = subprocess.Popen(['python', 'program.py'], 
                          stdout=subprocess.PIPE, stderr=subprocess.PIPE)
   while True:
        try:
           wait = Proc.wait()
           if wait:
                if wait != (-1 * signal.SIGKILL):
                    print "Restarting ....(return code %d)" % wait
                    time.sleep(1)
                    Proc = subprocess.Popen(['python', 'program.py'], 
                                            stdout=subprocess.PIPE,  
                                            stderr=subprocess.PIPE)
                else:
                   ''' kill yourself '''
                   sys.exit(0)
        except KeyboardInterrupt:
            # If python >= 2.6 
            # Proc.kill()
            sys.exit(0)

if __name__ == '__main__':
    main()
于 2013-08-23T00:04:02.370 回答
0

如果您可以更改program.py,我会对其进行修改,以便您可以直接调用它,而不是在子进程中调用它。如果您的程序遵循仅包含定义和仅在直接调用时才执行的最终可执行部分的约定,即它看起来像

def do_something():
  pass

def do_something_else():
  pass

if __name__ == '__main__':
  do_something()
  do_something_else()

将最后一个块包装在一个函数中就足够了,例如

def main():
  do_something()
  do_something_else()

if __name__ == '__main__':
  main()

此时您可以只导入您的program.py模块并调用program.main(),使您的代码更简单。

于 2013-08-23T07:25:53.103 回答