Python 中向后兼容的输入调用 [英] Backwards-compatible input calls in Python
问题描述
我想知道是否有人建议编写向后兼容的 input() 调用来检索文件路径?
I was wondering if anyone has suggestions for writing a backwards-compatible input() call for retrieving a filepath?
在 Python 2.x 中,raw_input 对于像/path/to/file 这样的输入工作正常.在这种情况下,对于 3.x,使用 input 工作正常,但由于 eval 行为,在 2.x 中会抱怨.
In Python 2.x, raw_input worked fine for input like /path/to/file. Using input works fine in this case for 3.x, but complains in 2.x because of the eval behavior.
一种解决方案是检查 Python 的版本,并根据版本将 input
或 raw_input
映射到一个新函数:
One solution is to check the version of Python and, based on the version, map either input
or raw_input
to a new function:
if sys.version_info[0] >= 3:
get_input = input
else:
get_input = raw_input
我相信有更好的方法可以做到这一点.有人有什么建议吗?
I'm sure there is a better way to do this though. Anyone have any suggestions?
推荐答案
由于 Python 2.x 版本的 input()
基本上没用,你可以简单地通过 raw_input<覆盖它/代码>:
Since the Python 2.x version of input()
is essentially useless, you can simply overwrite it by raw_input
:
try:
input = raw_input
except NameError:
pass
一般来说,我不会试图针对同时适用于 Python 2.x 和 3.x 的代码,而是以一种适用于 2.x 的方式编写您的代码,并且您会得到一个有效的 3.x 版本使用 2to3
脚本.
In general, I would not try to aim at code that works with both, Python 2.x and 3.x, but rather write your code in a way that it works on 2.x and you get a working 3.x version by using the 2to3
script.
这篇关于Python 中向后兼容的输入调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!