帮助将.py转换为.exe,使用py2exe
我运行的脚本是
# p2e_simple_con.py
# very simple script to make an executable file with py2exe
# put this script and your code script into the same folder
# run p2e_simple_con.py
# it will create a subfolder 'dist' where your exe file is in
# has the same name as the script_file with extension exe
# (the other subfolder 'build' can be deleted)
# note: with console code put a wait line at the end
from distutils.core import setup
import py2exe
import sys
sys.argv.append("py2exe")
sys.argv.append("-q")
# this is your code script file, change it as needed
# use it in the working directory or give full path
script_file = 'DateTime_Test1.py'
# create a single .exe file and use compression
# (the .exe file is 30% larger with no compression)
setup(
options = {'py2exe': {'bundle_files': 1, 'compressed': 1,}},
zipfile = None,
# replace console with windows for a GUI program
console = [{'script': script_file}]
)
我试了这个,但出现了以下错误
C:\Python26\Lib\distutils\dist.py:266: UserWarning: Unknown distribution option: 'console'
warnings.warn(msg)
C:\Python26\Lib\distutils\dist.py:266: UserWarning: Unknown distribution option: 'zipfile'
warnings.warn(msg)
usage: py2exe.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: py2exe.py --help [cmd1 cmd2 ...]
or: py2exe.py --help-commands
or: py2exe.py cmd --help
error: invalid command 'py2exe'
4 个回答
0
这个问题可能是因为 py2exe
是针对 Python 3 的。
而针对 Python 2 的工具似乎是 py2exe2msi
。
我在使用 Python 2 时也遇到了类似的错误,因为我在尝试运行为 Python 3 写的代码。
0
这只是一个想法(不算真正的答案,但我不能评论)。
从错误信息来看,似乎有一个参数传给了 py2exe
,而这个参数是它不接受的。我猜这个参数可能是 -q
。所以你可以试着去掉这一行 sys.argv.append("-q")
,然后再运行脚本。
我自己没有用过 py2exe,所以不能真的测试一下。这只是个想法。
1
这些代码行:
sys.argv.append("py2exe")
sys.argv.append("-q")
看起来有点“奇怪”,可能是导致“无效命令”消息的原因。我很好奇这样写的理由是什么。
更新
通常的约定是把脚本命名为 setup.py
(不过在这个例子中,它似乎叫 p2e_simple_con.py
)。这个 setup
函数会解析命令行,通常你会用类似这样的命令来运行它:
python setup.py py2exe
这里的 py2exe
是一个 py2exe 包能理解的命令,然后它会生成 EXE 文件。所以只要你安装了 py2exe 包,这个命令就应该可以被接受。
代码行 sys.argv.append("py2exe")
是把这个命令加到命令行中,所以在你的情况下,你应该只需要输入:
python p2e_simple_con.py
就可以生成 exe 文件。不过,如果你没有安装 py2exe 包,那么基础的 distutils
就不会识别 py2exe
命令。但在这种情况下,我预计你会在 import py2exe
这一行遇到错误。所以,我不太确定发生了什么。
你用什么命令来运行这个设置程序的?