以管理员身份运行python脚本

时间:2011-10-27 20:30:03

标签: python windows-installer py2exe

我正在使用py2exe编写安装程序,需要在admin中运行以获得执行各种文件操作的权限。我已经修改了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 :(得分: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
)

答案 1 :(得分: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"]}
              }
    )