From what I can tell, you need to do three things to be able to utilize static file resources within a PEX deployment package:
- Make sure you initially build the PEX package with the
--not-zip-safe
option,
- Forcibly install the
setuptools
pip package when initially building your PEX package, and
- Utilize the pkg_resources module from setuptools to determine the right path to access your resources.
So in order to build your PEX package, you'll need a requirements.txt file that includes at least this line:
setuptools==49.2.0 # or whatever version, really, as long as some version is present
Then build the PEX file with something like this:
# first build the pex file with whatever pip requirements are needed
pex -r requirements.txt -e 'main:main' -o mypexfile.zip --not-zip-safe
# then add your files to it
zip mypexfile.zip Util/util1.py main.py WebService.xml
# finally, rename the extension (not strictly necessary)
mv mypexfile.zip mypexfile.pex
Finally, inside your main.py
file, you'll need code like this to access the resource file:
import os
import pkg_resources
def main():
path = pkg_resources.resource_filename(__name__, "WebService.xml")
if os.path.exists(path):
print("file exists")
That call to pkg_resources.resource_filename
basically is a way of looking up the ephemeral/relative path to where the file actually lives. If you print out the value of path
you'll see it will look funny and unpredictable. For example, in my case it ended up resolving to this value:
/root/.pex/code/da39a3ee5e6b4b0d3255bfef95601890afd80709/WebService.xml
But whatever that value actually is, the point is that the result of that call to pkg_resources.resource_filename
will give you the correct path, which should allow you to freely access your resource file.