Ubuntu: How do I call a sed command in a python script? [closed]


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'","www.txt"], shell=True)  


No input file  


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


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. … 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], ...])  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »