如何从Python 3.7.3正确调用带参数的PowerShell脚本?
解决Python调用带参数PowerShell脚本的问题
嘿,我来帮你搞定这个问题!你遇到的FileNotFoundError核心原因是**subprocess.call的参数格式用错了**,咱们一步步来修正:
错误根源
你写的subprocess.call(["powershell test.ps1 10.238.241.38"])是把整个命令当成了单个字符串放在列表里,subprocess会把这个完整字符串当成要执行的可执行文件名称,而不是去调用powershell并传递后续参数——系统当然找不到叫powershell test.ps1 10.238.241.38的程序,所以报错。
正确的调用方式
方式1:拆分命令为列表元素(推荐)
subprocess的列表模式下,第一个元素是可执行程序,后面每个元素都是独立的参数,这样系统能正确识别powershell,再传递脚本和IP参数:
import subprocess # 直接拆分参数,前提是Python脚本和test.ps1在同一目录 subprocess.call(["powershell", ".\\test.ps1", "10.238.241.38"])
方式2:使用脚本绝对路径(更稳妥)
如果你的Python脚本不在C:\Users\jgreen02或桌面目录下,最好用绝对路径指定test.ps1,避免因工作目录不同找不到脚本:
import subprocess # 用r前缀避免转义字符问题 script_path = r"C:\Users\jgreen02\Desktop\test.ps1" subprocess.call(["powershell", script_path, "10.238.241.38"])
方式3:使用shell=True(不推荐)
如果你一定要用整串命令的写法,可以加上shell=True,但这种方式有安全风险(比如参数来自外部输入时容易被注入),所以只在特殊场景用:
import subprocess subprocess.call("powershell .\\test.ps1 10.238.241.38", shell=True)
进阶:在Python中捕获输出
如果想直接在Python里获取PowerShell脚本的输出,而不是依赖脚本保存到文件,推荐用subprocess.run(Python3.5+支持):
import subprocess script_path = r"C:\Users\jgreen02\Desktop\test.ps1" try: # capture_output=True捕获输出,text=True让输出为字符串格式 result = subprocess.run( ["powershell", script_path, "10.238.241.38"], capture_output=True, text=True, check=True # 如果脚本执行出错会抛出异常 ) # 打印输出内容 print("脚本输出:") print(result.stdout) # 保存到文件 with open("router_output.txt", "w", encoding="utf-8") as f: f.write(result.stdout) except subprocess.CalledProcessError as e: print(f"脚本执行出错:{e.stderr}")
内容的提问来源于stack exchange,提问作者Jgreene44
相关产品推荐
相关产品推荐

