You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell及Python中运行路径含()的PS1脚本

解决带括号路径的PowerShell脚本执行问题

问题原因

路径中的()属于PowerShell元字符,用于子表达式分组,未加引号包裹时,PowerShell会将C:\hoge(foo)\test.ps1拆分为C:\hoge和子表达式(foo),导致路径识别不完整。

解决方案

方法1:修正os.system命令(给路径加引号,移除多余嵌套)

无需嵌套调用PowerShell,直接执行脚本并给带特殊字符的路径加上双引号:

import os
# 用原始字符串避免反斜杠转义问题
script_path = r'C:\hoge(foo)\test.ps1'
# 双引号包裹路径,让PowerShell识别为完整参数
os.system(f'powershell -ExecutionPolicy RemoteSigned "{script_path}"')

方法2:使用subprocess模块(更推荐)

官方已不推荐使用os.system,subprocess模块更灵活安全,采用参数列表形式可彻底避免字符串转义问题:

import subprocess
script_path = r'C:\hoge(foo)\test.ps1'
# 参数列表形式传递,每个参数独立解析,无需额外引号
subprocess.run(['powershell', '-ExecutionPolicy', 'RemoteSigned', script_path], check=True)

内容的提问来源于stack exchange,提问作者hashingpotato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:04:06