How to access a file in zipapp

℡╲_俬逩灬. 提交于 2020-01-24 14:08:42

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/58836162/how-to-access-a-file-in-zipapp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!