How do I call a sed command in a python script? [closed]
Solution 1:
With subprocess.call
, either every argument to the command should be a separate item in the list (and shell
should not be set to True
):
subprocess.call(["sed", "-i", "-e", 's/hello/helloworld/g', "www.txt"])
Or, the entire command should one string, with shell=True
:
subprocess.call(["sed -i -e 's/hello/helloworld/g' www.txt"], shell=True)
The arguments are treated similarly for subprocess.call
and Popen
, and as the documentation for subprocess.Popen
says:
On Unix with
shell=True
, the shell defaults to/bin/sh
. … Ifargs
is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. That is to say,Popen
does the equivalent of:Popen(['/bin/sh', '-c', args[0], args[1], ...])
Solution 2:
You should avoid subprocess
and implement the functionality of sed
with Python instead, e.g. with the fileinput
module:
#! /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"),