python - 使用 fileinput (Python) 进行搜索和替换,同时将消息发送到控制台

标签 python stdout

我有线

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_strfileinputstdout 映射到给定的文件。因此,print newline 和发送到 sys.stdout 的东西被发送到文件而不是控制台。

我想,在这个过程的中间,显示一些消息给控制台,例如我可以显示行中将要进行替换的部分,或一些其他消息,然后继续 print newline 到文件中。如何做到这一点?

最佳答案

来自 Python 文档:

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 以在控制台中显示消息,如下所示:

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 - 使用 fileinput (Python) 进行搜索和替换,同时将消息发送到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32668978/

相关文章:

python - 我们可以重载类对象的行为吗

python - NumPy:用 NaN remove 计算平均值

python - 使用 python selenium 自动测试 CSS 和视觉异常?

python - 如何用 NumPy 计算欧几里得距离?

python - 让 python 脚本打印到终端而不作为标准输出的一部分返回

python - datetime.timestamp 在 pandas apply 和 dataframe 选择中返回不同的值

python - 如何使用 StreamHandler 捕获记录器 stderr 上的输出?

java - 启动一个进程而不消耗它的输出

ant - 如何在ant脚本中重定向stdout stderr?

bash - grep stderr 和上一个命令的 stdout