打包python文件为exe文件(PyInstaller工具使用方法)
最后更新于:2022-04-01 23:02:49
最近做的新浪微博爬虫程序,打算打包成.exe软件以方便使用,网上找到一个很好的打包工具pyinstaller,这里记录一下打包的方法。
##一、下载pyinstaller
我使用的版本为PyInstaller-2.1,支持python版本2.3-2.7,[点击这里下载](http://download.csdn.net/detail/dianacody/8000503)。
##二、安装pyinstaller
下载完成后,解压即可。我的解压目录为D:\Python27\PyInstaller-2.1\
##三、使用pyinstaller打包.py成.exe应用程序
1.注意使用前要安装pywin32,[点击这里下载](http://download.csdn.net/detail/dianacody/7997941)。
2.将需要打包的.py放到PyInstaller-2.1目录下,如下图所示。

在命令行,cd进入可执行python命令的目录,执行命令:python pyinstaller.py [opts] yourprogram.py
主要选项包括:
-F, –onefile 打包成一个exe文件。
-D, –onedir 创建一个目录,包含exe文件,但会依赖很多文件(默认选项)。
-c, –console, –nowindowed 使用控制台,无界面(默认)
-w, –windowed, –noconsole 使用窗口,无控制台
更详细的使用方法可以参考下载包里的doc目录下的Manual.html文件。
具体操作:
python pyinstaller.py-F sina_crawler.py
**实际操作:(其实就是注意文件路径,我的pyinstaller安装目录D:\Python27\pyinstaller-2.1\)**
**cd到d:\Python27\目录下,然后命令:**
**python pyinstaller-2.1\pyinstaller.py -F pyinstaller-2.1\sina_crawler.py**
如果最后出现Appending archive to EXE,则生成成功。

**注意会生成(均在Python27目录下):**
**1. dist文件夹(包含生成好的sina_crawler.exe)**
**2.build文件夹(中间生成,没用,事后可以删掉)**
**3.sina_crawler.spec文件(中间生成,没用,事后可以删掉)**
## 四、生成的微博爬虫软件
双击生成的dist文件夹里的sina-crawler.exe文件,运行软件开始爬取微博。

顺便说句题外话,对于控制台程序运行,无论是.py文件还是生成的.exe文件,程序运行完闪退的情况:可以在程序加上raw_input()函数,表示运行结束等待回车输入再退出。
爬下来的页面:

';