我有以下小 python 脚本来运行本地服务器来测试一些 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
and
Listening at https:127.0.0.1:8000/ . . .
。当然,实际上并非如此work,因为现在服务器没有运行。
我觉得这很令人困惑。前面的行在最后一行之前执行。为什么最后一行会导致前面的行不起作用?
Windows7 上的 Python3 如果有人要问的话,但我怀疑这是否相关。
这可能与“臭名昭著”的需要有关flush为了让你的打印作品发挥作用!
相关阅读材料:
-
有关该主题的理论知识
-
如何刷新Python print 的输出?,
python `print` 不能在循环中工作,正如@Kerorin 所建议的:
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: 这是类似问题的已确认解决方案
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)