1

运行以下命令,然后尝试运行交互式命令失败...

c:\> python -u -i test.py | tee output.txt
... test.py output ...   

  File "<stdin>", line 1

    ^
SyntaxError: invalid syntax
>>> print "Hi"
  File "<stdin>", line 1
   print "Hi"
              ^

SyntaxError: invalid syntax

一个更简单的测试也失败了:

c:\> python -u 
>>> print "Hi"
  File "<stdin>", line 1
   print "Hi"
              ^

SyntaxError: invalid syntax

Python 2.6.6 (r266:84297, Aug 24 2010, 18:13:38) [MSC v.1500 64 bit (AMD64)] on win32在 Windows 7 上使用。

4

2 回答 2

1

解析器遇到了 Windows"\r\n"行尾问题。Python 的无缓冲模式也是二进制模式,C 运行时不会转换"\r\n""\n"Python 期望的换行符。尝试在第一个提示符处输入以下内容以切换回文本模式:import os, msvcrt; _ = msvcrt.setmode(0, os.O_TEXT) #. 例如:

>>> import sys, os, msvcrt #
>>> line = sys.stdin.readline() #
print "Hi"
>>> line #
'print "Hi"\r\n'

>>> _ = msvcrt.setmode(sys.stdin.fileno(), os.O_TEXT) #
>>> line = sys.stdin.readline()
print "Hi"
>>> line
'print "Hi"\n'
>>> print "Hi"
Hi
于 2015-10-02T16:37:40.707 回答
0

以下是该问题的解决方法:

c:\> python -u 
>>> print "Hi" # This comment prevents the bug
Hi

不幸的是,这是我能想到的最好的多行语句:

c:\> python -u 
>>> exec ''' # Comments still needed inside string
... for i in range(4): # 
...     print i #
... ''' # comment on the end of line
0
1
2
3
于 2015-10-02T15:10:47.967 回答