如何在Python的subprocess.Popen中向PowerShell脚本传参并指定NoProfile
解决方案
错误原因分析
你之前的尝试失败,核心问题是subprocess列表参数的传递方式错误:
- 使用
subprocess.Popen的列表形式参数时,每个命令行元素必须单独作为列表的一个项,不能把多个参数(比如-file、脚本路径、脚本参数)合并成一个字符串。 - Python字符串中的
\是转义字符,直接写C:\Temp会被解析成特殊字符,需要用原始字符串(r'C:\Temp\my script.ps1')或者转义成\\。
正确实现代码
推荐方式:列表形式传递参数(无需处理引号)
这是subprocess的最佳实践,能避免引号和转义问题:
import subprocess # 拆分每个命令元素,-NoProfile指定不加载配置文件 subprocess.Popen([ 'pwsh', '-NoProfile', '-File', r'C:\Temp\my script.ps1', # 原始字符串避免转义问题 'cat', 'dog' ]) input("Press enter to exit;")
可选方式:使用shell=True(不推荐,存在安全风险)
如果一定要用类似终端的字符串写法,可以开启shell=True,但需注意路径和参数的引号处理:
import subprocess subprocess.Popen( r'pwsh -NoProfile -File "C:\Temp\my script.ps1" "cat" "dog"', shell=True ) input("Press enter to exit;")
代码说明
-NoProfile:告诉PowerShell不加载用户配置文件,满足你的需求。-File:明确指定要执行的脚本文件,列表形式下subprocess会自动处理带空格的路径,无需手动加引号。- 脚本的参数
cat、dog直接作为列表的后续项,会被正确传递给PowerShell脚本。
运行后控制台会输出:
2 cat dog
内容的提问来源于stack exchange,提问作者Ralf_Reddings
相关产品推荐
相关产品推荐

