pyinstaller可以轻易地将python代码打包成可执行文件。
1、安装pyinstaller
-Bash 代码
1
sudo pip install pyinstaller
安装好后,可以用如下命令查看pyinstaller版本
-Bash 代码
1
pyinstaller --version
2、写python代码test.py,如
-Python 代码
1
import numpy as np
2
3
if __name__ == "__main__":
4
a = np.array([1,2,3])
5
b = np.array([4,5,6])
6
print a+b
3、用pyinstaller将代码打包
在代码目录下,输入
-Bash 代码
1
pyinstaller test.py
会在当前目录下生成两个文件夹build和dist,以及一个文件test.spec
其中dist中包含可执行文件test,直接运行即可
4、写一个用到了tensorflow的python代码,保存为test.py
-Python 代码
01
import numpy as np
02
import tensorflow as tf
03
04
if __name__ == "__main__":
05
a = np.array([1,2,3,4])
06
b = np.array([5,6,7,8])
07
print a+b
08
09
node1 = tf.constant(3.0, dtype=tf.float32)
10
node2 = tf.constant(4.0) # also tf.float32 implicitly
11
print(node1, node2)
12
13
sess = tf.Session()
14
print(sess.run([node1, node2]))
再按照步骤3打包成可执行文件,但运行时会报如下的错误
xception: Versioning for this project requires either an sdist tarball, or access to an upstream git repository. It's also possible that there is a mismatch between the package name in setup.cfg and the argument given to pbr.version.VersionInfo. Project name mock was given, but was not able to be found.
[1799] Failed to execute script test
这个错误,如何解决呢?
搜索得到了两种解决方案(参考https://github.com/pyinstaller/pyinstaller/issues/2883):
1、在python程序中,添加如下的语句:
-Html 代码
查看代码
1
import os
2
3
os.environ["PBR_VERSION"]='3.1.1' #版本号可以用 pbr -v查看本机版本号
但这个方法在linux好像不好使,在MAC OS上似乎有用
2、在/etc/environment中添加
-Python 代码
1
PBR_VERSION=3.1.1
再关闭当前vim,重启vim后有效,再运行就ok啦