在 Python 中使用子流程

Use subprocess in Python

我正在 Python 中编写一个小程序来录制音频并同时打印一些文本。

但是我的打印一直执行到录音结束。 你能帮我解决这个问题吗?

import picamera, subprocess, os, sys

a1 = "arecord -f cd -D plughw:0 -d 10 a.wav"
subprocess.call(a1,shell= True)
print("Audio record is only for 10sec")

您正在使用 subprocess.call,它会阻止:

Run the command described by args. Wait for command to complete, then return the returncode attribute.

您可以使用不阻塞的 Popen 对象:

proc = subprocess.Popen(a1.split())
# code will proceed

# use proc.communicate later on

或者您可以使用 Thread 分别拥有两个东西 运行(然后在它自己的上下文中生成一个进程):

import picamera, subprocess, os, sys
import threading

def my_process():
    a1 = "arecord -f cd -D plughw:0 -d 10 a.wav"
    subprocess.call(a1,shell= True)
thread = threading.Thread(target=my_process)
thread.start()
print("Audio record is only for 10sec")