python执行shell命令并继续而不等待,并在执行前检查是否正在运行

时间:2012-09-26 15:29:30

标签: python shell command-line

我需要从另一个执行另外两个python脚本。 命令看起来像这样:

#python send.py

#python wait.py

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

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

2 个答案:

答案 0 :(得分:9)

您可以使用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

答案 1 :(得分:0)

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)

这可以写得更好但是有效