如何用Python在单个AutoCAD实例中打开目录下所有.dwg文件
Hey there! Let's break down what's going wrong with your code and fix it step by step—you're super close, just a couple of small issues tripping you up.
What's Causing the Problems?
Path Escaping Mistakes
You're using regular strings for your paths like"D:\openFiles"instead of raw strings. Python interprets backslashes as escape characters, so your path might not be pointing where you think it is. That's exactly why the first file shows a "not found" error—your code is looking in a mangled version of the directory.AutoCAD Instance & Subprocess Issues
Callingacad.exedirectly in each loop iteration causes two problems:- AutoCAD takes a second to launch, so when your loop runs the second time, the first instance isn't fully ready yet. Windows thinks there's no running AutoCAD, so it spins up a second one.
- String concatenation for the command (
"%s %s" % (...)) is risky, especially with paths that have spaces (like your AutoCAD installation path). This can lead to command parsing errors that cause unexpected behavior, like the last file opening in both instances.
Fixed Code
Here's the revised version that fixes all these issues:
import os import subprocess # Use raw strings for all paths to avoid escape character chaos target_directory = r"D:\openFiles" for filename in os.listdir(target_directory): # Make sure we're only working with files (not folders) that end with .dwg if filename.endswith(".dwg") and os.path.isfile(os.path.join(target_directory, filename)): full_file_path = os.path.join(target_directory, filename) print(full_file_path) # Option 1: Let Windows handle opening the file (best for AutoCAD tab behavior) # This uses your system's default file association, which will auto-open in an existing AutoCAD tab subprocess.Popen([full_file_path], shell=True) # Option 2: If you need to force using your specific AutoCAD version # autocad_exe = r'C:\Program Files\Autodesk\AutoCAD 2019\acad.exe' # subprocess.Popen([autocad_exe, full_file_path])
Key Fixes Explained
- Raw Strings: Adding the
rprefix to paths (liker"D:\openFiles") tells Python to treat backslashes as regular characters, so your path stays exactly as you typed it. - List-Based Subprocess Call: Using a list (
[full_file_path]) instead of string concatenation avoids issues with spaces in paths and ensures the command is parsed correctly. - System File Association: Option 1 is the best bet because Windows will automatically detect an existing AutoCAD instance and open the file in a new tab—no extra work needed. If you have multiple AutoCAD versions installed and need to pick a specific one, use Option 2 instead.
Extra Tip
If you still run into multi-instance issues with Option 2, you can add a short delay between loop iterations to give AutoCAD time to launch fully:
import time # ... inside the loop, after Popen ... time.sleep(3)
This gives AutoCAD a few seconds to start up before the next file is processed.
内容的提问来源于stack exchange,提问作者itsme

