以管理员身份运行Python脚本
我正在用py2exe写一个安装程序,这个程序需要以管理员身份运行,以便有权限进行各种文件操作。我修改了一些来自py2exe自带的user_access_controls目录里的示例代码来创建安装文件。在我自己的电脑上创建和运行生成的exe文件都没问题。然而,当我尝试在一台没有安装Python的电脑上运行这个exe时,出现了一个错误,提示说导入的模块(在这个例子中是shutil和os)不存在。我原以为py2exe会自动把所有需要的文件依赖打包进exe里,但看来并不是这样。py2exe确实生成了一个叫做library的zip文件,里面包含了所有的Python模块,但显然这些模块并没有被生成的exe使用。基本上,我的问题是如何让py2exe生成的exe包含这些导入的模块。也许需要对我的setup.py文件进行一些修改,以下是这个文件的代码:
from distutils.core import setup
import py2exe
# The targets to build
# create a target that says nothing about UAC - On Python 2.6+, this
# should be identical to "asInvoker" below. However, for 2.5 and
# earlier it will force the app into compatibility mode (as no
# manifest will exist at all in the target.)
t1 = dict(script="findpath.py",
dest_base="findpath",
uac_info="requireAdministrator")
console = [t1]
# hack to make windows copies of them all too, but
# with '_w' on the tail of the executable.
windows = [{'script': "findpath.py",
'uac_info': "requireAdministrator",
},]
setup(
version = "0.5.0",
description = "py2exe user-access-control",
name = "py2exe samples",
# targets to build
windows = windows,
console = console,
)
2 个回答
0
我帮你把设置脚本重新写了一下。这样就可以用了。
from distutils.core import setup
import py2exe
# The targets to build
# create a target that says nothing about UAC - On Python 2.6+, this
# should be identical to "asInvoker" below. However, for 2.5 and
# earlier it will force the app into compatibility mode (as no
# manifest will exist at all in the target.)
t1 = dict(script="findpath.py",
dest_base="findpath",
uac_info="requireAdministrator")
console = [t1]
# hack to make windows copies of them all too, but
# with '_w' on the tail of the executable.
windows = [{'script': "findpath.py",
'uac_info': "requireAdministrator",
},]
setup(
version = "0.5.0",
description = "py2exe user-access-control",
name = "py2exe samples",
# targets to build
windows = windows,
console = console,
#the options is what you fail to include it will instruct py2exe to include these modules explicitly
options={"py2exe":
{"includes": ["sip","os","shutil"]}
}
)
2
试着在设置部分加上 options={'py2exe': {'bundle_files': 1}},
和 zipfile = None
。这样,Python 就会生成一个没有依赖项的单独 .exe 文件。举个例子:
from distutils.core import setup
import py2exe
setup(
console=['watt.py'],
options={'py2exe': {'bundle_files': 1}},
zipfile = None
)