win10: pyinstaller在python2和python3环境下的适应性配置

win10:pyinstaller在python2和python3环境下的适应性配置

前言

pyinstaller是一个非常优秀的python可执行程序打包工具,在windows下打包成.exe文件,在linux打包成linux下可执行文件。
最近,需要在python2和python3环境下分别使用pyinstaller进行打包,在网上搜集整理了很多资料,现在汇总如下。

相关配置

1.python安装不同版本

(1).在自定义位置,如c盘,新建python文件夹,比如 c:pythonpython2 和 c:pythonpython3

(2).前往官网下载好相应的python安装包,选择自定义安装(custom installation),勾选添加至系统路径,安装位置即(1)中对应文件夹.

  此时,查看系统环境变量中的Path:此电脑->鼠标右键->属性->高级系统设置->环境变量->系统变量->Path,会发现环境变量中多了几个路径:

  C:pythonpython2;

  C:pythonpython2Scripts;

  C:pythonpython3;

  C:pythonpython3Scripts

  通过查看这些文件夹下的内容,可以发现,比如python2文件夹下放的是python.exe,python2Scripts下放的是pip.exe

  系统正是通过这两个路径找到的可执行文件,所以我们可以通过改名的方式区分python2和python3

(3).将python3文件夹下的python.exe重命名为python3.exe;

(4).调出cmd终端,分别输入python 和 python3验证版本;pip2 -V 和 pip3 -V查看版本

2.下载并配置pyinstaller

(1).更换pip下载源:

  python2:

pip2 config --global set  global.index-url https://mirrors.aliyun.com/pypi/simple/

  python3

pip3 config --global set  global.index-url https://mirrors.aliyun.com/pypi/simple/

(2).更新pip

  python2

python -m pip install --upgrate pip

  python3

python3 -m pip install --upgrade pip

(3).安装pyinstaller

  python2

pip2 install pyinstaller

  python3

pip3 install pyinstaller

(4).pyinstaller.exe安装在了Scripts目录下,因此,只需要将python3Scripts目录下的pyinstaller.exe改名为Pyinstaller3.exe即可;

  如果python3Scripts目录下有pyinstaller-script.py,将其改名为pyinstaller3-script.py

(5).在cmd命令行分别输入pyinstaller3 -v 和 pyinstaller -v查看版本,查看成功就安装成功了

脚本

1.pyinstaller打包介绍

pyinstaller -F example.py -p c:/python/python2/Lib/site-packages/

  -p后跟的是依赖库的位置,也就是site-packages的位置,这样可以将依赖库也打到可执行文件里

  如果打出来的包执行时出现了终端黑窗口,可再加一个参数-w

2.简易python打包脚本

# -*- coding:utf-8 -*-
"""
Auto Pyinstaller
-----------------------
Auther:  Brian
version: 1.0
Time: 2021-02-20
----------------------
"""
import os
import sys

# 查看python版本
import platform
version = (platform.python_version()).split(".")[0]

# 查找python 附加包位置
from distutils.sysconfig import get_python_lib
lib_path = get_python_lib()

def usage():
    print("usage python mkexe.py <file>")
    sys.exit(0)
    

argc = len(sys.argv)
if argc < 2 :
    usage()
elif argc >2:
    usage()

filename = sys.argv[1]

if version == "2":
    # cmd = "pyinstaller -F {0} -p c:\Python27\Lib\site-packages\".format(filename)
    cmd = "pyinstaller -F {0} -p {1}".format(filename, lib_path)
    print(cmd)
elif version == "3":
    # cmd = "pyinstaller3 -F -w {0} -p C:\Python3\Lib\site-packages\".format(filename)
    cmd = "pyinstaller3 -F -w {0} -p {1}".format(filename, lib_path)
    print(cmd)
else:
    print("python version: {0}, please set environment  in this file".format(version))
    sys.exit(0)
    

f = os.popen(cmd, "r")
d = f.read()
print(d)
f.close()
print("pyinstaller finished")

  执行 python mkexe.py example.py;生成的可执行文件在dist目录下

参考

1. 查看python版本
2. 查看site-packages路径
3. os.popen()

原文地址:https://www.cnblogs.com/brian-sun/p/14422705.html