如何在 python 脚本中调用 sed 命令?

Ada*_*dam 7 python scripts sed

通过python脚本,我试图使用sed命令将字符串替换为文件中的字符串。我subprocess.call在脚本中做到了这一点。

当我在 shell 脚本或命令中运行命令时,它运行良好,但在 python 中我得到一个结果,说“没有输入文件”。知道如何修复该错误吗?

#!/usr/bin/python
import subprocess
subprocess.call(["sed -i -e 's/hello/helloworld/g'","www.txt"], shell=True)
Run Code Online (Sandbox Code Playgroud)

输出

No input file
Run Code Online (Sandbox Code Playgroud)

mur*_*uru 14

使用subprocess.call,命令的每个参数都应该是列表中的一个单独项目(并且shell不应设置为True):

subprocess.call(["sed", "-i", "-e",  's/hello/helloworld/g', "www.txt"])
Run Code Online (Sandbox Code Playgroud)

或者,整个命令应该是一个字符串,带有shell=True

subprocess.call(["sed -i -e 's/hello/helloworld/g' www.txt"], shell=True)
Run Code Online (Sandbox Code Playgroud)

参数的处理方式subprocess.callPopenand类似,如文档所述subprocess.Popen

在带有shell=True的Unix 上,shell 默认为/bin/sh. ...如果args是一个序列,则第一项指定命令字符串,任何附加项都将被视为 shell 本身的附加参数。也就是说,Popen相当于:

Popen(['/bin/sh', '-c', args[0], args[1], ...])
Run Code Online (Sandbox Code Playgroud)


Byt*_*der 6

您应该避免subprocess并实现sedwith Python的功能,例如使用fileinput模块:

#! /usr/bin/python
import fileinput
for line in fileinput.input("www.txt", inplace=True):
    # inside this loop the STDOUT will be redirected to the file
    # the comma after each print statement is needed to avoid double line breaks
    print line.replace("hello", "helloworld"),
Run Code Online (Sandbox Code Playgroud)

  • @PaulaLivingstone `print(line.replace("hello", "helloworld"), end="")` 应该这样做。Python 2 打印语句末尾的尾随逗号抑制了换行符,这正是 Python 3 中关键字参数 `end=""` 所做的。 (2认同)