gpt4 book ai didi

python - 在 Python 3 中从 CGI 输出二进制数据

转载 作者:太空狗 更新时间:2023-10-30 01:46:45 30 4
gpt4 key购买 nike

这个问题与this one有关.在 Python 2 中从 CGI 脚本打印原始二进制数据时,我没有遇到任何问题,例如:

#!/usr/bin/env python2

import os

if __name__ == '__main__':
with open(os.path.abspath('test.png'), 'rb') as f:
print "Content-Type: image/png\n"
print f.read()

以下是相关的响应 header :

> GET /cgi-bin/plot_string2.py HTTP/1.1
> User-Agent: curl/7.32.0
> Host: 0.0.0.0:8888
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 Script output follows
< Server: SimpleHTTP/0.6 Python/3.3.2
< Date: Fri, 13 Sep 2013 16:21:25 GMT
< Content-Type: image/png

并且结果被解释为图像,正如预期的那样。但是,如果我尝试翻译成 Python 3:

#!/usr/bin/env python

import os
import sys

if __name__ == '__main__':
with open(os.path.abspath('test.png'), 'rb') as f:
print("Content-Type: image/png\n")
sys.stdout.buffer.write(f.read())

什么都没有返回,这里是标题:

> GET /cgi-bin/plot_string3.py HTTP/1.1
> User-Agent: curl/7.32.0
> Host: 0.0.0.0:8888
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 Script output follows
< Server: SimpleHTTP/0.6 Python/3.3.2
< Date: Fri, 13 Sep 2013 16:22:13 GMT
< �PNG
<

我不能再做 print(f.read()) 因为那会打印类似 b'\x89PNG\r\n\x1a\n\x00...。我链接的问题提供了解决方案,但显然在这种环境下不起作用。

想法?

已添加:Note for the future :

This also means print is no good for CGI any more.

最佳答案

使用 sys.stdout.flush 强制在主体之前打印标题:

import os
import sys

if __name__ == '__main__':
with open(os.path.abspath('test.png'), 'rb') as f:
print("Content-Type: image/png\n")
sys.stdout.flush() # <---
sys.stdout.buffer.write(f.read())

或者删除打印,只使用sys.stdout.buffer.write:

import os
import sys

if __name__ == '__main__':
with open(os.path.abspath('test.png'), 'rb') as f:
sys.stdout.buffer.write(b"Content-Type: image/png\n\n") # <---
sys.stdout.buffer.write(f.read())

注意

如果文件很大,

f.read() 可能会导致问题。为防止这种情况,请使用 shutil.copyfileobj :

import os
import shutil
import sys

if __name__ == '__main__':
with open(os.path.abspath('test.png'), 'rb') as f:
sys.stdout.buffer.write(b"Content-Type: image/png\n\n")
shutil.copyfileobj(f, sys.stdout.buffer)

关于python - 在 Python 3 中从 CGI 输出二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18791004/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com