无需等待即可在后台运行Shell命令

时间:2019-01-10 12:18:15

标签: python shell operating-system

我想在python中同时运行多个命令,但是该程序似乎在上一个命令完成时执行了一个命令,

这是我的代码:

import os
import glob
for i in (glob.glob("PATH/SUB/*.csv")):
    file = i.split('\\')[1]
os.system("scrapy crawl quotes -a file=%s -o /OUTPUT/%s.csv &" % (file,file)) 

1 个答案:

答案 0 :(得分:1)

简短答案:

#!/usr/bin/env python3.6
import time
import asyncio
from asyncio.subprocess import PIPE, STDOUT


async def run(shell_command):
    p = await asyncio.create_subprocess_shell(shell_command, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    return (await p.communicate())[0].splitlines()


async def main():
    commands = [run('sleep 5; echo {i}'.format(i=i)) for i in range(5)]
    for f in asyncio.as_completed(commands):
        print(await f)


start = time.time()

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

total = time.time() - start

print("Total time {} s".format(total))

长答案:

您可以检查asyncio子进程。

让我们测试一下。我们将尝试运行5次“ sleep 5”命令-我们希望总运行时间类似于5秒(而不是25秒)。

[b'2']
[b'3']
[b'4']
[b'1']
[b'0']
Total time 5.0065038204193115 s

输出:

#!/usr/bin/env python3.6
import glob
import asyncio


async def run(shell_command):
    p = await asyncio.create_subprocess_shell(shell_command)
    await p.communicate()


async def main(shell_commands):
    for f in asyncio.as_completed([run(c) for c in shell_commands]):
        await f


commands = []
for i in (glob.glob("PATH/SUB/*.csv")):
    file = i.split('\\')[1]
    commands.append("scrapy crawl quotes -a file=%s -o /OUTPUT/%s.csv &" % (file, file))

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

一切正常。

在适应您的需求之后:

loop = asyncio.get_event_loop()

最后,如果您使用的是Windows,则需要进行更改

loop = asyncio.ProactorEventLoop() 

进入

file = i.split('\\')[1].

我认为您使用Windows是因为您的代码

{{1}}
相关问题