编译python代码为可执行程序

文章目录

  • 1. cx_freeze
    • 1.1. 安装python虚拟环境
    • 1.2. 进入python虚拟环境
    • 1.3. 安装cx_Freeze
    • 1.4. 安装bottle
    • 1.5. 编写代码
  • 2. cx_Freeze文档
    • 2.1 使用cx_Freeze
      • 2.1.1. cxfreeze命令方法
      • 2.1.2. 编写cxsetup.py, 然后用python执行
      • 2.1.3. 使用cxfreeze-quickstart生成 cxsetup.py模板
  • 3 . 参考:

1. cx_freeze

1.1. 安装python虚拟环境

pip3 install pipenv

1.2. 进入python虚拟环境

pipenv shell

1.3. 安装cx_Freeze

pip3 install cx_freeze -i https://pypi.douban.com/simple

1.4. 安装bottle

pip3 install bottole

1.5. 编写代码

# hello_world.py
from bottle import route, run

@route('/hello')
def hello():
    return "Hello World!"

run(host='localhost', port=8080, debug=True)

2. cx_Freeze文档

2.1 使用cx_Freeze

有三种不同的方法来使用cx_Freeze

2.1.1. cxfreeze命令方法

cxfreeze hello_world.py --target-dir out/      #把hello_world.py 打包成hello_world,放在out目录下 

2.1.2. 编写cxsetup.py, 然后用python执行

  1. 编写cxsetup.py编译脚本
#coding=utf-8
#cxsetup.py代码
from cx_Freeze import setup, Executable
setup(
    name="hello_world",
    version="1.0",
    description="To print hello world",
    author="xyl",
    executables=[Executable("hello_world.py")]
)

  1. 编译成二进制文件,可以脱离python环境执行
  • 注意:如果相关依赖安装在python虚拟环境中,需要先启动python虚拟环境
python cxsetup.py build

2.1.3. 使用cxfreeze-quickstart生成 cxsetup.py模板

  1. 生成的cxsetup.py 样式
from cx_Freeze import setup, Executable

# Dependencies are automatically detected, but it might need
# fine tuning.
buildOptions = dict(include_files = [], packages = [], excludes = [])

base = 'Console'

executables = [
    Executable('hello_world.py', base=base)
]

setup(name='hello-world',
      version = '1.0',
      description = 'print hello world',
      options = dict(build_exe = buildOptions),
      executables = executables)

  1. 添加配置文件
  • include_files = ["hello_world.config"]
  • include_files = [("hello_world.config", "hello_world.config")] # 目标位置只能使用相对路径, 因为只能在build构建目录之内,所以不能安装到系统的指定目录,要想安装到系统的指定目录,需要自行拷贝到指定目录

3 . 参考:

  • https://cloud.tencent.com/developer/article/1347382
  • https://www.thinbug.com/q/49350665
  • https://www.it-swarm.net/zh/python/%E4%BD%BF%E7%94%A8cxfreeze%E6%97%B6%E5%A6%82%E4%BD%95%E6%8D%86%E7%BB%91%E5%85%B6%E4%BB%96%E6%96%87%E4%BB%B6%EF%BC%9F/968187022/
  • https://cx-freeze.readthedocs.io/en/latest/distutils.html#build-exe

你可能感兴趣的:(编译python代码为可执行程序)