无法打印与子进程一起运行的python脚本的输出

时间:2016-12-27 21:18:41

标签: python subprocess

我尝试测试服务器,并希望在测试结束时打印输出

class TestHandler(TestCase):

    def setUp(self):
        cmd = [
            'python', '-m', 'server',
            '-f', write_to_path,
            '--debug'
        ]
        self.server = Popen(cmd, universal_newlines=True, cwd=root_dir_path,
                            stdout=PIPE, stderr=PIPE)

        # also tried this, did not help
        # cmd = [
        #     'python -m server --debug -f ' + write_to_path
        # ]
        # self.server = Popen(cmd, shell=True, universal_newlines=True, cwd=root_dir_path,
        #                     stdout=PIPE, stderr=PIPE)

    def tearDown(self):
        try:
            outs, errs = self.server.communicate(timeout=2)
            print(outs, errs)
        except TimeoutExpired:
            print("kill")
            self.server.kill()
            outs, errs = self.server.communicate()
            print(outs, errs) # empty output here

    def testWordWithoutParent(self):
        pass

当我运行它时,stdout和err是空的,但是执行了服务器代码(我在服务器/ __ main__.py中用pdb测试了它的主函数)

 ~/Documents/LINGUALEO/lingualeo2anki $ python -m unittest
.kill

.
----------------------------------------------------------------------
Ran 2 tests in 2.006s

OK

Source here

我在stackowerflow上试了很多答案差不多3个小时没人帮忙,我放弃了。

1 个答案:

答案 0 :(得分:0)

终止信号处理不当。

try:
    httpd = HTTPServer(config.server_address, Handler)
    debug('http server is running...listening on port %s', config.port)
    httpd.serve_forever()
except KeyboardInterrupt:
    httpd.server_close()
    sys.exit(0)
finally:
    httpd.socket.close()
    httpd.server_close()
    debug("finnaly")

成为

server = None

def close_server(signum, frame):
    debug("Signal handler called with signal %s", signum)
    if server:
        server.server_close()
        sys.exit()

server = HTTPServer(config.server_address, Handler)
signal.signal(signal.SIGINT, close_server)
signal.signal(signal.SIGTERM, close_server)
debug('http server is running...listening on port %s', config.port)
server.serve_forever()