【发布时间】: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