要读取一些文本文件,在C或Pascal中,我总是使用以下代码段来读取数据,直到EOF:
while not eof do begin
readline(a);
do_something;
end;
Run Code Online (Sandbox Code Playgroud)
因此,我想知道如何在Python中简单快速地完成这项工作?
我有点难以理解解决这个简单问题的python方法是什么.
我的问题很简单.如果您使用以下代码,它将挂起.这在子流程模块doc中有详细记载.
import subprocess
proc = subprocess.Popen(['cat','-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
for i in range(100000):
proc.stdin.write('%d\n' % i)
output = proc.communicate()[0]
print output
Run Code Online (Sandbox Code Playgroud)
寻找一个解决方案(有一个非常有洞察力的线程,但我现在已经丢失了)我发现这个解决方案(以及其他)使用了一个显式的fork:
import os
import sys
from subprocess import Popen, PIPE
def produce(to_sed):
for i in range(100000):
to_sed.write("%d\n" % i)
to_sed.flush()
#this would happen implicitly, anyway, but is here for the example
to_sed.close()
def consume(from_sed):
while 1:
res = from_sed.readline()
if not res:
sys.exit(0)
#sys.exit(proc.poll())
print 'received: ', [res]
def main():
proc = Popen(['cat','-'],stdin=PIPE,stdout=PIPE)
to_sed = proc.stdin
from_sed = …Run Code Online (Sandbox Code Playgroud) 我想知道是否可以使用VideoWriterPython 中的 OpenCV类“流式传输”数据?
通常为了处理内存中的数据,否则我会使用 BytesIO(或 StringIO)。
我尝试使用 BytesIO 失败了:
import cv2
from io import BytesIO
stream = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc('x264')
data = BytesIO()
# added these to try to make data appear more like a string
data.name = 'stream.{}'.format('av1')
data.__str__ = lambda x: x.name
try:
video = cv2.VideoWriter(data, fourcc=fourcc, fps=30., frameSize=(640, 480))
start = data.tell()
# Check if camera opened successfully
if (stream.isOpened() == False):
print("Unable to read camera feed", file=sys.stderr)
exit(1)
# record loop
while True: …Run Code Online (Sandbox Code Playgroud)