如何关闭使用os.startfile(),Python 3.6打开的文件 [英] How do I close a file opened using os.startfile(), Python 3.6
问题描述
我想关闭一些使用os.startfile()打开的.txt,.csv,.xlsx文件.
I want to close some files like .txt, .csv, .xlsx that I have opened using os.startfile().
我知道这个问题早先问过,但是我没有找到任何有用的脚本.
I know this question asked earlier but I did not find any useful script for this.
我使用Windows 10环境
I use windows 10 Environment
推荐答案
我相信问题的措辞有点误导-实际上,您想关闭使用os.startfile(file_name)
I believe the question wording is a bit misleading - in reality you want to close the app you opend with the os.startfile(file_name)
不幸的是,os.startfile
并没有为您提供返回进程的任何句柄.
help(os.startfile)
Unfortunately, os.startfile
does not give you any handle to the returned process.
help(os.startfile)
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.
幸运的是,您还有另一种通过外壳打开文件的方法:
Luckily, you have an alternative way of opening a file via a shell:
shell_process = subprocess.Popen([file_name],shell=True)
print(shell_process.pid)
返回的pid是父shell的pid,而不是进程本身的pid. 杀死它是不够的-它只会杀死一个shell,而不是子进程. 我们需要去找孩子:
Returned pid is the pid of the parent shell, not of your process itself. Killing it won't be sufficient - it will only kill a shell, not the child process. We need to get to the child:
parent = psutil.Process(shell_process.pid)
children = parent.children(recursive=True)
print(children)
child_pid = children[0].pid
print(child_pid)
这是您要关闭的PID. 现在我们可以终止该过程:
This is the pid you want to close. Now we can terminate the process:
os.kill(child_pid, signal.SIGTERM)
# or
subprocess.check_output("Taskkill /PID %d /F" % child_pid)
请注意,这在Windows上更加令人费解-没有os.killpg
有关更多信息:如何终止已启动的python子进程使用shell = True
Note that this is a bit more convoluted on windows - there is no os.killpg
More info on that: How to terminate a python subprocess launched with shell=True
此外,当尝试使用os.kill
os.kill(shell_process.pid, signal.SIGTERM)
subprocess.check_output("Taskkill /PID %d /F" % child_pid)
对我的任何进程都有效,而不会出现渗透错误
请参见 WindowsError:[错误5]访问被拒绝
subprocess.check_output("Taskkill /PID %d /F" % child_pid)
worked for any process for me without permision error
See WindowsError: [Error 5] Access is denied
这篇关于如何关闭使用os.startfile(),Python 3.6打开的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!