asynchronous subprocess Popen python 3.5
<p>I am trying to asynchronously run the Popen command from subprocess, so that I can run other stuff in the background.</p>

<pre><code>import subprocess
import requests
import asyncio
import asyncio.subprocess    

    async def x(message):
        if len(message.content.split()) &gt; 1:
            #output = asyncio.create_subprocess_shell(message.content[3:], shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
            output = subprocess.Popen(message.content[3:], shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
            return output.communicate()[0].decode('utf-8')
</code></pre>

<p>I have tried to understand <a href="https://docs.python.org/3/library/asyncio-subprocess.html" rel="nofollow">https://docs.python.org/3/library/asyncio-subprocess.html</a> but i am not sure what a protocol factory is.</p>

<p>This one is much simpler, I found it after the other reply that could, anyway, be interesting... so I left it.</p>

<pre><code>import time
import subprocess
import shlex
from sys import stdout


command = 'time sleep 5' # Here I used the 'time' only to have some output

def x(command):
    cmd = shlex.split(command)
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    return p

# Start the subprocess and do something else...
p = x(command)
# ...for example count the seconds in the mean time..

try: # This take care of killing the subprocess if problems occur
    for j in range(100):
        stdout.write('\r{:}'.format(j))
        stdout.flush()
        time.sleep(1)
        if p.poll() != None:
            print(p.communicate())
            break
except:
    p.terminate() # or p.kill()
</code></pre>

<p>The asynchronism is evident from the fact that the python script prints the counter value on the stdout while the background process runs the <code>sleep</code> command. The fact that the python script exit after ~5sec printing the output of the bash <code>time</code> command printing the counter in the meanwhile is an evidence that the script works.</p>

python asynchronous subprocess python-3.5