urain39 / stuff

Noting here.
1 stars 0 forks source link

Python asyncio异步执行命令 #47

Open urain39 opened 4 years ago

urain39 commented 4 years ago
import asyncio

async def async_run(command, timeout=6):
    proc = await asyncio.create_subprocess_shell(
        command,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE)
    try:
        stdout, stderr = await asyncio.wait_for(
            proc.communicate(),
            timeout=timeout)
    except asyncio.TimeoutError:
        proc.terminate()
        return 255, b'', b''
    return proc.returncode, stdout, stderr
urain39 commented 4 years ago
import asyncio

async def async_run(command, timeout=6):
    proc = await asyncio.create_subprocess_shell(
        command,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE)
    try:
        stdout, stderr = await asyncio.wait_for(
            proc.communicate(),
            timeout=timeout)
    except asyncio.TimeoutError:
        proc.terminate()
        return 255, b'', b''
    return proc.returncode, stdout, stderr

async def main():
    for cmd in (
        #'top', 'vi', 'vim',
        'awk \'BEGIN { print "Hello World" }\'',
        'sleep 9; echo "Hello"', 'echo "World"',
        'busybox crond -c ~',
        'sh -c "(sleep 127; echo Testing) &"'):
        print(await async_run(cmd))

loop = asyncio.get_event_loop()
loop.run_until_complete(main())