【问题标题】:Sed with Python/subprocess.call: How can I make python execute this call to sed使用 Python/subprocess.call 进行 Sed:如何让 python 执行对 sed 的调用
【发布时间】:2013-11-15 14:50:42
【问题描述】:

我从 shell 运行的工作 sed 是:

sed -re 's/(::\s+ni\s+=)[^=]*$/\1 512/' test.dat

但是,我无法通过 Python 的 subprocess.call 运行它:

我有以下几点:

infile = 'test.dat'
cmd= [
      "sed",
      "-re",
      "s/(::\s+ni\s+=)[^=]*$/\1 512/",
      infile
     ]
subprocess.call(cmd, stdout=open('out_test.dat','w'))

我尝试了许多不同的方法,但总是得到非零退出状态。

【问题讨论】:

  • 是不是因为你的正则表达式应该包含用双引号括起来的单引号,即"'s/(::\s+ni\s+=)[^=]*$/\1 512/'"
  • 你需要转义你的斜线。
  • 为什么不使用 Python 内置的正则表达式替换功能?
  • @Bill:它在shell命令行中没有被双引号包围的单引号。
  • 另外,sed 不是在向 stderr 写入错误消息,您可以在运行脚本时看到吗?

标签: python regex bash replace sed


【解决方案1】:

问题是 Python 字符串 "s/(::\s+ni\s+=)[^=]*$/\1 512/" 包含一个 control-A,您需要一个反斜杠和一个 1。每当您将正则表达式编写为字符串文字时,如果可能,您希望使用原始字符串,或者转义如果不是反斜杠。因此,只需将该行更改为:

r"s/(::\s+ni\s+=)[^=]*$/\1 512/",

【讨论】:

    猜你喜欢
    • 2014-06-10
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 2015-07-04
    • 2018-12-17
    • 1970-01-01
    • 2019-07-03
    相关资源
    最近更新 更多