pythonpipcefpython

Writing Python pip-able package: How to access files in the package?


I'm trying to develop a visualization package based on CEFpython technology, so the function has to access an html file. So the structure of the package is basically:

viz_tool

--> init.py

--> main.py

--> index.html

and in the main.py file, I defined a function:

def view():
    index_filepath = os.path.realpath("index.html")
    print(index_filepath)
    browser = cef.CreateBrowserSync(url='file://' + index_filepath,
                                window_title="viz tool")
    ....

The goal is, after installing this package, I can do:

from viz_tool import view
view()

but of course currently the "index_filepath" would be my current working directory, so it won't be able to find the "index.html" file.

How should I change the code so I could access the "index.html" file, which presumably would be in the directory where the package is installed?

Thank you very much! and please let me know if I need to clarify anything


Solution

  • Look at the documentation of pkg_resources.
    It has a method called resource_filename that you can use to get absolute path to any internal module.

    from pkg_resources import resource_filename
    from foo.bar import bazz # say bazz has template folder
    
    pth_to_template = resource_filename(bazz.__name__, "template")
    

    This will return the absolute path to <path to foo>/foo/bar/bazz/template.

    I would highly recommend not putting html file in root folder and also avoid using hardcoded paths in any form, including doing os.path.join recursively to traverse multiple levels. It makes moving files in future a mess.

    Edit: For accessing resources from the same module by relative path, you can do

    pth = resource_filename(__name__, "templates/something.html")
    

    Edit 2:. You will also have to add all the non-python files in package_data as here in order for setup.py to add them to the distribution package.