从标准输入读取二进制数据 [英] Reading binary data from stdin

查看:57
本文介绍了从标准输入读取二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Python 2.6 中将标准输入读取为二进制数据?如果是这样,如何?

Is it possible to read stdin as binary data in Python 2.6? If so, how?

我在 Python 3.1 文档 中看到这相当简单,但是在 2.6 中执行此操作的工具似乎不存在.

I see in the Python 3.1 documentation that this is fairly simple, but the facilities for doing this in 2.6 don't seem to be there.

如果 3.1 中描述的方法不可用,有没有办法关闭 stdin 并以二进制模式重新打开?

If the methods described in 3.1 aren't available, is there a way to close stdin and reopen in in binary mode?

更新

为了清楚起见,我在 MS-DOS shell 中使用type"将二进制文件的内容通过管道传输到我的 Python 代码.据我所知,这应该相当于 Unix 'cat' 命令.但是当我测试这个时,我总是比预期的文件大小少一个字节.

Just to be clear, I am using 'type' in a MS-DOS shell to pipe the contents of a binary file to my python code. This should be the equivalent of a Unix 'cat' command, as far as I understand. But when I test this out, I always get one byte less than the expected file size.

更新 #2

首先,感谢您的所有回答.我正在慢慢努力寻找一个真正的、可用的解决方案.最后,我仍在尝试构建一个自包含的 JAR 文件,该文件执行我的 Python 代码,自动传递所有未受污染的命令行参数.

First off, thanks for all the answers. I'm slowly working towards a real, usable solution here. In the end, I'm still trying to build a self contained JAR file that executes my Python code automatically passing through all the command line arguments untainted.

我选择 Java/JAR/Jython 路线的原因是因为我的主要外部库之一只能作为 Java JAR 使用.但不幸的是,我以 Python 开始了我的工作.不久前将我的代码转换为 Java 可能更容易,但由于这些东西都应该是兼容的,我想我会尝试通过它并证明它可以完成.

The reason I'm going the Java/JAR/Jython route is because one of my main external libraries is only available as a Java JAR. But unfortunately, I had started my work as Python. It might have been easier to convert my code over to Java a while ago, but since this stuff was all supposed to be compatible, I figured I would try trucking through it and prove it could be done.

如果有人想知道,这也与我前几天问的问题有关.

In case anyone was wondering, this is also related to the question I asked a few days ago.

从 Eclipse 打包和部署 Jython 程序

在这个问题中回答了部分问题.

Some of that question was answered in this question.

因此,我将尝试用一些关于我迄今为止所发现的内容的注释来更新我的原始问题.

So I'll try to update my original question with some notes on what I have figured out so far.

推荐答案

使用 -u 命令行开关 强制 Python 2 将 stdin、stdout 和 stderr 视为二进制无缓冲流.

Use the -u command line switch to force Python 2 to treat stdin, stdout and stderr as binary unbuffered streams.

C:> type mydoc.txt | python.exe -u myscript.py

这篇关于从标准输入读取二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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