简体   繁体   English

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

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

I am trying out an example Pipe program 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);

However, it errors with the following但是,它出现以下错误

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"

I expect the program to work as 'stdin' for P2 takes the output of P1's 'stdout'.我希望该程序能够作为 P2 的“标准输入”使用 P1 的“标准输出”的输出。 Not sure what am I doing wrong ?不确定我做错了什么?

You use Popen correctly, however PowerShell's pipeline between 2 command-lets is very different in its nature from a regular pipeline between processes.您正确使用了 Popen,但是 PowerShell 的 2 个 command-let 之间的管道在本质上与进程之间的常规管道非常不同。 PowerShell transfers objects. PowerShell 传输对象。 Look more in the Understanding pipeline document.了解管道文档中查看更多信息。

Unfortunately this feature cannot be used for communication between separate PowerShell processes using system pipeline.不幸的是,此功能不能用于使用系统管道的单独 PowerShell 进程之间的通信。

So this command will fail exactly the same way as it fails in your code:因此,此命令将与在您的代码中失败的方式完全相同:

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

You should use Popen to work with the single PowerShell process and let PowerShell to handle pipelining:您应该使用 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 Don't use ; PS不要使用; in Python在 Python 中

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

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