我有一个非常简单的Python 3脚本:
f1 = open('a.txt', 'r')
print(f1.readlines())
f2 = open('b.txt', 'r')
print(f2.readlines())
f3 = open('c.txt', 'r')
print(f3.readlines())
f4 = open('d.txt', 'r')
print(f4.readlines())
f1.close()
f2.close()
f3.close()
f4.close()
Run Code Online (Sandbox Code Playgroud)
但它总是说:
IOError: [Errno 32] Broken pipe
Run Code Online (Sandbox Code Playgroud)
我在互联网上看到了解决这个问题的所有复杂方法,但是我直接复制了这个代码,所以我认为代码有问题而不是Python的SIGPIPE.
我正在重定向输出,所以如果上面的脚本命名为"open.py",那么我的运行命令是:
open.py | othercommand
Run Code Online (Sandbox Code Playgroud) 如何将这段代码移植到Python 3,以便它可以同时在Python 2和Python3中运行?
raise BarException, BarException(e), sys.exc_info()[2]
Run Code Online (Sandbox Code Playgroud)
(从http://blog.ionelmc.ro/2014/08/03/the-most-underrated-feature-in-python-3/复制)
奖励问题
做类似的事情有意义吗
IS_PYTHON2 = sys.version_info < (3, 0)
if IS_PYTHON2:
raise BarException, BarException(e), sys.exc_info()[2]
# replace with the code that would run in Python 2 and Python 3 respectively
else:
raise BarException("Bar is closed on Christmas")
Run Code Online (Sandbox Code Playgroud)