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

问题描述 投票:1回答:1

当我运行测试时,如何才能输出我的__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 -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

附:当然,如果我在不使用测试的情况下运行main.py,那么它会正常打印(例如使用python shell / interpreter并使用sh调用main.py,就像在unittests中一样)

python python-3.x unit-testing stdout main
1个回答
1
投票

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

print(sh.python3('main.py', 'test123'))
© www.soinside.com 2019 - 2024. All rights reserved.