内容纲要

python 可以通过多种方式打开子进程,例如 os.popen, os.exec*;但是用 subprocess 模块可以管理子进程。

import subprocess

result = subprocess.run(
    ['echo', 'Hello from the child!'],
    capture_output=True,
    encoding='utf-8'
)

result.check_returncode()
print(result.stdout)
>>>
Hello from the child!
proc = subprocess.Popen(
    ['sleep', '1']
)

while proc.poll() is None:
    print('Working...')

print('Exit status', proc.poll())
>>>
Working...
Working...
Working...
Working...
Exit status 0
import time

start = time.time()
sleep_procs = []
for _ in range(10):
    proc = subprocess.Popen(['sleep', '1'])
    sleep_procs.append(proc)

for proc in sleep_procs:
    proc.communicate()

end = time.time()
delta = end - start
print(f'Finished in {delta:.3} seconds')
>>>
Finished in 1.05 seconds

发表评论

电子邮件地址不会被公开。 必填项已用*标注