如何让Python subprocess.run指定在PowerShell中执行ADB端口查询命令?
解决方案
可以通过subprocess.run的executable参数直接指定使用PowerShell运行命令,不需要显式添加powershell -Command参数或保存为.ps1文件,具体写法如下:
import subprocess # 你的PowerShell命令,用原始字符串避免转义反斜杠 ps_command = r'& "D:\Tools\Nmap\nmap.exe" -T4 192.168.2.20 -p 37000-44000 | Where-Object {$_ -match "tcp open"} | ForEach-Object {$_.split("/")[0]}' # 调用subprocess.run指定PowerShell执行 result = subprocess.run( ps_command, shell=True, executable="powershell.exe", # 用PowerShell Core则替换为"pwsh.exe" capture_output=True, text=True ) # 处理执行结果 if result.returncode == 0: print("检测到的ADB无线调试端口:") print(result.stdout.strip()) else: print("命令执行出错:") print(result.stderr.strip())
关键说明:
executable="powershell.exe":强制指定PowerShell作为执行命令的shell,替代默认的CMD。shell=True:必须开启此参数,subprocess才会调用指定的executable来解析执行命令字符串。- 使用原始字符串(前缀
r)可以避免手动转义路径中的反斜杠,让命令写法更简洁。
内容的提问来源于stack exchange,提问作者KumaTea
相关产品推荐
相关产品推荐

