Sed 一行在 python 子进程中不起作用



我正在尝试合并此 sed 命令以删除 son 文件中的最后一个逗号。

sed -i -e '1h;1!H;$!d;${s/.*//;x};s/(.*),/1 /' file.json"

当我在命令行中运行它时,它工作正常。当我尝试作为子进程运行时,它不起作用。

   Popen("sed -e '1h;1!H;$!d;${s/.*//;x};s/(.*),/1 /' file.json",shell=True).wait()

我做错了什么?

它不起作用,因为当你编写1时,python将其解释为x01,而我们的正则表达式不起作用/是非法的。

这已经更好了:

check_call(["sed","-i","-e",r"1h;1!H;$!d;${s/.*//;x};s/(.*),/1 /","file.json"])

因为拆分为真实列表并将正则表达式作为原始字符串传递有更好的工作机会。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)

通常,您可以尝试以下解决方案:

  1. 传递原始字符串,如前所述
  2. 转义"\"字符。

此代码还执行您需要的操作:

Popen("sed -e '1h;1!H;$!d;${s/.*//;x};s/(.*),/\1 /' file.json", shell=True).wait()

try:
    check_call(["sed", "-i", "-e", "1h;1!H;$!d;${s/.*//;x};s/(.*),/\1 /", "file.json"])
except:
    pass # or handle the error

最新更新