[英]How can I make sure that python finds the necessary data files?
请考虑以下脚本:
$ tree my_application
my_application
├── my_application
│ ├── sound.mp3
│ ├── __init__.py
│ ├── my_application.py
│ ├── my_application.pyc
│ └── __pycache__
│ ├── __init__.cpython-34.pyc
│ └── my_application.cpython-34.pyc
├── my_application.egg-info
│ ├── dependency_links.txt
│ ├── entry_points.txt
│ ├── PKG-INFO
│ ├── requires.txt
│ ├── SOURCES.txt
│ └── top_level.txt
├── run.py
├── MANIFEST.in
└── setup.py
my_application.py
是一个仅使用mplayer
播放sound.mp3
的脚本:
class Sound():
def __init__(self):
self.cmd = ["mplayer", "sound.mp3"]
def play(self):
subprocess.Popen(self.cmd)
setup.py
是您的经典setup.py文件,带有对my_application:main
的console_script
。
MANIFEST.in
包含对sound.mp3
的引用,以确保在运行setup.py
时将其复制:
include my_application/sound.mp3
global-exclude *.pyc
run.py
包含一小段代码,用于运行my_application
的main()
函数:
from my_application import main
if __name__ == "__main__":
main()
还有一个__init__.py
文件,因此main()
函数可以正确显示给“外部世界”:
from .my_application import main
__all__ = ["main"]
现在,当我在内部my_application
目录中运行main()
函数时,此脚本有效。 但是一旦从其他地方运行该功能(例如通过运行run.py
或使用控制台脚本), mplayer
抱怨它找不到sound.mp3
:
Cannot open file 'sound.mp3': No such file or directory
无论我位于哪个目录下,如何确保mplayer
找到sound.mp3
?
如果使用setuptools,则可以使用pkg_resources
检索文件的正确路径:
import pkg_resources
class Sound():
def __init__(self):
sound_path = pkg_resources.resource_filename(
'my_application', 'sound.mp3')
self.cmd = ['mplayer', sound_path]
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.