当我运行测试时,如何才能输出我的__main__
文件打印输出?我的意思是从该文件打印,而不是unittests文件打印。
我有这个示例结构(所有文件都在同一目录中):
卖弄.朋友:
import argparse
print('print me?') # no output
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('name')
args = parser.parse_args()
print(args.name) # no output
other.朋友:
def print_me():
print('ran print_me')
test.朋友:
import unittest
import sh
import other
class TestMain(unittest.TestCase):
def test_main(self):
print('test_main') # prints it.
sh.python3('main.py', 'test123')
def test_other(self):
print('test_other') # prints it.
other.print_me()
我用python3 -m nose -s
或python3 -m unittest
运行它,但它没有区别,打印不是从main.py
输出,只是直接在测试文件上定义的。这是我得到的:
user@user:~/python-programs/test_main$ python3 -m nose -s
test_main
.test_other
ran print_me
.
----------------------------------------------------------------------
Ran 2 tests in 0.040s
OK
附:当然,如果我在不使用测试的情况下运行main.py
,那么它会正常打印(例如使用python shell / interpreter并使用sh
调用main.py,就像在unittests中一样)
sh.python3
启动新流程,其产出未被nose
捕获。您可以重定向输出打印结果:
print(sh.python3('main.py', 'test123'))