【发布时间】:2022-04-13 17:44:35
【问题描述】:
考虑以下程序:
import tempfile
import unittest
import subprocess
def my_fn(f):
p = subprocess.Popen(['cat'], stdout=subprocess.PIPE, stdin=f)
yield p.stdout.readline()
p.kill()
p.wait()
def my_test():
with tempfile.TemporaryFile() as f:
l = list(my_fn(f))
class BuggyTestCase(unittest.TestCase):
def test_my_fn(self):
my_test()
my_test()
unittest.main()
运行它会产生以下输出:
a.py:13: ResourceWarning: unclosed file <_io.BufferedReader name=4>
l = list(my_fn(f))
ResourceWarning: Enable tracemalloc to get the object allocation traceback
.
----------------------------------------------------------------------
Ran 1 test in 0.005s
OK
警告的实际原因是什么以及如何解决?请注意,如果我注释掉unittest.main(),问题就会消失,这意味着它特定于 subprocess+unittest+tempfile。
【问题讨论】:
-
@Leon 但它为什么还要我让警告静音呢? unittest 是否禁用文件关闭或其他什么?
-
unitttest只是设置了比平时更高的警告级别。您可以通过使用-Wd选项运行python 来实现相同的效果。见docs.python.org/3.4/library/…
标签: python