Python __future__ 在特定模块外使用

5 投票
3 回答
905 浏览
提问于 2025-04-17 01:27

在 Python 2.7 中,通过使用

 from __future__ import division, print_function

我现在可以让 print(1/2) 显示 0.5

不过,有没有办法让这个在 Python 启动时自动导入呢?

我试着使用 sitecustomize.py 这个特殊模块,但导入的内容只在模块内部有效,在命令行里不行。

我知道有人会问我为什么需要这个:我在教青少年学习 Python 时,发现整数除法对他们来说不太容易,所以我们决定切换到 Python 3。不过课程的一个要求是能够绘制函数,而 Matplotlib 非常好用,但只适用于 Python 2.7。

所以我的想法是使用一个定制的 2.7 版本……虽然不是完美,但我没有更好的主意来同时使用 Matplotlib 和新的“自然”除法“1/2=0.5”。

有没有什么建议,或者有没有在 Python 3.2 上可以用的 Matplotlib 替代品?

3 个回答

0

这可能不太实际,但你可以尝试编译一个自定义的Python版本,把Python 3的除法行为移植过来。问题在于,matplotlib 可能需要Python 2的那种除法行为(不过我不太确定)。

2

你不需要重新编译一个新的 Python 2.x 版本。你可以在启动时做到这一点。

正如你发现的,sitecustomize.py 这个文件并不好使。这是因为 from __future__ import IDENTIFIER 其实并不是一个真正的导入。它只是告诉模块要按照特殊规则来编译。任何使用这些特性的模块都必须有 __future__ 的导入,交互式控制台也是如此。

下面这个命令可以启动一个交互式控制台,并且启用 divisionprint_function

python -ic "from __future__ import division, print_function"

你可以在 Linux 上给 python 设置一个别名,或者设置一个启动器来隐藏那些额外的内容。

如果你在使用 IDLE,@DSM 提到的 PYTHONSTARTUP 脚本应该也能在那儿工作。

需要注意的是,这些设置并不是在整个解释器中都有效,它只影响交互式控制台。文件系统中的模块必须明确地从 __future__ 导入才能使用这些特性。如果这造成了问题,我建议你可以做一个模板,里面包含所有需要的导入:

# True division
from __future__ import division

# Modules
import matplotlib

# ... code ...

def main():
    pass

if __name__ == "__main__":
    main()
6

在Python 3上使用matplotlib其实比你想象的要简单得多,你可以查看这个链接了解更多信息:https://github.com/matplotlib/matplotlib-py3; 还有这个链接也很有用:http://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib

那么,为什么不使用PYTHONSTARTUP而是选择sitecustomize.py呢?

localhost-2:~ $ cat startup.py 
from __future__ import print_function
from __future__ import division
localhost-2:~ $ export PYTHONSTARTUP=""
localhost-2:~ $ python
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1/2
0
>>> print("fred",end=",")
  File "<stdin>", line 1
    print("fred",end=",")
                    ^
SyntaxError: invalid syntax
>>> ^D
localhost-2:~ $ export PYTHONSTARTUP=startup.py
localhost-2:~ $ python
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1/2
0.5
>>> print("fred",end=",")
fred,>>> 

撰写回答