gpt4 book ai didi

python - 如何在 python 2 和 3 中覆盖?

转载 作者:太空宇宙 更新时间:2023-11-03 17:39:56 25 4
gpt4 key购买 nike

我正在尝试编写一个简单的程序,它将在终端中显示一个与 python 2.7 和 3.3 兼容的旋转加载图标。虽然 from __future__ import print_function 语句可以工作,但我在 python 2 中得到的只是一个空行。然后我尝试了 sys.stdout.write 但结果也是空白。

这是我的简化代码:

from __future__ import print_function
import time
import sys
import itertools

def load_icon(pause=0.5, timeout=None):
tic = time.time()
try:
while (not timeout) or timeout < time.time() - tic:
for symbol in itertools.cycle('\|/-'):
##print('\r{} '.format(symbol), end='') # Old version
sys.stdout.write('\r{} '.format(symbol)) # New
# Neither of the above work in py 2.7 yet do in py 3.3
time.sleep(pause)
except KeyboardInterrupt:
pass
finally:
sys.stdout.write('\r \n')

if __name__ == '__main__':
load_icon(*[float(arg) for arg in sys.argv[1:]])

这是结果:

$ python3 load_icon.py
/
$ # a rotating line
$ python2 load_icon.py

$ # nothing shown

有没有办法解决这个问题,而无需为每个版本创建两个单独的文件?我在 Linux centOS6 上使用 python 2.7.8 和 3.3.1 运行它。提前致谢。

最佳答案

显式地flushing sys.stdout似乎可以在Python 2中修复它:

            sys.stdout.write('\r{} '.format(symbol))
sys.stdout.flush()

print 函数还有一个 flush 参数:

            print('\r{} '.format(symbol), end='', flush=True)

但是,这似乎只在 Python 3 中有效。使用 from __future__ import print_function 导入的 print 版本似乎缺少此参数。

关于python - 如何在 python 2 和 3 中覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30709143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com