Home  >  Article  >  Backend Development  >  How to Achieve Non-Blocking Subprocess Execution in Python?

How to Achieve Non-Blocking Subprocess Execution in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-10-19 13:47:02210browse

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>

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>

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>

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!

Statement:
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