Можно воспользоваться модулем Pexpect. Начиная с вер. 4.0 добавлена (ограниченная) поддержка для Windows:
As of version 4.0, Pexpect can be used on Windows and POSIX systems. However, pexpect.spawn
and pexpect.run()
are only available on POSIX, where the pty
module is present in the standard library. See Pexpect on Windows for more information.
Небольшой пример:
>>> from pexpect.popen_spawn import PopenSpawn
>>> from pexpect import EOF,TIMEOUT
>>>
>>> p = PopenSpawn ('python -iu')
>>> p.expect (['>>> ', TIMEOUT, EOF], timeout=1)
0
>>> p.before.rstrip ().decode ()
'Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32\nType "help", "copyright", "credits" or "license" for more information.'
>>> p.sendline ('1+2')
5
>>> p.expect (['>>> ', TIMEOUT, EOF], timeout=1)
0
>>> p.before.rstrip ().decode ()
'3'
>>> p.sendeof ()
>>> p.wait ()
0
Возможно также и с subprocess.Popen, но будет несколько сложнее:
>>> from subprocess import Popen, PIPE, STDOUT
>>>
>>> p = Popen (['python', '-iu'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
>>> p.stdout.readline ().rstrip ().decode ()
'Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32'
>>> p.stdout.readline ().rstrip ().decode ()
'Type "help", "copyright", "credits" or "license" for more information.'
>>> p.stdin.write (b'1+2\n')
4
>>> p.stdin.flush ()
>>> p.stdout.readline ().rstrip ().decode ()
'>>> 3'
>>> p.stdin.close ()
>>> p.wait ()
0