一次性删除 python 程序中的所有打印语句

Remove all print statements in a python program in one go

最近我继续清理我的 python 代码。我觉得把代码中的所有打印语句一个一个地删除。

在编辑器或 RE 中是否有任何快捷方式可以一次性删除或注释 python 程序中的打印语句?

查找/替换

  • 查找将 print( 替换为 # print( 会将它们注释掉
  • 可能适用于大多数编辑器

Notepad++ 与正则表达式结合使用

  • 免费下载
  • 识别多种编程语言
  • 搜索表达式(print).*
    • ^(print).* 如果你只想从行首打印语句

编写脚本

from pathlib import Path

p = Path('c:\...\path_to_python_files')  # path to directory with files
files = list(p.rglob('*.py'))  # find all python files including subdirectories of p

for file in files:
    with file.open('r') as f:
        rows = [re.sub('(print).*', '', row) for row in f.readlines()]
    
    new_file_name = file.parent / f'{file.stem}_no_print{file.suffix}'

    with new_file_name.open('w') as f:  # you could overwrite the original file, but that might be scary
        f.writelines(rows)

您应该避免使用打印语句。请改用 python 日志模块:

import logging
logging.debug('debug message')

一旦你完成开发并且不需要调试信息,你可以提高日志级别:

logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.WARNING)

这会抑制所有低于警告的日志消息。 有关详细信息,请参阅 DOCS

  1. 在 Ubuntu
  2. 中打开文本编辑器
  3. 按 Ctrl + h
  4. 替换:打印
  5. 替换为:# print