推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
frmongo
V2EX  ›  Python

Python 多进程问题

  •  
  •   frmongo · Dec 2, 2020 · 3039 views
    This topic created in 2161 days ago, the information mentioned may be changed or developed.

    在一个 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 replies  •  2020-12-04 17:32:38 +08:00
    ruanimal
    ruanimal
    Dec 2, 2020
    1
    直接用 subprocess.popen 就好了啊,用啥 multiprocessing 。。。
    jkhere
    jkhere
    Dec 2, 2020
    2
    不是很好实现,子进程开始执行后,主进程就无法精确控制子进程了。
    假设你子进程开始后,主进程开始计时,到时间后杀死子进程,这样也只是粗略的控制时间。
    mingl0280
    mingl0280
    Dec 2, 2020 via Android
    3
    先开始放音乐,再启动录音,录音返回以后( system 有返回值吧) kill 掉放音……
    ysc3839
    ysc3839
    Dec 2, 2020 via Android
    4
    @ruanimal 我也觉得应该直接使用 subprocess.popen 。play_music 就只是调用 shell 启动个新进程,不如直接自己启动新进程,没必要绕一圈。
    ruanimal
    ruanimal
    Dec 2, 2020
    5
    @ysc3839 意思是用 subprocess.popen 替换 multiprocessing 和 os.system
    ysc3839
    ysc3839
    Dec 2, 2020 via Android
    6
    @ruanimal 是的,我就是想表达这个意思。
    jkhere
    jkhere
    Dec 4, 2020
    8
    给你个 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
    jkhere
    Dec 4, 2020
    9
    ```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())
    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1327 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 20:09 · PVG 04:09 · LAX 12:09 · JFK 15:09
    ♥ Do have faith in what you're doing.