2015-05-13 217 views
0

我想創建一個名爲knife的python應用程序,可以從CLI執行,問題是它無法導入模塊。Python安裝包不會導入模塊

我的文件結構是這樣的:

my_project/ 
    knife/ 
     __init__.py 
     knife.py 
     external.py 
    setup.py 

我setup.py看起來是這樣的:

#!/usr/bin/python 

from setuptools import setup, find_packages 

setup(name='Knife', 
     version='0.3', 
     description='Very cool project', 
     author='John Doe', 
     author_email='[email protected]', 
     packages=find_packages(), 
     py_modules=['knife.external'], 
     scripts=['knife/knife.py'], 
    ) 

我knife.py看起來是這樣的:

#!/usr/bin/python 

import external 

def main(): 
    print("Execute main function") 

if __name__ == "__main__": 
    main() 

所以後安裝與setup.py安裝模塊,我試圖運行刀,但不斷拋出這個錯誤:

$ knife.py 
Traceback (most recent call last): 
    File "/usr/bin/knife.py", line 4, in <module> 
    __import__('pkg_resources').run_script('Knife==0.3', 'knife.py') 
    File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 723, in run_script 
    self.require(requires)[0].run_script(script_name, ns) 
    File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 1643, in run_script 
    exec(script_code, namespace, namespace) 
    File "/usr/lib/python2.7/site-packages/Knife-0.3-py2.7.egg/EGG-INFO/scripts/knife.py", line 3, in <module> 
    __requires__ = 'Knife==0.3' 
ImportError: No module named external 

究竟發生了什麼?我該如何解決它?

回答

1

external.py也應該發貨。因此,setup.py添加了external.py:

scripts=['knife/knife.py', 'knife/external.py'], 
+0

如果external.py是一個文件夾而不是文件,該怎麼辦? I.E.刀/外部/ __ init__.py –

+1

是的,所有的依賴需要複製。 –

+0

如果有很多依賴關係,有沒有最簡單的方法來做到這一點?我看了一下django項目setup.py,它只有一個CLI腳本文件,使用相同的結構我得到了錯誤:'pkg_resources.ResolutionError:沒有名爲'knife.py'的腳本 –