调用serve_forever()时打印语句不起作用?

tem*_*ame 2 python simplehttpserver python-3.x

我有以下小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()
Run Code Online (Sandbox Code Playgroud)

当我在终端中运行它时,它会阻止print语句:没有打印.但服务器工作,我可以localhost:8000在浏览器中访问我的html文件.但是,如果我注释掉最后一行,则调用serve_forever(),它可以打印"打开"和"收听https:127.0.0.1:8000 /"..'.当然,它实际上并不起作用,因为现在服务器没有运行.

我觉得这很混乱.前一行在最后一行之前执行.为什么最后一行会导致前一行不起作用?

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

Joh*_*fis 8

这可能与"臭名昭着"需要冲洗,以使您的打印工作!

相关阅读材料:


因为您使用的是Python 3,从版本3.3开始,您不必遵循上述优秀答案中给出的解决方案.
打印内置的类型有一个选项flush默认为False.做:

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()
Run Code Online (Sandbox Code Playgroud)

PS:这是一个类似问题的确认解决方案


Gal*_*man 6

有这种现象的几种解决方案:

禁用输出缓冲

使用写入模式重新打开stdout文件描述符,并将0作为缓冲区大小(未缓冲).我建议将此行写为代码中的第一行,这样,除了stdout缓冲区之外,所有代码都将保持不变:

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
Run Code Online (Sandbox Code Playgroud)

使用无缓冲的二进制stdout和stderr运行python

强制stdout和stderr流的二进制层(可用作其缓冲区属性)无缓冲.如果写入控制台,文本I/O层仍将是行缓冲的,如果重定向到非交互式文件,则仍然是块缓冲的.

所以只需像这样运行你的脚本:

python -u <your_pyScript>
Run Code Online (Sandbox Code Playgroud)

或者通过设置环境变量 PYTHONUNBUFFERED

flush关键字参数设置为true

从Python 3.3开始,您可以强制print()刷新普通函数,而无需使用sys.stdout.flush()"flush"关键字参数设置为true:

print("...", flush=True)
Run Code Online (Sandbox Code Playgroud)

将一个模块中的默认值更改为 flush=True

您可以通过使用functools.partial模块的全局范围来更改打印功能的默认值:

import functools
print = functools.partial(print, flush=True)
Run Code Online (Sandbox Code Playgroud)

我们可以看到它的工作方式与预期一致:

>>> print('foo')
foo
Run Code Online (Sandbox Code Playgroud)


Ser*_*rge 5

import logging
logging.info('Listening at https://127.0.0.1:8000/ . . .')
Run Code Online (Sandbox Code Playgroud)

嗨,请考虑使用日志记录而不是打印,您不想打扰print语句的所有缺点。打印适用于初学者,可能适用于交互模式。所有专业的服务器端编码人员都依赖日志记录。

入python,为什么要使用日志记录而不是print?有关完整记录日志的信息。

  • 实际上并没有回答这个问题,这是关于理解为什么会发生这种情况,但无论如何确实提供了一个非常有用的相关建议!已投赞成票。我之前没有遇到过日志记录模块。 (2认同)