2014-07-13 52 views
25

我的python以某種方式無法在同一目錄中找到任何模塊。 我在做什麼錯? (python2.7)Python無法在同一個文件夾中找到模塊

所以我有一個目錄 '2014_07_13_test',有兩個文件在裏面:

  1. test.py
  2. hello.py

其中hello.py:

# !/usr/local/bin/python 
# -*- coding: utf-8 -*- 

def hello1(): 
    print 'HelloWorld!' 

和test.py:

# !/usr/local/bin/python 
# -*- coding: utf-8 -*- 

from hello import hello1 

hello1() 

不過蟒蛇給我

>>> Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<string>", line 4, in <module> 
ImportError: No module named hello 

有什麼不對?

+0

你是如何執行腳本模塊的頂部將這個?另外什麼是輸入sys的輸出; sys.path' – Salem

+1

嘗試'>>> import test' – martineau

+0

@Casy_fill您是否從目錄運行程序,其中存在哪些文件?對於導入來說,導入和導入的文件共享一個目錄並不重要。重要的是,你的Python解釋器已經正確設置了當前目錄。 –

回答

25

你的代碼很好,我懷疑你的問題是你如何啓動它。

您需要從'2014_07_13_test'目錄啓動python。

打開命令提示符並在'2014_07_13_test'目錄中'cd'。

例如:

$ cd /path/to/2014_07_13_test 
$ python test.py 

如果你不能 'CD' 到這樣的目錄,你可以把它添加到sys.path

在test.py:

import sys, os 
sys.path.append('/path/to/2014_07_13_test') 

或設置/編輯PYTHONPATH

而且一切都應該很好...

......你的'shebang'行(兩個文件中的第一行)有一個小錯誤,'#'和'!'之間不應有空格。

有一個better shebang你應該使用。

此外,您不需要每個文件上的shebang行......只有您打算從shell作爲可執行文件運行的那些行。

+0

非常感謝,那個問題! 不幸的是,SublimeRepl(我使用)不支持從文件夾中立即啓動python,所以現在看來​​我需要導出PATH –

19

在test.py更改進口:

from .hello import hello1 
+6

如果其他人發現此後,這稱爲相對導入並添加到python 2.5:https ://docs.python.org/2.5/whatsnew/pep-328.html – sgfit

3

我有一個類似的問題,我解決它通過明確添加文件的目錄路徑列表:

import os 
import sys 

file_dir = os.path.dirname(__file__) 
sys.path.append(file_dir) 

之後,我從同一個目錄導入沒有問題。

0

這是我使用的通用解決方案。它解決了在同一個文件夾,從模塊導入的問題:

import os.path 
import sys 
sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 

在其中給出了錯誤「無模塊名爲XXXX」

相關問題