Python 3.2.2从控制台读取

Sha*_*ndM 2 python console python-3.x

我正在使用Python 3.2.2.用户可以选择在控制台上输入值,或者如果他只是按ENTER键则使用默认值.例如,如果用户点击ENTER,则该值设置为c:\ temp,如下面的代码片段所示:

READ=os.read(0,100)
if READ == "\n" :
  READ="c:\\temp"
Run Code Online (Sandbox Code Playgroud)

此代码曾用于python 2.7,但它不适用于python 3.2.2.

在3.2.2中,READ保持为空.有什么建议请改进这段代码吗?

Viv*_*odo 7

该函数在python 2.7中os.read返回class str,但class bytes在python 3.2中.因此,在蟒蛇3.2,if READ == "\n": READ="C:\\temp"永远True.你可能会这样改变:

if str(READ,"ascii") == os.linesep: READ = "C:\\temp"
Run Code Online (Sandbox Code Playgroud)

也许,更确切地说:

import os,sys
READ = os.read(0,100)
if str(READ,sys.stdin.encoding) == os.linesep:
   READ = "C:\\temp"
Run Code Online (Sandbox Code Playgroud)