【问题标题】:Sed one liner not working in python subprocesssed 一个班轮在 python 子进程中不起作用
【发布时间】:2017-09-10 01:12:59
【问题描述】:

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

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()

我做错了什么?

【问题讨论】:

    标签: python json shell sed subprocess


    【解决方案1】:

    一般来说,您可以尝试以下解决方案:

    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
    

    【讨论】:

    • 您是否还必须在\\(\\) 中添加...\...
    【解决方案2】:

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

    那就更好了:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      • 2017-12-08
      • 1970-01-01
      • 2014-03-26
      相关资源
      最近更新 更多