当调用serve_forever()时,打印语句不起作用? [英] Print statements not working when serve_forever() is called?

查看:858
本文介绍了当调用serve_forever()时,打印语句不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下小的python脚本来运行本地服务器以测试某些html:

I have the following small python script to run a local server for testing some html:

print('opened')

from http.server import HTTPServer, SimpleHTTPRequestHandler

server_address = ('', 8000)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)

print("Listening at https://127.0.0.1:8000/ . . .")
httpd.serve_forever()

当我在终端中运行它时,它会阻塞print语句:什么都不会打印.但是服务器可以工作,我可以在浏览器中转到localhost:8000并访问我的html文件.但是,如果我将最后一行(对serve_forever()的调用)注释掉,则可以正常工作,同时打印"opened"和"listening at https:127.0.0.1:8000/". . .".当然,除了它实际上不能工作之外,因为现在服务器没有运行.

When I run this in the terminal, it blocks the print statements: nothing is printed. But the server works and I can go to localhost:8000 in the browser and access my html files. If, however, I comment out the last line, the call to serve_forever(), it works, printing both 'opened' and 'Listening at https:127.0.0.1:8000/ . . .'. Except of course it doesn't actually work, since now the server isn't being run.

我觉得这很令人困惑.前几行在最后一行之前执行.为什么最后一行会导致前几行不起作用?

I find this very confusing. The previous lines are executed before the last line. Why would the last line cause the previous lines to not work?

如果有人要问问Windows7上的Python3,但我怀疑这是否相关.

Python3 on Windows7 if anyone was going to ask, but I doubt that's relevant.

推荐答案

可能与臭名昭著"有关,需要冲洗,以使打印效果正常!

That maybe related with the "infamous" need to flush in order for your prints to work!

相关阅读材料:

  • Theoretical knowledge on the subject
  • How to flush output of Python print?, python `print` does not work in loop, as suggested by @Kerorin:


因为您使用的是Python 3,并且从3.3版开始,所以您不必遵循上述出色答案中给出的解决方案.
打印内置类型具有选项flush,该选项由默认值为False.做:


Because you are using Python 3 and since version 3.3 you don't have to follow the solutions given in the above great answers.
The print build-in type has an option flush which by default is False. Do:

print('opened', flush=True)

from http.server import HTTPServer, SimpleHTTPRequestHandler

server_address = ('', 8000)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)

print('Listening at https://127.0.0.1:8000/ . . .', flush=True)
httpd.serve_forever()


PS:此是类似问题的公认解决方案

这篇关于当调用serve_forever()时,打印语句不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆