【问题标题】:bash in python : sed unterminated s command [duplicate]python中的bash:sed未终止的s命令[重复]
【发布时间】:2014-09-30 17:19:57
【问题描述】:

以下命令在 bash 中运行良好。

/folk/vlm/commandline/./vlmTool find -l all | grep -e "^Target ID" -e "City" -e "Zone" | sed "s#.*City.*#&\n#g" > new.txt

但在 python 中,当我尝试执行相同的命令时,我得到:

['sed', 's#.*City.*#&\n#g']
**sed: -e expression #1, char 12: unterminated `s' command**

代码:

#!/usr/local/bin/python -tt

import subprocess
import shlex
cmd = '/folk/vlm/commandline/./vlmTool find -l all | grep -e "^Target ID" -e "City" -e "Zone" | sed "s#.*City.*#&\n#g" > new.txt'
cmd2= "/folk/vlm/commandline/./vlmTool find -l all"
args1 = shlex.split(cmd2)
cmd3 = 'grep -e "^Target ID" -e "City" -e "Zone"'
args2 = shlex.split(cmd3)
cmd4 =  'sed "s#.*City.*#&\n#g"'
args3 = shlex.split(cmd4)
print args3
p1 = subprocess.Popen(args1, stdout=subprocess.PIPE)
p2 = subprocess.Popen(args2, stdin=p1.stdout, stdout=subprocess.PIPE)
p3 = subprocess.Popen(args3, stdin=p2.stdout, stdout=subprocess.PIPE)
p1.stdout.close()
p2.stdout.close()
output = p3.communicate()[0]

【问题讨论】:

  • 试试['sed', r's#.*City.*#&\n#g']

标签: python bash


【解决方案1】:

\n 序列在 python 中被理解为换行符的转义序列;所以 sed 认为你已经完成了 s 命令并开始一个新的命令。要获取包含在字符串中的反斜杠,可以将其转义,如 ...\\n... 或使用原始字符串:r's#.*City.*#&\n#g'

【讨论】:

  • 谢谢...\\n 使用了所需的输出,但使用 r 并没有为我提供所需的结果。
  • 你是最棒的。
  • 谢谢。节省了我的时间。已经在谷歌上搜索了一段时间。
猜你喜欢
  • 2013-06-11
  • 2012-07-10
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
  • 2016-07-29
  • 2019-05-04
  • 2013-11-27
  • 2012-05-05
相关资源
最近更新 更多