2010-09-09 65 views
0

我是新來的蟒蛇,我面臨一個問題:什麼是導入模塊的強制步驟?

我試圖擴展我的SConstruct文件,並導入位於我的項目的子目錄中的模塊。

這裏是我的SConstruct文件:

import os, sys 
sys.path.append(os.path.abspath(os.path.join('.', 'custom_dir'))) 
import mymodule 

mymodule.foo() 

這裏是mymodule.py文件,定位到一個名爲custom_dir子目錄:

def foo(): 
    print 'foo' 

我也有一個__init__.py文件在我custom_dir目錄。

當我執行scons

File ".\SConstruct", line 22, in <module> 
    mymodule.foo() 
AttributeError: 'module' object has no attribute 'foo' 

如果我做python.exe SConstruct我得到了相同的結果。

我在這裏做錯了什麼?

+1

'def foo()'後面需要冒號。如果你從Python的命令行輸入mymodule,然後輸入mymodule .__ dict__,會發生什麼? – 2010-09-09 10:33:14

+0

@Mike:如果我在與我的模塊相同的目錄中啓動命令行工具,我可以從命令行成功加載和使用模塊。 – ereOn 2010-09-13 08:33:37

+0

實際上,我在想'mymodule .__ dict__'的輸出是什麼,但現在已經沒有意義了。 – 2010-09-13 14:38:58

回答

1

你應該確保你正在導入正確的模塊,而不是一個不同的名稱相同的別的地方在你的路徑

嘗試python.exe -v SConstruct

print mymodule.__file__權運行程序之前print mymodule.foo()

+0

我有一個與衝突模塊名稱相同的目錄。非常感謝這種調試技術;) – ereOn 2010-09-13 09:12:04

1

小心路徑操縱;麻煩會找到你。

看看http://docs.python.org/tutorial/modules.html

我已經設置了什麼,我認爲你正在嘗試下面的事情。這應該工作。

文件結構:

/SConstruct.py 
/custom_dir/ 
/custom_dir/__init__.py 
/custom_dir/mymodule.py 

/custom_dir/__init__.py是空白

/custom_dir/mymodule.py:

def foo(): 
    print 'foo' 

/SConstruct.py:

import custom_dir.mymodule as mymodule 

mymodule.foo() 
+0

我得到這個:'AttributeError:'module'object has no attribute'foo': 文件「C:\ workbench \ scons_test \ SConstruct」,第18行: mymodule.foo() – ereOn 2010-09-13 08:28:27

0

您可以訪問SCons分類例如,除SConstruct以外的其他模塊的環境包括

from SCons.Script import * 

請參閱文檔here

此外,而不是使用'。'爲了表示構建樹的根,您應該使用Dir('#').path

相關問題