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

Git Bash中Python脚本CLI参数异常,Windows CMD运行正常

Git Bash中Python脚本接收以/开头的CLI参数被自动追加Git安装路径的问题解决

问题描述

在Git Bash里运行Python脚本testsuit_adaptation.py时,传入的第三个CLI参数/api会被自动加上C:/Program Files/Git/前缀,哪怕给参数套引号也没用,通过sys.argv拿到的参数值是C:/Program Files/Git/api;但在Windows CMD里执行一模一样的命令,参数能正常获取为/api。

Git Bash执行示例

$ python testsuit_adaptation.py ../testsuits /api
['testsuit_adaptation.py', '../testsuits', 'C:/Program Files/Git/api']
below testcase need to do adaptation
$ python testsuit_adaptation.py ../testsuits "/api"
['testsuit_adaptation.py', '../testsuits', 'C:/Program Files/Git/api']
below testcase need to do adaptation

Windows CMD执行示例

C:\My_Space\Codes\my_codes\Python\sct_scenario\utils>python testsuit_adaptation.py ../testsuits /api
['testsuit_adaptation.py', '../testsuits', '/api']
below testcase need to do adaptation

原因分析

这是Git Bash自带的路径转换机制搞的鬼——Git Bash会把以/开头的参数当成类Unix系统的路径,自动转换成Windows下的绝对路径,映射到Git的安装目录,所以/api就被转成了C:/Program Files/Git/api。

解决方案

方法1:用双斜杠转义参数

给参数前面多加一个斜杠,让Git Bash不触发路径转换逻辑:

python testsuit_adaptation.py ../testsuits //api

这样脚本通过sys.argv拿到的就是/api。

方法2:临时禁用路径转换

执行命令前设置MSYS_NO_PATHCONV=1环境变量,临时关掉Git Bash的路径转换:

MSYS_NO_PATHCONV=1 python testsuit_adaptation.py ../testsuits /api

如果需要永久生效,可以把export MSYS_NO_PATHCONV=1添加到Git Bash的配置文件~/.bashrc里。

方法3:在Python脚本内修正参数

不想改命令的话,直接在脚本里对参数做后处理,去掉多余的前缀:

import sys

def fix_arg_path(arg):
    git_install_prefix = "C:/Program Files/Git/"
    if arg.startswith(git_install_prefix):
        return "/" + arg[len(git_install_prefix):]
    return arg

if __name__ == "__main__":
    # 修正所有参数
    sys.argv = [fix_arg_path(item) for item in sys.argv]
    # 后续正常业务逻辑
    print(sys.argv)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 20:15:05