Ahk*_*k86 6 python shell json subprocess sed
我正在尝试合并此 sed 命令来删除子文件中的最后一个逗号。
sed -i -e '1h;1!H;$!d;${s/.*//;x};s/\(.*\),/\1 /' file.json"
Run Code Online (Sandbox Code Playgroud)
当我在命令行中运行它时,它工作正常。当我尝试作为子进程运行时,它不起作用。
Popen("sed -e '1h;1!H;$!d;${s/.*//;x};s/\(.*\),/\1 /' file.json",shell=True).wait()
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
它不起作用,因为当你写 时\1,python 会将其解释为\x01我们的正则表达式不起作用/非法。
这已经更好了:
check_call(["sed","-i","-e",r"1h;1!H;$!d;${s/.*//;x};s/\(.*\),/\1 /","file.json"])
Run Code Online (Sandbox Code Playgroud)
因为拆分为真实列表并将正则表达式作为原始字符串传递有更好的工作机会。并且check_call是您只需要调用一个进程,而不关心其输出。
但我会做得更好:由于 python 擅长处理文件,鉴于你的问题相当简单,我会创建一个完全可移植的版本,不需要sed:
# read the file
with open("file.json") as f:
contents = f.read().rstrip().rstrip(",") # strip last newline/space then strip last comma
# write back the file
with open("file.json","w") as f:
f.write(contents)
Run Code Online (Sandbox Code Playgroud)