擅长:python、mysql、java
<p>基于@fakerainbrigan解决方案,我建议一个更安全的解决方案:</p>
<pre class="lang-py prettyprint-override"><code>import os, sys
class HiddenPrints:
def __enter__(self):
self._original_stdout = sys.stdout
sys.stdout = open(os.devnull, 'w')
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.close()
sys.stdout = self._original_stdout
</code></pre>
<p>然后你可以这样使用它:</p>
<pre><code>with HiddenPrints():
print("This will not be printed")
print("This will be printed as before")
</code></pre>
<p>这更安全,因为您不能忘记重新启用stdout,这在处理异常时尤其重要。</p>
<pre><code># This is an example of not-so-good solution
# without 'with' context manager statement.
try:
disable_prints()
something_throwing()
# enable_prints() This wouldn't be enough!
except ValueError:
handle_error()
finally:
enable_prints() # That's where it needs to go.
</code></pre>
<p>如果您忘记了<code>finally</code>子句,那么您的<code>print</code>调用将不再打印任何内容。使用<code>with</code>语句,这是不可能的。</p>
<p>使用<code>sys.stdout = None</code>是不安全的,因为有人可以调用sys.stdout.write()等方法</p>