简体   繁体   English

sys.stdout.write对于Windows上的二进制文件无法正常工作

[英]sys.stdout.write not working properly for binary files on windows

I have a python script that handles all the incoming requests and generates/returns content based on the type of input. 我有一个处理所有传入请求并根据输入类型生成/返回内容的python脚本。

When I run my python script with 当我运行我的python脚本时

print "Content-Type: text/plain\r\n\r\n" #debug mode

The generated html is what I expect to be. 生成的html是我期望的。 But, when I comment the above line, it truncates a part of the output. 但是,当我评论以上行时,它会截断输出的一部分。 I generate the html by reading a file and using sys.stdout.write to write to the output. 我通过读取文件并使用sys.stdout.write生成HTML来写入输出。

Code links : 代码链接

driver: http://pastebin.com/VULgJWEx (contains the print statement) 驱动程序: http : //pastebin.com/VULgJWEx (包含打印语句)

Handler: http://pastebin.com/j87rrQyx (contains writeFileToStdout which writes to stdout) 处理程序: http : //pastebin.com/j87rrQyx (包含写入标准输出的writeFileToStdout)

Sample : 样品

with Content-type: text - 内容类型:文本-

Content-Length: 105

Content-Type: application/vnd.apple.mpegurl

#EXTM3U

#EXT-X-TARGETDURATION:10

#EXT-X-MEDIA-SEQUENCE:118394

#EXTINF:5,

20110203T230818-01-118403.ts


without print: 不打印:

 Content-Length: 105 Content-Type: application/vnd.apple.mpegurl #EXTM3U #EXT-X-TARGETDURATION:10 #EXT-X-MEDIA-SEQUENCE:118394 #EXTINF:5, 20110203T230818-01-118403 #(ts is missing!!) 

The last ts is truncated. 最后的ts被截断。


Would anyone have a clue why the print is causing this ? 有人知道打印的原因吗? (or is it something else?) (或者是别的什么?)

There was not a problem in print or stdout (as expected). 在打印或标准输出中没有问题(如预期的那样)。

I was trying to read from a binary file (on windows) and write it to stdout. 我试图从二进制文件(在Windows上)读取并将其写入stdout。 Since the 'sys' module opens the 'stdout' file object on your behalf and normally does so in text mode, things were going haywire. 由于“ sys”模块代表您打开“ stdout”文件对象,并且通常在文本模式下打开,因此事情变得一团糟。

So, to fix this problem: 因此,要解决此问题:

msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

This link does a good job of explaining the problem. 链接很好地解释了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM