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.call与Popenand类似,如文档所述subprocess.Popen:
在带有
shell=True的Unix 上,shell 默认为/bin/sh. ...如果args是一个序列,则第一项指定命令字符串,任何附加项都将被视为 shell 本身的附加参数。也就是说,Popen相当于:Run Code Online (Sandbox Code Playgroud)Popen(['/bin/sh', '-c', args[0], args[1], ...])
您应该避免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)