【问题标题】:Sed with space in python在 python 中带空格的 Sed
【发布时间】:2017-12-19 03:42:11
【问题描述】:

我尝试在VMkernel 中使用 sed 执行替换。我使用了以下命令,

sed s/myname/sample name/g txt.txt

我收到一条错误消息,提示 sed: unmatched '/'。 我用\ 替换了空格。它奏效了。

当我尝试使用 python 时,

def executeCommand(cmd):
   process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
   output, error = process.communicate()
   print (output.decode("utf-8")) 
executeCommand('sed s/myname/sample\ name/g txt.txt')

我再次收到错误sed: unmatched '/'。我使用 \s 而不是空格,我将名称替换为 samplesname

如何用空格替换字符串?

【问题讨论】:

  • split() 默认按空格分割...所以当然会有问题...使用\s python 字符串起作用...改用r'string' 格式
  • 报价。在 shell 中:sed 's/myname/sample name/g' txt.txt 在 python 中:executeCommand('sed s/myname/sample\\ name/g txt.txt')(额外的反斜杠)- 未经测试。
  • 通过使用split(),您将列表['sed', 's/myname/sample\', 'name/g', 'txt.txt'] 发送到子进程。 sed 表达式被分成两半。最好自己创建列表,这样您就可以完全控制。

标签: python sed vcenter


【解决方案1】:

最简单的事情就是不要聪明地拆分命令:

executeCommand(['sed', 's/myname/sample name/g', 'txt.txt'])

否则,您将打开一罐蠕虫,有效地扮演 shell 解析器的角色。


或者,您可以在 shell 中运行命令,让 shell 解析并运行命令:

import subprocess

def executeCommand(cmd):
   process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
   # Or:
   # This will run the command in /bin/bash (instead of /bin/sh)
   process = subprocess.Popen(['/bin/bash', '-c', cmd], stdout=subprocess.PIPE)
   output, error = process.communicate()
   print (output.decode("utf-8")) 

executeCommand("sed 's/myname/sample name/g' txt.txt")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    相关资源
    最近更新 更多