【问题标题】:Continuous interaction with subprocess in Python (Windows)在 Python (Windows) 中与子进程的持续交互
【发布时间】:2021-01-03 04:34:37
【问题描述】:

我正在从 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 什么都不做。 我该如何解决这个问题?

【问题讨论】:

标签: python windows powershell subprocess


【解决方案1】:

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

test.py

import subprocess, sys, os

p = subprocess.Popen(['start', 'powershell.exe', '-File', 'H:\Coding\stack\script.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:\Coding\stack> 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

【讨论】:

  • 感谢您的努力。 “powershell.exe”前面缺少“start”,因为我需要一个单独的窗口。我没有使用 p.communicate() 因为我有多个输入。
  • 换句话说,我有多个“hello”作为输入,但是“hello1”、“hello2”、“hello3”等,我需要依次处理它们
  • @Lin 更新答案
  • 要获得一个单独的控制台窗口,您可以使用creationflags=subprocess.CREATE_NEW_CONSOLEshell=False(默认)而不是CMD 的内部start 命令和shell=True。无需为此生成 cmd.exe 进程。
  • 另外,args 列表不应该与 shell=True 一起使用,因为子进程不知道如何正确构建 cmd.exe 的命令行(它不使用 CommandLineToArgvW 规则)。此外,如果脚本的路径最终包含空格,则在此处使用 start 是错误的,因为 start 将解释第一个带引号的字符串,在这种情况下是路径,作为要使用的窗口标题。
猜你喜欢
  • 2015-05-08
  • 2023-03-09
  • 2013-12-09
  • 1970-01-01
  • 2017-07-11
  • 1970-01-01
  • 2020-06-26
  • 2019-02-18
  • 1970-01-01
相关资源
最近更新 更多