gpt4 book ai didi

python - 在 Python 中同步 Linux 系统命令和 while 循环

转载 作者:太空狗 更新时间:2023-10-29 11:44:17 25 4
gpt4 key购买 nike

对于 RaspberryPi 系统,我必须将 Raspbian 系统命令 (raspivid -t 20000) 与从传感器连续读取并将样本存储在数组中的 while 循环同步。 Raspbian 命令通过 RaspberryPi 相机 CSI 模块启动视频录制,我必须确保它在传感器采集的同一时刻开始。我看到许多解决方案让我对 multiprocessingthreadingsubprocess、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 循环才会运行。但正如我上面所写,我需要这两个进程是同步的并且并行工作。有什么建议吗?

最佳答案

只需在末尾添加一个&,即可使进程脱离后台:

os.system("raspivid -t 20000 /home/pi/test.h264 &")

根据 bash 手册页:

If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.

另外,如果你想在执行 raspivid 后最小化循环开始的时间,你应该分配你的 dataindx 在通话之前:

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!"

关于python - 在 Python 中同步 Linux 系统命令和 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27651719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com