![](/img/trans.png)
[英]How to kill this python process opened using subprocess.pOpen() in Windows?
[英]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.