【问题标题】:How to execute a bash script from within python in a non-blocking way, and allowing to see its output?如何以非阻塞方式从 python 中执行 bash 脚本,并允许查看其输出?
【发布时间】:2020-01-28 16:17:58
【问题描述】:

在 Ubuntu Linux 系统上,我想从 python 脚本中启动 bash 脚本。我需要以非阻塞方式运行它,以便 python 脚本将 bash 脚本的所有输出报告到标准输出。

我发现了一个非常相似的问题here(当然)对我不起作用。这是我的 bash 脚本testbash.sh,它只打印一行数字:

#!/bin/bash
i=0

while [ $i -le 10 ]
do
  echo Number: $i
  ((i++))
  sleep 1
done

这是python脚本:

import sys
import time
from subprocess import PIPE, Popen
from threading  import Thread

try:
    from queue import Queue, Empty
except ImportError:
    from Queue import Queue, Empty  # python 2.x


ON_POSIX = 'posix' in sys.builtin_module_names

def enqueue_output(out, queue):
    for line in iter(out.readline, b''):
        queue.put(line)
    out.close()

p = Popen(['.','testbash.sh'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX, shell=True)
q = Queue()
t = Thread(target=enqueue_output, args=(p.stdout, q))
t.daemon = True # thread dies with the program
t.start()

# read line without blocking
running = True
while running:
    time.sleep(1)
    try:
        line = q.get_nowait() # or q.get(timeout=.1)
    except Empty:
        print('no output yet')
    else:
        # got line
        print(line)

运行此脚本时,我只得到输出“还没有输出”,并且没有来自 bash 脚本的实际输出。

只要 bash 脚本运行,我希望 python 脚本运行,将 bash 脚本的输出重定向到 python 标准输出(这样我每隔 1-2 秒就会看到数字 1..10) ,大约 10 秒后,python 脚本停止。我还需要检查 bash 脚本是否正常完成或出现错误

我错过了什么?脚本真的在运行吗?如何获得它的输出?如何查看退出代码?

【问题讨论】:

  • 我不确定,但在 bash 中使用 sleep 命令可能会更好
  • 我愿意吗?我也更新了问题
  • 试试Popen(['./testbash.sh','testbash.sh'],... 或者干脆Popen('./testbash.sh',... 第一个参数是要运行的程序。您的原始程序尝试运行'.',这是当前目录。

标签: python linux bash


【解决方案1】:

需要做一些改动,特别是shell脚本的调用:

import sys
import time
from subprocess import PIPE, Popen
from threading  import Thread

try:
    from queue import Queue, Empty
except ImportError:
    from Queue import Queue, Empty  # python 2.x


ON_POSIX = 'posix' in sys.builtin_module_names

def enqueue_output(out, queue):
    for line in iter(out.readline, b''):
        queue.put(line.decode('ascii'))
    out.close()

p = Popen(['./testbash.sh'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX, shell=True)
q = Queue()
t = Thread(target=enqueue_output, args=(p.stdout, q))
t.daemon = True # thread dies with the program
t.start()

# read line without blocking
while t.is_alive():
    time.sleep(1)
    try:
        line = q.get_nowait() # or q.get(timeout=.1)
    except Empty:
        print('no output')
    else:
        # got line
        print(line, end='')

p.wait()
print(f'returncode = {p.returncode}')

【讨论】:

  • 非常感谢修复 - 有没有办法获得 bash 脚本的退出状态?
  • 更新,最后
猜你喜欢
  • 2011-10-03
  • 1970-01-01
  • 1970-01-01
  • 2011-05-09
  • 1970-01-01
  • 1970-01-01
  • 2016-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多