使用 sys 模块的 Python 3 中的奇怪行为 [英] Strange behavior in Python 3 using the sys module

查看:46
本文介绍了使用 sys 模块的 Python 3 中的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在我的 Python 3 解释器(Python 3.4.2,通过 brew 安装)中尝试一些东西时,我遇到了一些我没想到的奇怪输出:

<预><代码>>>>导入系统>>>sys.stdout.write("foo")foo3>>>sys.stderr.write("bar")3酒吧

尝试不同的字符串后,我认为数字是我传递的输入的长度.

我已经在 Python 2.7.8(在输出中没有给出数字)和由 virtualenv 创建的 Python 3.4.2(给出相同的结果)中尝试了这个

输出应该是这样的吗?

解决方案

你说得对,就是长度.在 Python 2 中,File.write() 方法返回 None.当迁移到 Python 3 时,返回值更改为写入的字符数.

您从 stdoutstderr 获得不同输出的原因可能与文件句柄上显示的顺序有关.

对于 stdoutwrite 输出 "foo" 然后 REPL 循环(在 PIN 码和 ATM 机的伟大传统中)输出计数到同一个流.

对于stderr,很可能REPL循环首先输出标准输出(长度),然后是标准错误的内容.

或者,它可能完全不确定,它可能不是您应该依赖的东西,尤其是因为除了解释器的交互模式之外,REPL 循环实际上并不存在.

While I was trying some stuffs in my Python 3 interpreter (Python 3.4.2, installed via brew), I encountered some weird outputs I didn't expected:

>>> import sys
>>> sys.stdout.write("foo")
foo3
>>> sys.stderr.write("bar")
3
bar

After experimenting with different strings, I think the number is the length of the inputs I pass.

I've tried this in Python 2.7.8 (gives no numbers in the outputs) and Python 3.4.2 created by virtualenv (gives the same result)

Is the output supposed to be like this?

解决方案

You're right that it's the length. In Python 2, the File.write() method returned None. When the move was made to Python 3, the return value changed to be the number of characters written.

The reason you're getting the different output from stdout and stderr will probably have to do with the order in which things show up on the file handles.

For stdout, write outputs "foo" then the REPL loop (in the grand tradition of PIN numbers and ATM machines) outputs the count to the same stream.

For stderr, it's likely that the REPL loop outputs standard output first (the length) then the content of standard error.

Or, it may be totally non-deterministic, it's probably not something you should rely on, especially as the REPL loop doesn't really exist except in the interactive mode of the interpreter.

这篇关于使用 sys 模块的 Python 3 中的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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