Why is redirection not working with python scripts?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Setting the correct encoding when piping stdout in python
如预期的那样,下面的代码在python shell(2.7.3)中运行
1 2 | for i in range(999): print i, unichr(i) |
将其保存在文件(asd.py)中,并在shell中运行
1 | $ ./asd.py |
也工作,但
1 | $ ./asd.py > asd.txt |
给予:
1 2 3 4 | Traceback (most recent call last): File"./asd.py", line 3, in <module> print i, unichr(i) UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in position 0: ordinal not in range(128) |
为什么会这样?如何解决这个问题?
试试这个代码
1 2 3 | #!/usr/bin/python for i in range(999): print i, unichr(i).encode('utf-8') |