Python3 - 当 运行 单元测试时输出 __main__ 文件(来自实际程序,而不是单元测试)

Python3 - output __main__ file prints when running unittests (from actual program, not unittests)

如何在 运行 测试时输出我的 __main__ 文件打印件?我的意思是从那个文件打印,而不是单元测试文件打印。

我有这个示例结构(所有文件都在同一目录中):

main.py:

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.py:

def print_me():
    print('ran print_me')

test.py:

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 -spython3 -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

P.S。当然,如果我 运行 main.py 不使用测试,那么它会正常打印(例如使用 python shell/interpreter 并使用 sh 调用 main.py,就像在单元测试中一样)

sh.python3 启动新进程,其输出未被 nose 捕获。您可以重定向打印结果的输出:

print(sh.python3('main.py', 'test123'))