【问题标题】:python execute shell command and continue without waiting and check if running before executingpython执行shell命令并继续而不等待并在执行前检查是否运行
【发布时间】:2012-09-18 06:54:19
【问题描述】:

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

#python send.py

#python wait.py

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

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

【问题讨论】:

  • 您是否尝试过使用子流程模块?
  • 为什么不能import这两个脚本并正常调用里面的函数呢?
  • 因为这两个应用程序会在某个时候用不同的语言重写。
  • 子进程似乎要等待应用程序完成才能继续。我需要执行并继续前进。
  • @larsmans,如果您不明确使用 Popen,它确实如此。

标签: python shell command-line


【解决方案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)

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • stdout 仅在将stdout=subprocess.PIPE 传递给Popen 构造函数时才有意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 2020-06-14
    • 1970-01-01
    • 2014-12-14
    • 2012-08-13
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多