首页 > 解决方案 > 是否可以使用 Python 检查是否已在 Windows 上打开文件夹?

问题描述

例如,假设我的桌面上有一个文件夹。当我打开文件夹时,程序是否可以在它发生时运行?有什么方法可以识别特定文件夹打开的动作吗?

标签: pythonwindows

解决方案


你可以使用handle.exe微软发布的,可以从微软官方网站下载:https ://docs.microsoft.com/zh-cn/sysinternals/downloads/handle

下载后,放入handle.exe同一个文件夹test.py,然后执行python test.py $your_folder得到结果,仅供参考。

测试.py

import os
import sys

candidate_folder = sys.argv[1]
print('Please wait for some seconds before the process done...')
rc = os.system("handle.exe -accepteula %s | findstr pid" %(candidate_folder))
if 0 == rc:
    print('The folder is opened by above process.')
else:
    print('No process open this folder now.')

1)test1:(不要打开文件夹C:\abc)

C:\Handle>python test.py C:\abc
Please wait for some seconds before the process done...
No process open this folder now.

2)test2:(打开文件夹C:\abc)

C:\Handle>python test.py C:\abc
Please wait for some seconds before the process done...
explorer.exe       pid: 15052  type: File          2B9C: C:\abc
explorer.exe       pid: 15052  type: File          2BC0: C:\abc
The folder is opened by above process.

推荐阅读