itsme
itsme

Reputation: 41

How to open all .dwg files in a directory in one instance of AutoCAD using Python

I started learning Python (and coding all together) this week and i'm stuck on a simple task i want to do.

The functionality i'm looking for is this:

  1. Print all .dwg files in a specified directory in the console.
  2. Open an instance of AutoCAD.
  3. For every .dwg file in said directory open a drawing in a new tab. (If i have an instance of AutoCAD open it automatically opens tabs when double clicking a .dwg file)

The code i wrote now:

import os
import subprocess

autocadPath = r'C:\Program Files\Autodesk\AutoCAD 2019\acad.exe'     

for file in os.listdir("D:\openFiles"):
    if file.endswith(".dwg"):
        print(os.path.join("D:\openFiles", file))

        subprocess.Popen("%s %s" % (autocadPath, os.path.join("D:\openFiles", file))) 

What happens when i run this:

  1. Two instances of autocad open.
  2. The last printed drawing opens in both instances
  3. It tries to open the first printed file but only in the second instance of AutoCAD and it doesn't find the file.

(I only have 2 .dwg files in de directory.)

I hope someone can help me out with this.

Upvotes: 4

Views: 2339

Answers (1)

Lee Mac
Lee Mac

Reputation: 16025

By far the easiest way to print a batch of drawings within AutoCAD is using an AutoCAD Script file (.scr), which can issue a sequence of commands and responses to command prompts to the AutoCAD command-line. I describe this process (albeit from an AutoLISP perspective) in my answer here.

Using an AutoCAD Script, you can open each drawing, issue the -PLOT command to either plot using a saved plot configuration (.pc3) or by entering the detailed configuration mode and responding to each prompt at the command-line.

I describe the syntax for an AutoCAD Script file in my tutorial here. For the -PLOT command, the Script might look something like the following:

-PLOT Y  "dwg to PDF" "ANSI full bleed B (11.00 x 17.00 Inches)" I L N E F C Y monochrome.ctb Y N N N "C:/YourFilename.pdf" N Y

You could use Python to write the Script, which can then be run from the AutoCAD command-line by supplying the SCRIPT command with the filename & filepath of the Script file created.

Upvotes: 1

Related Questions