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使用输入可以正常工作,但由于评估行为,在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?
推荐答案
由于input()
的Python 2.x版本实际上是无用的,因此您可以简单地用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的方式编写代码.使用2to3
脚本的x版本.
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屋!