4

我需要从另一个执行另外两个 python 脚本。命令如下所示:

# python 发送.py

# python 等待.py

这将在一个循环中发生,该循环将休眠 1 分钟然后重新运行。

在执行命令以启动其他脚本之前,我需要确保它们没有仍在运行。

4

2 回答 2

18

您可以使用subprocess.Popen来做到这一点,例如:

import subprocess

command1 = subprocess.Popen(['command1', 'args1', 'arg2'])
command2 = subprocess.Popen(['command2', 'args1', 'arg2'])

如果您需要检索输出,请执行以下操作:

command1.wait()
print command1.stdout

示例运行:

sleep = subprocess.Popen(['sleep', '60'])
sleep.wait()
print sleep.stdout  # sleep outputs nothing but...
print sleep.returncode  # you get the exit value
于 2012-09-26T15:45:18.147 回答
1
import time
import commands
from subprocess import Popen

while True:
  t_ph = commands.getstatusoutput('ps -eo pid,args | grep script1.py | grep -v service | grep -v init.d | grep -v grep | cut -c1-6')
  t_fb = commands.getstatusoutput('ps -eo pid,args | grep script2.py | grep -v service | grep -v init.d | grep -v grep | cut -c1-6')

  if t_ph[1] == '':
    r_ph = Popen(["python", "script1.py"])

  if t_fb[1] == '':
    r_fb = Popen(["python", "script2.py"])

  time.sleep(60)

或者

import time
import commands
from subprocess import Popen

r_ph = False
r_fb = False

while True:

  if r_ph == False:
    r_ph = Popen(["python", "script1.py"])
  else:
    if r_ph.poll():
      r_ph = Popen(["python", "script1.py"])

  if r_fb == False:
    r_fb = Popen(["python", "script2.py"])
  else:
    if r_fb.poll():
      r_fb = Popen(["python", "script2.py"])

  time.sleep(60)

这可以写得更好一点,但它的工作原理

于 2012-09-26T16:50:58.070 回答