subprocess.run配置shell=True后无法正常执行PowerShell命令问题问询
问题根本成因
- shell默认值不匹配:Windows平台下Python
subprocess开启shell=True时,默认调用的系统shell是cmd.exe,而非PowerShell。$profile是PowerShell专属的自动变量,Get-ChildItem是PowerShell专属的Cmdlet,cmd.exe完全不识别这类语法,因此会报“命令拼写错误或无法找到”的错误。 dir可正常运行的原因:dir是cmd.exe和PowerShell同时支持的同名内置命令,在cmd环境下可以被正常解析执行,因此不会触发报错。
修复方案
如果需要调用PowerShell执行相关命令,不需要依赖shell=True,直接显式指定调用PowerShell程序即可,示例代码如下:
import subprocess txt = subprocess.run( ["powershell", "-Command", "$profile"], capture_output=True, text=True ) # 输出$profile的返回结果 print(txt.stdout)
如果使用的是PowerShell 7+版本,将上述代码中的powershell替换为pwsh即可适配。
内容的提问来源于stack exchange,提问作者SergeantSuperUser
相关产品推荐
相关产品推荐

