2011-09-05 72 views
5

以外在蟒2.7,通過使用的Python __future__特定模塊

from __future__ import division, print_function 

我現在可以有print(1/2)0.5表示。

然而,有可能有這自動導入到python啓動?

我嘗試使用sitecustomize.py特殊模塊,但inport僅在模塊內有效,而不在shell中有效。

因爲我確信人們會問爲什麼我需要這樣的東西:教給Python的青少年我注意到整數部分對他們來說並不容易,所以我們決定切換到Python 3.然而,該課程的一個要求是能夠繪製功能和Matplotlib是相當不錯的,但只對Python 2.7有效。

所以我的想法是使用自定義2.7安裝...並不完美,但我沒有更好的主意,讓Matplotlib和新的「自然」部門「1/2 = 0.5」。

任何意見或可能是一個Matplotlib替代工作在Python 3.2?

回答

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,>>> 
+0

是我見過的工作已經開始4個月前,但我沒有設法手動安裝numpy的(在我的64位計算機上),所以我最終使用這個軟件包:http://www.enthought.com/products/epd_free.php 我會嘗試PYTHONSTARTUP –

+0

'PYTHONSTARTUP'肯定是要走的路。 –

0

這可能不實用,但您可能能夠編譯自定義Python,並且Python 3分割行爲被反向移植。這個問題是matplotlib可能需要Python 2的行爲(雖然我不確定)。

2

無需編譯新版本的Python 2.x.你可以在啓動時做到這一點。

如您所見,sitecustomize.py無效。這是因爲from __future__ import IDENTIFIER不是的導入。它標記要在特殊規則下編譯的模塊。任何使用這些功能的模塊必須具有導入__future__以及交互式控制檯。

以下shell命令將divisionprint_function積極啓動交互式控制檯:

python -ic "from __future__ import division, print_function" 

你可以別名python(在Linux上)或設置一個啓動器來隱藏多餘的東西。

如果您使用的是IDLE,PYTHONSTARTUP腳本@DSM建議應該在那裏工作。

請注意,這些在整個解釋器中都不是全局的,它隻影響交互式控制檯。文件系統上的模塊必須明確地從__future__導入才能使用該功能。如果這是一個問題,我建議做掉了所有所需的進口模板的基礎工作:

# True division 
from __future__ import division 

# Modules 
import matplotlib 

# ... code ... 

def main(): 
    pass 

if __name__ == "__main__": 
    main()