Python:终止进程并关闭它在 (windows) 中打开的 window

Python: kill process and close window it opened in (windows)

我正在工作中开发一个数据输入工具,它基本上需要一个报告 ID 号,打开一个 PDF 到该报告的那个页面,允许您输入信息然后保存它。

我对在 python 中实例化新进程完全陌生;这是我第一次真正尝试这样做。所以基本上,我有一个相关的功能:

def get_report(id):
    path = report_path(id)
    if not path:
        raise NameError
    page = get_page(path, id)
    proc = subprocess.Popen(["C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe", "/A", "page={}".format(page),
                             path])

为了在 Adob​​e Acrobat 中打开报表并能够在报表打开时输入信息,我决定必须使用 multiprocessing。因此,在程序的主循环中,它遍历数据并获取报告 ID,我有这个:

for row in rows:
    print 'Opening report for {}'.format(ID)
    arg = ID
    proc = Process(target=get_report, args=(arg,))
    proc.start()

    row[1] = raw_input('Enter the desired value: ')
    rows.updateRow(row)

    while proc.is_alive():
        pass

这样一来,就可以在程序不挂在subprocess.Popen()命令上的情况下输入数据了。但是,如果它只是继续下一条记录而不关闭弹出的 Acrobat window,那么它实际上不会打开下一个报告。因此 while proc.is_alive():,因为它提供了一个手动关闭 window 的机会。我 喜欢 在点击 'enter' 并输入值后立即终止进程,这样它将继续并只需更少的工作就可以打开下一份报告。我尝试了几种不同的方法,使用 os.kill() 通过 pid 终止进程的方法;我尝试杀死子进程,杀死进程本身,杀死它们,还尝试使用 subprocess.call() 而不是 Popen() 来查看它是否有所作为。

没有。

我在这里错过了什么?如何终止进程 关闭它在其中打开的 window?这可能吗?就像我说的,我对 python 中的流程只有大约 0 的经验。如果我做错了什么,请告诉我!

提前致谢。

到kill/terminate一个子进程,调用proc.kill()/proc.terminate()。它可能会留下孙进程 运行,参见 subprocess: deleting child processes in Windows

This way, one can enter data without the program hanging on the subprocess.Popen() command.

  1. Popen() 启动命令。它不会等待命令完成。有.wait()方法和call()
  2. 等便利函数
  3. 即使Popen(command).wait() returns即对应的外部进程已经退出;在一般情况下并不一定意味着文档已关闭(启动器应用程序已完成但主应用程序可能仍然存在)。

也就是说,第一步是删除不必要的 multiprocessing.Process 并在主进程中调用 Popen()

第二步是确保启动一个拥有打开文档的可执行文件,即如果它被杀死,相应的文档将不会保持打开状态:AcroRd32.exe 可能已经是这样的程序(测试它:查看 call([r'..\AcroRd32.exe', ..]) 是否等待文档关闭)或者它可能具有启用此类行为的命令行开关。参见 How do I launch a file in its default program, and then close it when the script finishes?


I tried killing the subprocess, killing the process itself, killing both of them, and also tried using subprocess.call() instead of Popen() to see if it made a difference.
It didn't.

如果 kill()Popen() 在你的情况下表现相同,那么要么你犯了一个错误(他们的表现不一样:你应该 create a minimal standalone code example with a dummy pdf that demonstrates the problem。描述使用文字:你期望发生什么(一步一步),而不是发生什么)或 AcroRd32.exe 只是我上面描述的启动器应用程序(它只是打开文档并立即退出而不等待文档关闭)。