Python 没有方法的模块包

Python Module Package with no methods

我写了一个Python模块,只有两个方法,帮助和检查。 Check 只接受一个字符串文件名并用它做一些事情。当我导入模块时,其中没有方法。只有__name__之类的东西,但目录中既没有check也没有help。

我正在导入文件。 lyricCheck.py

这是我在 lyricCheck.py 中的代码:

#!/usr/bin/python
#python lyric checker
#Jim Boulter
#January 19, 2015
#Copyright 2015

import sys
import urllib2
import fileinput
from decimal import *
from re import *
from pygoogle import pygoogle

def help():
    print 'usage: python check.py filename.txt\n'
    print 'input line structure: artist name; song title\n'

def check(filename):
    if(str(filename).lower == "help" or str(filename).lower == "-h"):
        help()
        return
    #do lots of other stuff

如果您正在像这样创建您的包,我相信您是,您需要从您的包中导入您的模块:

~/tmp$ mkdir lyricCheck
~/tmp$ cd lyricCheck/
~/tmp/lyricCheck$ touch __init__.py
~/tmp/lyricCheck$ cat > lyricCheck.py
#!/usr/bin/python
#python lyric checker
#Jim Boulter
#January 19, 2015
#Copyright 2015

import sys
import urllib2
import fileinput
from decimal import *
from re import *
from pygoogle import pygoogle

def help():
    print 'usage: python check.py filename.txt\n'
    print 'input line structure: artist name; song title\n'

def check(filename):
    if(str(filename).lower == "help" or str(filename).lower == "-h"):
        help()
        return
    #do lots of other stuff
~/tmp/lyricCheck$ cd ..
~/tmp$ python 
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import lyricCheck
>>> dir(lyricCheck)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']

这是我的收获,如果我有 pygoogle,这应该会奏效,所以这就是我发现问题的方式:

>>> from lyricCheck import lyricCheck
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "lyricCheck/lyricCheck.py", line 12, in <module>
    from pygoogle import pygoogle
ImportError: No module named pygoogle

您可以将其放入您的 __init__.py 文件中,以从较低级别的模块中导入功能,并使它们在包级别可用:

from lyricCheck import help, check

另请注意,当您执行此操作时:

from decimal import *
from re import *

您将这些模块中的所有名称转储到模块的名称空间中。通常认为单独声明它们更好。