线程子进程读取不提供任何输出

时间:2014-01-24 09:46:08

标签: python multithreading subprocess stdout

我有以下代码,我试图在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

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

1 个答案:

答案 0 :(得分:1)

好的,我们把评论放在答案中。

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)

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