在Python(Windows)中与子流程的连续交互



我正在从python在一个新的PowerShell窗口中启动一个脚本,我想让这个进程在后台运行,这样我就可以不断地与它交互。

我尝试了以下代码:

p = subprocess.Popen(['start powershell.exe', '-File', 'script.ps1']
shell    = True,
stdin    = subprocess.PIPE,
stdout   = subprocess.PIPE,
bufsize  = 1,
encoding ='utf-8')
p.stdin.write('input1')
p.stdout.readline()
p.stdin.write('input2')
p.stdout.readline()
p.stdin.write('input3')
p.stdout.readline()

但是p.stdin.write什么都不做。我该如何解决这个问题?

我创建了一个最小的示例来准确理解您想要什么。告诉我你想要什么?

测试.py

import subprocess, sys, os
p = subprocess.Popen(['start', 'powershell.exe', '-File', 'H:Codingstackscript.ps1'],
shell=True,
stdout = subprocess.PIPE,
stdin = subprocess.PIPE,
bufsize = 1,
encoding ='utf-8'
)
while p.poll() is None:
output = p.stdout.readline()
print(output)
print('end of python'))

script.ps1

$input = Read-Host -Prompt 'input'
Write-Host $input
$input = Read-Host -Prompt 'input'
Write-Host $input
$input = Read-Host -Prompt 'input'
Write-Host $input
Write-Host 'end of process'
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

结果

PS H:Codingstack> python test.py
(new window started)
input: test
test
input: this
this
input: out
out
end of process
Press any key to continue...
(window closed)
end of python

最新更新