对于RaspberryPi系统,我必须同步一个Raspbian命令(raspivid -t 20000)和一个With循环,该循环从传感器连续读取,并将样本存储在数组中。Raspbian命令启动由RaspberryPi相机CSI模块录制的视频,我必须确保它在传感器获取的同时启动。我看到了许多解决方案,使我在multiprocessing、threading、subprocess、ecc等模块中感到困惑。到目前为止,我唯一理解的是,只要脚本运行,os.system()函数就会阻止以下python命令的执行。所以如果我试着:
import os
import numpy as np
os.system("raspivid -t 20000 /home/pi/test.h264")
data = np.zeros(20000, dtype="float") #memory pre-allocation supposing I have to save 20000 samples from the sensor (1 for each millisecond of the video)
indx=0
while True:
sens = readbysensor() #where the readbysensor() function is defined before in the script and reads a sample from the sensor
data[indx]=sens
if indx==19999:
break
else:
indx+=1只有当os.system()函数完成时,while-循环才会运行。但是,正如我上面所写的,我需要这两个进程是同步的,并并行工作。有什么建议吗?
发布于 2014-12-26 00:12:35
只需在末尾添加一个&,以使流程与后台分离:
os.system("raspivid -t 20000 /home/pi/test.h264 &")根据bash手册页:
如果一个命令被控制操作符终止&,shell将在子shell的后台执行该命令。shell不等待命令完成,返回状态为0。
此外,如果您希望在执行raspivid后尽量减少循环启动所需的时间,则应该在调用之前分配您的data和indx:
data = np.zeros(20000, dtype="float")
indx=0
os.system("raspivid -t 20000 /home/pi/test.h264 &")
while True:
# ....更新:
由于我们在注释中进行了进一步的讨论,很明显没有必要像raspivid一样“同时”启动循环(不管这意味着什么),因为如果您试图从I2C读取数据并确保不遗漏任何数据,那么在运行raspivid之前启动读取操作将是最好的。通过这种方式,您可以确定在这段时间内(无论这两次执行之间有多么大的延迟),您不会丢失任何数据。
考虑到这一点,您的代码可能如下所示:
data = np.zeros(20000, dtype="float")
indx=0
os.system("(sleep 1; raspivid -t 20000 /home/pi/test.h264) &")
while True:
# ....这是在运行raspivid之前添加1秒延迟的最简单版本,因此我们有时间进入while循环并开始等待I2C数据。
这是可行的,但它几乎不是一个生产质量代码。为了获得更好的解决方案,请在一个线程中运行数据采集函数,在另一个线程中运行raspivid,保持启动顺序(首先启动读取线程)。
就像这样:
import Queue
import threading
import os
# we will store all data in a Queue so we can process
# it at a custom speed, without blocking the reading
q = Queue.Queue()
# thread for getting the data from the sensor
# it puts the data in a Queue for processing
def get_data(q):
for cnt in xrange(20000):
# assuming readbysensor() is a
# blocking function
sens = readbysensor()
q.put(sens)
# thread for processing the results
def process_data(q):
for cnt in xrange(20000):
data = q.get()
# do something with data here
q.task_done()
t_get = threading.Thread(target=get_data, args=(q,))
t_process = threading.Thread(target=process_data, args=(q,))
t_get.start()
t_process.start()
# when everything is set and ready, run the raspivid
os.system("raspivid -t 20000 /home/pi/test.h264 &")
# wait for the threads to finish
t_get.join()
t_process.join()
# at this point all processing is completed
print "We are all done!"发布于 2014-12-26 09:33:53
您可以将代码重写为:
import subprocess
import numpy as np
n = 20000
p = subprocess.Popen(["raspivid", "-t", str(n), "/home/pi/test.h264"])
data = np.fromiter(iter(readbysensor, None), dtype=float, count=n)subprocess.Popen()在不等待raspivid结束的情况下立即返回。
https://stackoverflow.com/questions/27651719
复制相似问题