How to Achieve Non-Blocking Subprocess Execution in Python?

Linda Hamilton
Release: 2024-10-19 13:47:02
Original
209 people have browsed it

How to Achieve Non-Blocking Subprocess Execution in Python?

Non-Blocking Subprocess Execution

To achieve non-blocking subprocess execution, consider using subprocess.Popen instead of subprocess.call. subprocess.call waits for the command to complete before returning, while subprocess.Popen immediately starts the subprocess and returns a file-like object.

<code class="python">import subprocess

subprocess.Popen(["python", "slave.py"] + sys.argv[1:])</code>
Copy after login

By using subprocess.Popen, you can pass arguments to slave.py and allow it to run independently of main.py. slave.py can then execute its tasks without blocking main.py.

<code class="python">import subprocess
import time

p = subprocess.Popen(['sleep', '5'])

while p.poll() is None:
    print('Still sleeping')
    time.sleep(1)

print('Not sleeping any longer.  Exited with returncode %d' % p.returncode)</code>
Copy after login

In Python 3.5 and later, you can also use coroutines to achieve parallelism and non-blocking subprocess execution.

<code class="python">import asyncio

async def do_subprocess():
    print('Subprocess sleeping')
    proc = await asyncio.create_subprocess_exec('sleep', '5')
    returncode = await proc.wait()
    print('Subprocess done sleeping.  Return code = %d' % returncode)

async def sleep_report(number):
    for i in range(number + 1):
        print('Slept for %d seconds' % i)
        await asyncio.sleep(1)

loop = asyncio.get_event_loop()

tasks = [
    asyncio.ensure_future(do_subprocess()),
    asyncio.ensure_future(sleep_report(5)),
]

loop.run_until_complete(asyncio.gather(*tasks))
loop.close()</code>
Copy after login

The above is the detailed content of How to Achieve Non-Blocking Subprocess Execution in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!