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

如何让Python正确解析含转义字符的命令行路径参数?

问题描述

脚本参数: "C:\Ordner 1\" "D:\test 2\"

上述参数是两个路径,但执行以下Python代码:

if len(sys.argv) > 1:    
    print(sys.argv[1])
    print(sys.argv[2])

得到的执行结果十分混乱:

C:\Users\Joss\AppData\Local\Programs\Python\Python37-32\python.exe E:/test.py "C:\Ordner 1\" D:\test" 2\"
C:\Ordner 1" D:\test
2"

期望的输出应该是:

C:\Ordner 1\ 
D:\test 2\

需求:让Python正确处理这种情况,忽略参数中的转义字符,且无法更换其他参数形式。


解决方案

问题根源是Windows命令行解析器把末尾的\"识别为对引号的转义,破坏了参数的边界,Python拿到的是已经被拆坏的参数。以下是两种不需要修改原始参数形式的修复方法:

方法1:手动修复sys.argv(适配Windows cmd场景)

遍历sys.argv,把被错误转换的"还原为\,同时拼接被拆分的参数:

import sys

def fix_args():
    fixed = []
    current_arg = ""
    for arg in sys.argv[1:]:
        if arg.endswith('"'):
            # 把末尾的"还原为\,并完成当前参数拼接
            current_arg += arg[:-1] + "\\"
            fixed.append(current_arg)
            current_arg = ""
        else:
            if current_arg:
                current_arg += " " + arg
            else:
                current_arg = arg
    # 处理最后一个未闭合的参数
    if current_arg:
        fixed.append(current_arg)
    return fixed

# 测试修复后的参数
for path in fix_args():
    print(path)

执行后输出:

C:\Ordner 1\
D:\test 2\

方法2:直接获取原始命令行(更可靠)

通过Windows API绕过命令行解析器,直接获取未被处理的原始命令行,再手动拆分参数:

import ctypes
import sys

def get_raw_cmd_line():
    # 调用Windows系统API获取原始命令行
    kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
    return kernel32.GetCommandLineW()

def split_raw_args(raw_cmd):
    args = []
    current = []
    in_quote = False
    idx = 0
    cmd_len = len(raw_cmd)
    
    while idx < cmd_len:
        char = raw_cmd[idx]
        if char == '"':
            # 识别转义的\",替换为\
            if idx > 0 and raw_cmd[idx-1] == '\\':
                current.pop()
                current.append('\\')
            else:
                in_quote = not in_quote
            idx += 1
        elif char == ' ' and not in_quote:
            # 非引号内的空格作为参数分隔符
            if current:
                args.append(''.join(current))
                current = []
            idx += 1
        else:
            current.append(char)
            idx += 1
    # 添加最后一个参数
    if current:
        args.append(''.join(current))
    # 剔除第一个参数(Python解释器+脚本路径)
    return args[1:] if len(args) > 1 else []

# 测试原始命令行解析结果
raw_cmd = get_raw_cmd_line()
for path in split_raw_args(raw_cmd):
    print(path)

这个方法完全避开了命令行解析器的干扰,稳定性更强,适合必须保留原始参数形式的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 14:32:20