编译python代码为可执行程序

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 . 参考:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值