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

允我心安 提交于 2020-02-01 05:55:15

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/32668978/using-fileinput-python-for-a-search-and-replace-while-also-sending-messages-to

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!