gpt4 book ai didi

没有方法的Python模块包

转载 作者:行者123 更新时间:2023-12-01 04:53:05 24 4
gpt4 key购买 nike

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

我只是导入文件。歌词检查.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 *

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

关于没有方法的Python模块包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28036403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com