有些时候我们开发的python算法需要再不同的windows环境下运行,为了不受到不同的Python版本以及第三方库版本匹配的影响,我们可以采用将Python代码打包为EXE文件,这样就可轻松的在各个windows环境下进行流畅运行了,实现这一目的可以采用如下步骤进行:
1.在Python中引入argparse,通过该模块来实现打包成EXE后的参数输入与输出功能
import argparse
2.在你的代码中加入如下内容实现参数的传入
if __name__=="__main__":
# Parse command-line arguments
parser = argparse.ArgumentParser(description="KNN Model")
parser.add_argument("--file", type=str, required=True, help="File path")
parser.add_argument("--history_time_period", type=int, required=True, help="history_time_period")
parser.add_argument("--future_time_period", type=int, required=True, help="future_time_period")
parser.add_argument("--neighbors", type=int, required=True, help="neighbors")
args = parser.parse_args()
# Call lstm function with command-line arguments
knn(args.file,args.history_time_period,args.future_time_period,args.neighbors)
3.在该python运行的虚拟环境中安装pyinstaller
pip install pyinstaller
4.在该python代码运行的虚拟环境中运行
pyinstaller --onefile your_script_name.py
注意这里请切换到你计划放该EXE文件的文件夹下面,这样生成的your_script_name.exe文件就会位于当前这个文件夹的位置,比如你计划将生成的exe文件放在d盘的这个OUT文件夹下面那么你就应该切换到这个目录D:\OUT\下运行该命令,如下所示
(venv)D:\OUT>pyinstaller --onefile your_script_name.py
Tips:如何需要在打包后运行EXE的时候不想显示命令行黑框框,则使用下面的,命令来进行打包即可
pyinstaller --onefile --noconsole your_script.py
5.生成后的exe文件就会在这个文件里面:
D:\OUT\dist\your_script_name.exe
6.这样我们就可以在配置了不同环境的windows平台运行这个python程序实现的功能了,通过使用help命令你就可以看到如给这个EXE程序输入参数了,如下所示
D:\OUT\dist>your_script_name.exe --help
usage: pre_sales.exe [-h] --file FILE --history_time_period HISTORY_TIME_PERIOD --future_time_period
FUTURE_TIME_PERIOD --neighbors NEIGHBORS
KNN Model
optional arguments:
-h, --help show this help message and exit
--file FILE File path
--history_time_period HISTORY_TIME_PERIOD
history_time_period
--future_time_period FUTURE_TIME_PERIOD
future_time_period
--neighbors NEIGHBORS
neighbors
7.对于该EXE程序我们依据help里面的提示,进行参数的输入,运行程
D:\OUT\dist>your_script_name.exe --file "mk.csv" --history_time_period 100 --future_time_period 30 --neighbors 5
8.到此我们就完成了Python打包为exe程序的全部操作,同时还实现了对该exe的调用运行。
本文介绍了如何将Python代码打包为可执行文件EXE,以解决不同Windows环境下Python版本和库兼容问题。方法包括引入argparse处理参数,使用PyInstaller工具打包,并提供示例命令行参数调用。
1143

被折叠的 条评论
为什么被折叠?



