如何关闭使用os.startfile()打开的文件,Python 3.6

2024-04-25 10:27:43 发布

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

我想关闭一些文件,如.txt,.csv,.xlsx,我已经打开使用操作系统启动文件(). 在

我知道这个问题之前问过,但我没有找到任何有用的脚本。在

我使用windows 10环境


Tags: 文件csvtxt脚本环境windowsxlsx
2条回答

基于thisSO post,无法关闭用os.startfile()打开的文件。类似的事情在thisQuora帖子中也有讨论。在

然而,正如Quora文章中建议的那样,使用不同的工具来打开文件,例如subprocess或{},可以让您更好地控制文件的处理。在

我假设您正在尝试读入数据,因此对于您关于不想手动关闭文件的评论,您可以始终使用with语句,例如

with open('foo') as f:
    foo = f.read()

稍微有点麻烦,因为您还需要做一个read(),但它可能更适合您的需要。在

我相信这个问题的措辞有点误导人——实际上你想关闭你用os.startfile(file_name)打开的应用程序

不幸的是,os.startfile没有为返回的进程提供任何句柄。 help(os.startfile)

startfile returns as soon as the associated application is launched. There is no option to wait for the application to close, and no way to retrieve the application's exit status.

幸运的是,您有另一种通过shell打开文件的方法:

shell_process = subprocess.Popen([file_name],shell=True) 
print(shell_process.pid)

返回的pid是父shell的pid,而不是进程本身的pid。 杀死它是不够的-它只会杀死一个shell,而不是子进程。 我们需要找到孩子:

^{pr2}$

这是您要关闭的pid。 现在我们可以终止该过程:

os.kill(child_pid, signal.SIGTERM)
# or
subprocess.check_output("Taskkill /PID %d /F" % child_pid)

注意,这在windows上有点复杂-没有os.killpg 更多信息:How to terminate a python subprocess launched with shell=True

另外,当我试图用os.kill杀死shell进程时,我收到了PermissionError: [WinError 5] Access is denied

os.kill(shell_process.pid, signal.SIGTERM)

subprocess.check_output("Taskkill /PID %d /F" % child_pid)为我的任何进程工作,没有权限错误 见WindowsError: [Error 5] Access is denied

相关问题 更多 >