我有一个包含 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 …Run Code Online (Sandbox Code Playgroud) str = "cmd -opt1 { a b c d e f g h } -opt2"
Run Code Online (Sandbox Code Playgroud)
我想要这样的输出:
[ 'cmd', '-opt1', '{ a b c d e f g h }', '-opt2' ]
Run Code Online (Sandbox Code Playgroud)