Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using fileinput (Python) for a search-and-replace while also sending messages to console

Tags:

python

stdout

I have lines

for line in fileinput.input(file_full_path, inplace=True):
    newline, count = re.subn(search_str, replace_str, line.rstrip())
    # ... display some messages to console ...
    print newline # this is sent to the file_full_path

which are supposed to replace all occurrences of search_str in the file file_full_path and replace them with replace_str. The fileinput maps stdout to the given file. So, print newline and things sent to sys.stdout are sent to the file and not to the console.

I would like to, in the middle of the process, display some messages to console, e.g. I could show the portion of the line in which the replacement is going to occur, or some other messages, and then continue with the print newline into the file. How to do this?

like image 581
Anna Taurogenireva Avatar asked Sep 19 '15 13:09

Anna Taurogenireva


1 Answers

From Python docs:

Optional in-place filtering: if the keyword argument inplace=1 is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently).

so you should write to stderr to display messages in the console, like this:

import sys

for line in fileinput.input(file_full_path, inplace=True):
    newline, count = re.subn(search_str, replace_str, line.rstrip())
    sys.stderr.write("your message here")
    print newline
like image 154
pzelasko Avatar answered Nov 10 '22 19:11

pzelasko