繁体   English   中英

如何在 Windows 上使用 Python 使用 Popen?

[英]How to use Popen using Python on Windows?

我正在尝试在 Windows 上使用 Python 的示例 Pipe 程序

import subprocess

p1 = subprocess.Popen(["powershell", "Get-ChildItem C:\\dev\\python"],  stdout=subprocess.PIPE);

p2 = subprocess.Popen(["powershell", "Select-String", "py"], stdin=p1.stdout, stdout=subprocess.PIPE);
p1.stdout.close();

p2_output = p2.communicate()[0];
print(p2_output);

但是,它出现以下错误

cmdlet Select-String at command pipeline position 1
Supply values for the following parameters:
Path[0]: b"\r\nSelect-String : Cannot bind argument to parameter 'Path' because it is an empty array.\nAt line:1 char:1\n+ Select-String py\n+ ~~~~~~~~~~~~~~~~\n    + CategoryInfo          : InvalidData: (:) [Select-String], ParameterBindingValidationException\n    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyArrayNotAllowed,Microsoft.PowerShell.Commands.SelectStringCommand\n \n"

我希望该程序能够作为 P2 的“标准输入”使用 P1 的“标准输出”的输出。 不确定我做错了什么?

您正确使用了 Popen,但是 PowerShell 的 2 个 command-let 之间的管道在本质上与进程之间的常规管道非常不同。 PowerShell 传输对象。 了解管道文档中查看更多信息。

不幸的是,此功能不能用于使用系统管道的单独 PowerShell 进程之间的通信。

因此,此命令将与在您的代码中失败的方式完全相同:

powershell Get-ChildItem C:\\dev\\python | powershell Select-String py

cmdlet Select-String at command pipeline position 1
Supply values for the following parameters:
Path[0]:
Select-String : Cannot bind argument to parameter 'Path' because it is an empty array.
At line:1 char:1
+ Select-String -Pattern py
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Select-String], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyArrayNotAllowed,Microsoft.PowerShell.Commands.SelectStringCommand

您应该使用 Popen 来处理单个 PowerShell 进程,并让 PowerShell 处理流水线:

import subprocess

p = subprocess.Popen("powershell Get-ChildItem C:\\dev\\python | Select-String py", stdout=subprocess.PIPE)

p_output = p.communicate()[0].decode()
print(p_output)

PS不要使用; 在 Python 中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM