given this code would it close other words i have opened? def convertdoc2pdf(filepaths:…
- User
given this code would it close other words i have opened?
def convert_doc2pdf(file_paths: list[str], output_path: str = None) -> list[str]: try: pythoncom.CoInitialize()
WORD2PDF = 17 word = win32com.client.Dispatch("Word.Application") word.Visible = False word.DisplayAlerts = 0 converted_files = [] file_paths = [ p.resolve() for p in map(Path, file_paths) if not p.name.startswith("~") and p.suffix.lower() in (".doc", ".docx") ] if output_path: output_path = Path(output_path).resolve() else: output_path = file_paths[0].parent output_path.mkdir(parents=True, exist_ok=True) for doc_filepath in tqdm(sorted(file_paths), "Converting Word to PDF"): pdf_filepath = output_path / (doc_filepath.stem + ".pdf") try: doc = word.Documents.Open(str(doc_filepath), ReadOnly=1) doc.SaveAs(str(pdf_filepath), FileFormat=WORD2PDF) converted_files.append(str(pdf_filepath)) except Exception as e: raise ValueError(f"Failed to convert {doc_filepath}: {e}") finally: doc.Close(False) except Exception as e: raise ValueError(f"Failed to convert {doc_filepath}: {e}") finally: word.Quit() pythoncom.CoUninitialize() return converted_files Assistant
The current code could potentially close other Word documents you have open if they are part of the same Word application instance. Here's why and how to fix it:
Key Issue:
The script creates a Word instance with
word = win32com.client.Dispatch("Word.Application"). By default, this might connect to an existing Word instance if one is already running. Whenword.Quit()is called at the end, it would close all documents in that shared instance, including any you opened manually.
Fixed Code (Prevents Closing Other Documents):
def convert_doc2pdf(file_paths: list[str], output_path: str = None) -> list[str]: try: pythoncom.CoInitialize() WORD2PDF = 17 # Force new Word instance (don't attach to existing) word = win32com.client.DispatchEx("Word.Application") # <-- CRITICAL FIX word.Visible = False word.DisplayAlerts = 0 converted_files = [] file_paths = [ p.resolve() for p in map(Path, file_paths) if not p.name.startswith("~") and p.suffix.lower() in (".doc", ".docx") ] if output_path: output_path = Path(output_path).resolve() else: output_path = file_paths[0].parent if file_paths else Path(".") output_path.mkdir(parents=True, exist_ok=True) for doc_filepath in tqdm(sorted(file_paths), "Converting Word to PDF"): pdf_filepath = output_path / (Path(doc_filepath).stem + ".pdf") try: # Open document in the isolated Word instance doc = word.Documents.Open(str(doc_filepath), ReadOnly=1) doc.SaveAs(str(pdf_filepath), FileFormat=WORD2PDF) converted_files.append(str(pdf_filepath)) except Exception as e: raise ValueError(f"Failed to convert {doc_filepath}: {e}") finally: if 'doc' in locals(): # Ensure doc exists before closing doc.Close(False) except Exception as e: raise ValueError(f"Conversion failed: {e}") finally: if 'word' in locals(): # Ensure word exists before quitting word.Quit() pythoncom.CoUninitialize() return converted_files
Critical Changes:
-
Use
DispatchExInstead ofDispatch:word = win32com.client.DispatchEx("Word.Application")DispatchExforces a new isolated Word instance, preventing interaction with any existing Word windows you have open.
-
Safer Cleanup:
- Added checks (
if 'word' in locals()) to prevent errors if initialization fails. - Explicitly check if
docexists before closing.
- Added checks (
-
Output Path Fix:
- Added fallback (
if file_paths else Path(".")) iffile_pathsis empty.
- Added fallback (
Why This Works:
- The script now runs in its own dedicated Word instance.
- When
word.Quit()is called, only the script's isolated instance is closed. - Your manually opened Word documents remain untouched.
If you still encounter issues, ensure:
- No documents are already open in the script's Word instance.
- You have write permissions for the output directory.
- The Word document isn't corrupted/corrupted.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.