簡體   English   中英

打開受 docx 保護的文件的最快命令

[英]Fastest command to open a docx protected file

實際上,為了在不知道密碼的情況下快速打開受密碼文件保護的相同 .docx,我正在使用這些代碼行:

import comtypes.client
word = comtypes.client.CreateObject('Word.Application')
word.Documents.Open(wordPathFile, False, True, None, 'the_pwd')

但我注意到這種方法非常慢,而且它使用了很多處理器功能,特別是如果我需要大量時間重復這個任務,而且速度非常快。

那么有沒有更好的方法來完成這項任務? 這意味着首先(也是最重要的)必須更快且處理器消耗更少的方式?
提醒:任務是在不知道密碼的情況下嘗試非常快速地打開同一個文件 .docx 密碼保護文件。

如果我理解,您想在一個程序中多次打開同一個 DOCX 文件。 創建Word.Application的調用可能很昂貴。 相反,您可以打開 Word 一次,然后多次使用它。 既然你想保存狀態(應用程序對象),一個小類可能是最方便的。

import comtypes.client
import threading

class DocxFile:

    """Allows for opening a single DOCX file many times from a single
    Word.Application.
    """

    def __init__(self, filename, pwd):
        """Create a document opener for filename"""
        self.word_app = None
        self.lock = threading.Lock()
        self.filename = filename
        self.pwd = pwd
        
    def open_doc(self):
        """Open a new instance of the document. Caller is responsible for
        closing."""
        if not self.word_app:
            with self.lock:
                if not self.word_app:
                    self.word_app = comtypes.client.CreateObject('Word.Application')
        return word.Documents.Open(self.filename, False, True, None, self.pwd)

def main():
    doc_getter = DocxFile("my_doc.docx", "secret-dont-tell")
    for i in range(1_000_000):
        doc = doc_getter.open_doc()
        etc...

這是我發現的另一種方式,似乎要快一些:

import msoffcrypto

enc_file = msoffcrypto.OfficeFile(open(wordPathFile, "rb"))  # try start msoffcrypto-tool as OfficeFile with file-name and read-access only
enc_file.load_key(password=pwd_test)  # if password required, take the generated
enc_file.decrypt(open("decrypted.docx", "wb"))  # if password correct, open new file with write-access and copy content in it

在所有情況下,如果有人知道執行此任務的更快方法(這意味着在不知道密碼的情況下非常快速地打開相同的文件 .docx 密碼保護文件),即使此答案被標記為已接受,我也會非常很高興閱讀它並將他的答案標記為已接受。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM