【发布时间】:2021-05-20 17:53:21
【问题描述】:
长话短说:我正在建立一个数据库,其中包含我们公司曾经做过的所有报价。照顾特定的文件扩展名:*.prc 我想检索的信息之一是文件的所有者。 我正在使用以下代码(仅显示部分代码):
import os, time, win32security, subprocess
from threading import Thread
from time import time
def GET_THE_OWNER(FILENAME):
open (FILENAME, "r").close ()
sd = win32security.GetFileSecurity (FILENAME, win32security.OWNER_SECURITY_INFORMATION)
owner_sid = sd.GetSecurityDescriptorOwner ()
name, domain, type = win32security.LookupAccountSid (None, owner_sid)
return name
starttime = time()
path = "C:/Users/cbabycv/Documents/Python/0. Quotations/Example"
for root, dirs, files in os.walk(path):
for file in files:
if (file.endswith(".prc")):
#getting data from the file information
Filename = os.path.join(root,file)
try:
Owner = GET_THE_OWNER(Filename)
except:
Owner = "Could not get the owner."
print(Owner)
endtime = time()
print (Owner)
print(endtime-starttime, " sec")
这个过程很慢(尤其是当您必须阅读大约 100.000 个文件时)。我想知道是否有另一种方法可以使它更快? 请注意,我要求的是 Windows 操作系统而不是其他所有东西(在这种情况下我不能使用 os.stat() - 根本不适用于 Windows) 我尝试过这里描述的另一种方式:how to find the owner of a file or directory in python 通过 Paal Pedersen,但它甚至比使用 windows Api 还要慢
我正在使用 os.walk() 来查找服务器上的文件。我没有文件的确切位置,它们可能在任何文件夹中(所以我只是查看所有文件夹/子文件夹中的每个文件,看看它是否是 *.prc 文件)。一个建议的多处理 - 非常感谢 :) 我会尝试优化整个代码,但我的问题仍然有效 - 有没有更快/更好的方法在 Windows 操作系统中找到文件的所有者?
@theCreator 建议使用powershell。试过了。这是大约。慢了 14 倍...
import os, subprocess
from pathlib import Path
from time import time
starttime = time()
def GET_THE_OWNER(cmd):
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
completed = subprocess.run(["powershell.exe", "-Command", "Get-Acl ", cmd, " | Select-Object Owner"], capture_output=True, startupinfo=startupinfo)
return completed
path = Path('C:/Users/cbabycv/Documents/Python/0. Quotations/Example')
for root, dirs, files in os.walk(path):
for file in files:
if (file.endswith(".prc")):
#getting data from the file information
Filename = os.path.join(root,file)
Filename = "\"" + Filename +"\""
Owner = GET_THE_OWNER(Filename)
if Owner.returncode != 0:
print("An error occured: %s", Owner.stderr)
else:
print(Owner.stdout)
endtime = time()
print(endtime-starttime, " sec")
【问题讨论】:
-
这能回答你的问题吗? How do I parallelize a simple Python loop?