【问题标题】:Threaded subprocess read is not give any output线程子进程读取不给出任何输出
【发布时间】:2014-02-15 05:59:20
【问题描述】:

我有以下代码,并试图在 linux 的 Idle 中运行。

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

try:
    from Queue import Queue, Empty
except ImportError:
    from queue import Queue, Empty  # python 3.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(['youtube-dl', '-l', '-c', 'https://www.youtube.com/watch?v=utV1sdjr4PY'],   stdout=PIPE, bufsize=1, close_fds=ON_POSIX)

q = Queue()
t = Thread(target=enqueue_output, args=(p.stdout, q))
t.daemon = True # thread dies with the program
t.start()

# ... do other things here

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

但是总是打印“还没有输出”。 编辑:我编辑了代码并且它正在工作。但我还有另一个问题。下载的百分比是单行更新的,但是代码只有在行完成后才会读取它

【问题讨论】:

  • 可能是因为比基尼?尝试 sys.stdout.write("\rNo line") 而不是 print('no output yet')。你会看到一些输出,但我不知道你搜索的是不是那个
  • @cox 这和比基尼有什么关系?
  • 尝试脚本(或点击 youtube 链接)。这是“性感比基尼女郎史诗失败汇编 2013-AYlb-7TXMxM.mp4”。
  • @cox 它正在工作,但我现在有另一个问题。检查编辑!
  • 也许让我们尝试从这里解除 youtube-dl 的缓冲:stackoverflow.com/a/1544690/1219585 ?

标签: python multithreading subprocess stdout


【解决方案1】:

好的,让我们把 cmets 放在一个答案中。

import sys, os
from subprocess import PIPE, Popen
from time import sleep
import pty

master, slave = pty.openpty()
stdout = os.fdopen(master)

p = Popen(['youtube-dl', '-l', '-c', 'https://www.youtube.com/watch?v=AYlb-7TXMxM'], shell=False,stdout=slave,stderr=slave, close_fds=True)

while True:
    #line = stdout.readline().rstrip() - will strip the new line
    line = stdout.readline()
    if line != b'':
        sys.stdout.write("\r%s" % line)
        sys.stdout.flush()
    sleep(.1)

如果你想要一个线程和一个不同的 while,我建议包装在一个类中并避免排队。输出是“无缓冲” - 感谢@FilipMalckzak

【讨论】:

  • P.S.:我看到你已经改变了链接。我对机器人没意见,但比基尼让事情变得更快。
  • 您的脚本在完成之前不会打印新行。
  • 它对我有用。我不在家,但我会重新测试。你在哪个平台上?
猜你喜欢
  • 2012-04-06
  • 2012-06-07
  • 2015-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多