Through python script, I am trying to replace a string by a string in a file using sed command. I do that through subprocess.call as it in the script.

When I run the command in the shell script or command, it runs fine, but in python I get a result saying "No input file". Any idea how to fix that error?

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

Output

No input file 
2

2 Answers

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', ""]) 

Or, the entire command should one string, with shell=True:

subprocess.call(["sed -i -e 's/hello/helloworld/g' "], 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. … If args 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], ...]) 
1

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("", 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"), 
6