我正在尝试为使用 pywin32 绑定(bind)来编辑一些 excel 电子表格的程序创建安装程序。我已经使用 py2exe 创建了一个可执行文件,当从桌面上的文件夹中运行可执行文件时一切正常。但是,我希望能够分发一个安装程序文件,将程序安装到 C:\Program Files\或任何系统上的等效文件夹中。我在这方面也取得了成功,但是,当使用 pywin32 绑定(bind)时,无论工作目录在哪里,它们都会创建临时文件。
这是一个很大的问题,因为较新版本的 Windows 已经做到了,所以只有管理员才有权限写入这些目录。因此,当从这些目录运行应用程序时,它会失败并显示错误:
WindowsError: [Error 5] Access is denied: 'C:\\Program Files (x86)\\DataPlotter\\.\\win32com\\gen_py\
\00020813-0000-0000-C000-000000000046x0x1x6'
将应用更改为以管理员权限运行是一个糟糕的解决方案,因为它会引入漏洞。
有谁知道这个问题的修复方法或如何更改 pywin32 绑定(bind)用作临时文件位置的位置。
请您参考如下方法:
如果您希望恢复以前的当前目录,即使在发生未处理的异常。要做到这一点,还需要在 yield 周围添加一个 try...finally 子句(见下文)。
另外,我认为最好是让它成为一个独立的函数而不是某个类的方法,并将要切换到的目录作为参数传递给它——这两者都使它更通用、更容易重用。我将其命名为 pushd() 因为 similarities它与 Windows 和 Unix shell 命令同名。
from contextlib import contextmanager
import os
import tempfile
@contextmanager
def pushd(dir=None):
""" Context manager which saves the current working directory before
changing either to the one passed or the default folder for temporary
files and then restores the former after the controlled suite of
statements have executed. This will happened even if an unhandled
exception occurs within the block. """
cwd = os.getcwd()
os.chdir(dir if dir is not None else tempfile.gettempdir())
try:
yield
finally:
os.chdir(cwd)
# sample usage
with pushd():
self.xl = win32com.client.gencache.EnsureDispatch("Excel.Application")
执行 yield cwd 而不是什么都不做也可能很有用,这将允许任何可选的 as 变量接收一个值,该值指示先前的当前工作目录以供可能引用在 block 内。
