2024-04-25 10:27:43 发布
网友
我想关闭一些文件,如.txt,.csv,.xlsx,我已经打开使用操作系统启动文件(). 在
我知道这个问题之前问过,但我没有找到任何有用的脚本。在
我使用windows 10环境
基于thisSO post,无法关闭用os.startfile()打开的文件。类似的事情在thisQuora帖子中也有讨论。在
os.startfile()
然而,正如Quora文章中建议的那样,使用不同的工具来打开文件,例如subprocess或{},可以让您更好地控制文件的处理。在
subprocess
我假设您正在尝试读入数据,因此对于您关于不想手动关闭文件的评论,您可以始终使用with语句,例如
with
with open('foo') as f: foo = f.read()
稍微有点麻烦,因为您还需要做一个read(),但它可能更适合您的需要。在
read()
我相信这个问题的措辞有点误导人——实际上你想关闭你用os.startfile(file_name)打开的应用程序
os.startfile(file_name)
不幸的是,os.startfile没有为返回的进程提供任何句柄。 help(os.startfile)
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,而不是子进程。 我们需要找到孩子:
这是您要关闭的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.killpg
另外,当我试图用os.kill杀死shell进程时,我收到了PermissionError: [WinError 5] Access is denied
os.kill
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
subprocess.check_output("Taskkill /PID %d /F" % child_pid)
基于thisSO post,无法关闭用
os.startfile()
打开的文件。类似的事情在thisQuora帖子中也有讨论。在然而,正如Quora文章中建议的那样,使用不同的工具来打开文件,例如},可以让您更好地控制文件的处理。在
subprocess
或{我假设您正在尝试读入数据,因此对于您关于不想手动关闭文件的评论,您可以始终使用
with
语句,例如稍微有点麻烦,因为您还需要做一个
read()
,但它可能更适合您的需要。在我相信这个问题的措辞有点误导人——实际上你想关闭你用
os.startfile(file_name)
打开的应用程序不幸的是,
os.startfile
没有为返回的进程提供任何句柄。help(os.startfile)
幸运的是,您有另一种通过shell打开文件的方法:
返回的pid是父shell的pid,而不是进程本身的pid。 杀死它是不够的-它只会杀死一个shell,而不是子进程。 我们需要找到孩子:
^{pr2}$这是您要关闭的pid。 现在我们可以终止该过程:
注意,这在windows上有点复杂-没有
os.killpg
更多信息:How to terminate a python subprocess launched with shell=True另外,当我试图用
os.kill
杀死shell进程时,我收到了PermissionError: [WinError 5] Access is denied
subprocess.check_output("Taskkill /PID %d /F" % child_pid)
为我的任何进程工作,没有权限错误 见WindowsError: [Error 5] Access is denied相关问题 更多 >
编程相关推荐