如何在Windows上使用Python使用Popen?
我正在Windows上试用一个使用Python的示例管道程序如何在Windows上使用Python使用Popen?,python,powershell,Python,Powershell,我正在Windows上试用一个使用Python的示例管道程序 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);
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的“stdin”工作,并获取P1的“stdout”的输出。不确定我做错了什么?您正确地使用了Popen,但是PowerShell的2个命令let之间的管道在性质上与进程之间的常规管道大不相同。PowerShell传输对象。在文档中查看更多信息 不幸的是,此功能不能用于使用系统管道的独立PowerShell进程之间的通信 因此,此命令的失败方式与代码中的失败方式完全相同:
powershell获取子项C:\dev\python | powershell选择字符串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)
注意不要使用
代码>在Python中您希望使用交互式Python shell吗?