使用文件输入 (Python) 进行搜索和替换,同时还将消息发送到控制台 [英] Using fileinput (Python) for a search-and-replace while also sending messages to console
问题描述
我有线条
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
应该替换文件 file_full_path
中所有出现的 search_str
并将它们替换为 replace_str
.fileinput
将 stdout
映射到给定的文件.所以,print newline
和发送到 sys.stdout
的东西被发送到文件而不是控制台.
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.
我想在过程中向控制台显示一些消息,例如我可以显示将要发生替换的行的部分或其他一些消息,然后继续将 print newline
插入文件.如何做到这一点?
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?
推荐答案
来自 Python 文档:
From Python docs:
可选的就地过滤:如果关键字参数 inplace=1 是传递给 fileinput.input() 或 FileInput 构造函数,文件被移动到备份文件,标准输出被定向到输入文件(如果与备份文件同名的文件已经存在,则将被默默替换)
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).
因此您应该写入 stderr 以在控制台中显示消息,如下所示:
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
这篇关于使用文件输入 (Python) 进行搜索和替换,同时还将消息发送到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!