pythonphp-ziparchive

How to access a file in zipapp


I've got a simple Python zipapp built with the following command:

python -m pkg/ -c -o test -p '/usr/bin/python3' -m 'test:main' zipapp

I would like to access the binary file from the script

$ cat pkg/test.py 
def main():
    with open('test.bin', 'rb') as f:
        print(f.name)

Directory structure

$ tree pkg/
pkg/
├── test.bin
└── test.py

0 directories, 2 files

But it looks like the script is referring to a file from the current directory:

$ ./test 
Traceback (most recent call last):
  File "/usr/lib64/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib64/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "./test/__main__.py", line 3, in <module>
  File "./test/test.py", line 2, in main
FileNotFoundError: [Errno 2] No such file or directory: 'test.bin'

It's a quite large binary file so I would like to avoid creating a variable. Is there a way to access this file from the script itself?


Solution

  • OK, it looks like I can open the zip file within the script itself:

    import zipfile
    
    def main():
        with zipfile.ZipFile(os.path.dirname(__file__)) as z:
            print(z.namelist())
            with z.open('test.bin') as f:
                print(f.name)