Python:如果以反斜杠分隔,则加入连续的行并删除反斜杠

Dee*_*dav 4 python

我有一个包含 shell 命令的文件。每个命令可以分成多行(在末尾使用反斜杠):
例如

  cmd1 -opt1 \  
    -opt2 val2  \  
    -opt3 val3 val4
Run Code Online (Sandbox Code Playgroud)

如果最后以反斜杠分隔,我想加入连续的行。我也想在加入后删除反斜杠。

问题类似于:
Input:
['abc', 'def \\', 'ghi \\', 'jkl' , 'yyy \\', 'zzz']
output:
['abc', 'def ghi jkl ', 'yyy zzz']

是循环遍历列表唯一的解决方案吗?

with open("cmd", "r") as fp:
    cmd = ""
    cont = False
    list = []
    for line in fp:
        line = line.rstrip("\n")
        if line.endswith('\\'):
            line = line[:-1]
            if cont:
                cmd = cmd + line
                continue
            if cmd:
                list.append(cmd)
            cmd = line
            cont = True
        else:
            if cont:
                cmd = cmd + line
                if cmd:
                    list.append(cmd)
                cmd = ""
                continue
            cont = False
    print(list)
Run Code Online (Sandbox Code Playgroud)

Clo*_*ion 5

cmd = ['abc', 'def \\', 'ghi \\', 'jkl', 'yyy \\', 'zzz']

res = "\n".join(cmd).replace("\\\n", "").splitlines()

打印(资源)

=> ['abc', 'def ghi jkl', 'yyy zzz']

克洛迪翁