跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • Python 多进程问题
未分類
28 11 月 2020

Python 多进程问题

Python 多进程问题

資深大佬 : frmongo 3

在一个 linux 主机上,我想同时开始播放音乐和录音(有麦克风),期望录音结束,音乐自动停止。 现在只需要录音 20 秒,下面的代码录音结束后,音乐不会停止,怎么写可以实现目的呢

# coding:utf-8  from multiprocessing import Process as process import os  def play_music():     cmd1 = "aplay muisc.wav"     os.system(cmd1)  def record():     cmd1 = "arecord -r 16000 -t wav -d 20 -v out.wav"     os.system(cmd1)  if __name__ == '__main__':          p1 = process(target=play_music)     p1.daemon=True     p1.start()     record()     p1.terminate()     p1.join() 

大佬有話說 (9)

  • 資深大佬 : ruanimal

    直接用 subprocess.popen 就好了啊,用啥 multiprocessing 。。。

  • 資深大佬 : jkhere

    不是很好实现,子进程开始执行后,主进程就无法精确控制子进程了。
    假设你子进程开始后,主进程开始计时,到时间后杀死子进程,这样也只是粗略的控制时间。

  • 資深大佬 : mingl0280

    先开始放音乐,再启动录音,录音返回以后( system 有返回值吧) kill 掉放音……

  • 資深大佬 : ysc3839

    @ruanimal 我也觉得应该直接使用 subprocess.popen 。play_music 就只是调用 shell 启动个新进程,不如直接自己启动新进程,没必要绕一圈。

  • 資深大佬 : ruanimal

    @ysc3839 意思是用 subprocess.popen 替换 multiprocessing 和 os.system

  • 資深大佬 : ysc3839

    @ruanimal 是的,我就是想表达这个意思。

  • 資深大佬 : NeezerGu

    https://www.notion.so/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F6cca620b-71c7-4204-8b3f-ba6fa526c8ca%2FUntitled.png?table=block&id=1a34c76c-7b1e-4c22-ba85-199194a1edf6&width=3840&userId=&cache=v2

    https://www.notion.so/neezer/python-a216d49fb46040e181ae70df69d247f2

    很久没写多进程了,不知道这样可以吗?

  • 資深大佬 : jkhere

    给你个 demo,用 python 的协程吧:

    import asyncio

    async def eternity():
    # do your job
    while True:
    print(‘doing!’)

    async def main():
    # Wait for at most 20 second
    try:
    await asyncio.wait_for(eternity(), timeout=20.0)
    except asyncio.TimeoutError:
    print(‘timeout! job done’)

    asyncio.run(main())

  • 資深大佬 : jkhere

    “`python
    import asyncio

    async def eternity():
    # do your job
    while True:
    print(‘doing!’)

    async def main():
    # Wait for at most 20 second
    try:
    await asyncio.wait_for(eternity(), timeout=20.0)
    except asyncio.TimeoutError:
    print(‘timeout! job done’)

    asyncio.run(main())
    “`

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具