以adminis身份运行python脚本

2024-05-05 13:45:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个使用py2exe的安装程序,它需要在admin中运行才能拥有执行各种文件操作的权限。我修改了py2exe附带的user_access_controls目录中的一些示例代码,以创建安装文件。当我在自己的计算机上运行生成的exe文件时,它的创建/运行工作正常。但是,当我试图在没有安装python的计算机上运行exe时,我得到一个错误消息:导入模块(在本例中是shutil和os)不存在。我的印象是py2exe会自动将所有的文件依赖项包装到exe中,但我想情况并非如此。py2exe确实生成了一个名为library的zip文件,其中包含所有python模块,但显然生成的exe不使用它们。基本上,我的问题是如何将导入包含在py2exe生成的exe中。也许需要对我的设置.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,
    )

Tags: 模块文件theto代码pyimportaccess
2条回答

我为你重写了你的设置脚本。这会有用的

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"]}
              }
    )

尝试在设置部分设置options={'py2exe': {'bundle_files': 1}},和{}。Python将生成一个没有依赖关系的.exe文件。示例:

from distutils.core import setup
import py2exe

setup(
    console=['watt.py'],
    options={'py2exe': {'bundle_files': 1}},
    zipfile = None
)

相关问题 更多 >