如何将已经 运行 的进程(即 Excel)分配给 Python 对象(PyWin32)以关闭它

How do I assign an already running process (i.e Excel) to a Python Object (PyWin32) to close it

所以我想做的是:

  1. 打开一个 Excel 工作簿并在单元格中输入一些值
  2. 使用 Pandas 读取 Excel 文件,将其转换为 DataFrame
  3. 对DataFrame进行一些操作
  4. 关闭工作簿(我想自动执行此步骤,当 Excel 文件仍处于打开状态时 Pandas 无法写入输出)
  5. 在同一个工作簿的另一个工作表中输出结果
  6. 重新打开 Excel 工作簿以检查结果

具体来说,第 4 步是我遇到一些问题的地方,我必须关闭 Excel 否则我会收到错误消息(PermissionError:[Errno 13])。我知道如何使用 PyWin32 打开 Excel 应用程序并执行任何操作,但是有没有办法将已经打开的 Excel 工作簿(之前从文件资源管理器打开)分配给 PyWin32 对象?

您可以使用 psutil 库。

您必须在调用树中搜索 运行 进程并将其杀死。

import os
import signal
import psutil

def kill_proc_tree(pid, sig=signal.SIGTERM, include_parent=True,
                   timeout=None, on_terminate=None):
    """Kill a process tree (including grandchildren) with signal
    "sig" and return a (gone, still_alive) tuple.
    "on_terminate", if specified, is a callabck function which is
    called as soon as a child terminates.
    """
    assert pid != os.getpid(), "won't kill myself"
    parent = psutil.Process(pid)
    children = parent.children(recursive=True)
    if include_parent:
        children.append(parent)
    for p in children:
        p.send_signal(sig)
    gone, alive = psutil.wait_procs(children, timeout=timeout,
                                    callback=on_terminate)
    return (gone, alive)

参见documentation

抱歉,我想我找到了我想要的解决方案,但是,我想我可能首先在这里描述了我的问题。基本上,我只是想要一个代码来关闭一个已经打开的 Excel 应用程序(也许应该说这个而不是工作簿)并将一些结果写入其中然后重新打开它。

import os, sys
import tempfile
import win32com.client

from pathlib import Path
filename = Path.cwd() / "ExcelFile.xlsx"

# Obtains the opened Excel instance
wb1 = win32com.client.GetObject(str(filename))

# Closes Excel
wb1.Application.Quit()

# Do whatever here like writing output in that Excel Workbook

# Reopen that Excel file
os.startfile(filename)

发现 this 很有用。再次对误导性描述表示抱歉。