繁体   English   中英

如何确保python找到必要的数据文件?

[英]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:mainconsole_script

MANIFEST.in包含对sound.mp3的引用,以确保在运行setup.py时将其复制:

include my_application/sound.mp3
global-exclude *.pyc

run.py包含一小段代码,用于运行my_applicationmain()函数:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM