首页 > 解决方案 > 在 Python 中,如何关闭使用 os.startfile() 打开的文件?

问题描述

我使用 os.startfile('test-conversion.pdf') 打开 PDF 文件,但我想关闭文件打开它的应用程序。os.startfile() 启动关联的应用程序,但可能会使用 Windows 注册表来执行此操作。

如何以编程方式找出哪个应用程序打开了它,获取它的进程句柄,然后关闭应用程序和文件?

import os
import subprocess

# specify the file name
file1 = 'test-conversion.pdf'

# open the file using the .startfile() method
os.startfile('test-conversion.pdf')

# open the file using the subprocess.Popen() method
subprocess.Popen([file1],shell=True)

# subprocess.Pclose([file1],shell=True)

我尝试了最后一行,但它会引发错误并且不会关闭文件或进程。

标签: file

解决方案


推荐阅读