python小技巧[] 禁用脚本中的print

场景

在调试的过程中在脚本中引入了过多的print,如何快速禁用print 函数。

方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import sys, os

# Disable
def blockPrint():
sys.stdout = open(os.devnull, 'w')

# Restore
def enablePrint():
sys.stdout = sys.__stdout__


print 'This will print'

blockPrint()
print "This won't"

enablePrint()
print "This will too"

参考

  1. https://stackoverflow.com/questions/8391411/suppress-calls-to-print-python