Исключение «ConnectionResetError» после ожидания subprocesss.stdout.drain () из модуля asyncio.subprocess - PullRequest
0 голосов
/ 19 сентября 2019

Я столкнулся с исключением, когда пытался запустить внешний файл python с помощью asyncio.subprocess.Вот мой код:

import asyncio
async def external():
    writing_process=await asyncio.create_subprocess_shell("pwd",
                                                            stdin=asyncio.subprocess.PIPE, 
                                                            stdout=asyncio.subprocess.PIPE, 
                                                            stderr=asyncio.subprocess.PIPE,
                                                            cwd="/home/user1/folder1")
    print(await writing_process.stdout.read())
    writing_process.stdin.writelines([b"python test.py"])
    await writing_process.stdin.drain()
    print(await writing_process.stdout.read())
asyncio.run(run_outer_py_file())

Вот вывод:

b'/home/bykov/nra_banks\n'
---------------------------------------------------------------------------
ConnectionResetError                      Traceback (most recent call last)
<ipython-input-9-67bbc190049c> in async-def-wrapper()

<ipython-input-9-67bbc190049c> in external()
     11     print(await writing_process.stdout.read())
     12 await external()

~/anaconda3/lib/python3.7/asyncio/streams.py in drain(self)
    346             # would not see an error when the socket is closed.
    347             await sleep(0, loop=self._loop)
--> 348         await self._protocol._drain_helper()
    349 
    350 

~/anaconda3/lib/python3.7/asyncio/streams.py in _drain_helper(self)
    200     async def _drain_helper(self):
    201         if self._connection_lost:
--> 202             raise ConnectionResetError('Connection lost')
    203         if not self._paused:
    204             return

ConnectionResetError: Connection lost

Может кто-нибудь объяснить мне, где я не прав?

1 Ответ

0 голосов
/ 19 сентября 2019

В соответствии с @ user4815162342 я понимаю, что я должен поместить все свои команды в скрипт bash и использовать имя файла python в качестве параметра строки команды.

Итак, мой bash-скрипт:

#!/bin/bash
source /home/user1/anaconda3/bin/activate my_env
python "$@"

И мой код Python:

import asyncio
async def run_external(script, *args):
    writing_process=await asyncio.create_subprocess_shell("bash test.sh "+' '.join((script,)+args), 
                                                      stdin=asyncio.subprocess.PIPE, 
                                                      stdout=asyncio.subprocess.PIPE, 
                                                      stderr=asyncio.subprocess.PIPE,
                                                      cwd="/home/user1/folder1")
    print((await writing_process.stdout.read()).decode())
asyncio.run(run_external("test.py"))
...