把Python项目源码打包成一个文件

1
2
3
├── program
│   ├── core.py
│   └── __main__.py

core.py

1
2
3
4
5
6
7
8
9
from http.server import SimpleHTTPRequestHandler
from socketserver import TCPServer


def run_server(port=8080):
print("listen at", port)
with TCPServer(("", port), SimpleHTTPRequestHandler) as httpd:
httpd.serve_forever()

__main__.py

1
2
3
4
5
from core import run_server

if __name__ == "__main__":
run_server()

__main__.py 的意义:把当前package当做script运行,__main__.py则是这个script的入口。

打包成一个文件

1
2
3
4
#!/usr/bin/env bash
cd program;zip -r ../app.zip .;cd ..
echo '#!/usr/bin/env python3' | cat - app.zip > app
chmod a+x app

项目地址python-one-file

转载请包括本文地址:https://allenwind.github.io/blog/11208/
更多文章请参考:https://allenwind.github.io/blog/archives/