autocad

AutoCAD expects scripts to have the ‘.scr’ extension. The generated scripts can be run using the AutoCAD script command, or by dragging the script file onto the AutoCAD window. For more information see the AutoCAD help.

Wrapper for AutoCAD command script generation.

classes

Layer

class pygencad.autocad.Layer(name, co=None, lw=None, lc=None, desc='', st='', plt=True)[source]

AutoCAD layer wrapper.

In addition to color, line-weight, and line-type you can also set plot-style, non-plot, and description. The co, lw, and lc values default to “bylevel” which means that the attribute is not output in the script.

Parameters:
  • name (string OR Layer-like) – The name visible in Acad after the script is run. A tuple of layer properties, or a Layer object may be passed as the first argument (name) in which case the new layer is initialized with provided values.
  • co (int) – The color of the layer.
  • lw (number) – The line-weight of the layer.
  • lc (string) – The line-class (type) of the layer.
  • desc (string) – The layer description.
  • st (string) – The layer style.
  • plt (boolean) – Whether the layer is can be plotted.
__str__()[source]

Render this layer as a string.

The __str__ method is used to output the commands necessary to set the Layer objects properties active in AutoCAD.

CommandFile

class pygencad.autocad.CommandFile(filelike, setup=None, teardown=None)[source]

Wrapper for AutoCAD script generation.

In addition to implementing the methods defined in the base class this class provides a UCS context manager, 3d polyline method, and block method.

Parameters:
  • filelike (filelike) – An object with a write method.
  • setup (string OR callable) – Commands to include at the beginning of the script.
  • teardown (string OR callable) – Commands to include at the end of the script.
class Layer(name, co=None, lw=None, lc=None, desc='', st='', plt=True)

Local binding to the Acad Layer class

CommandFile.setup()[source]

Write default configuration info and run user provided setup func.

The default setup stores the active osnaps in a variable named “osmodeinit” and turns off osnaps (which normally interfere with scripts). The initial value of cmdecho is recorded as “cmdechoinit” and cmdecho is also disabled.

CommandFile.teardown()[source]

Write cleanup commands and run user provided teardown func.

The initial values recorded in the setup method are restored.

CommandFile.ucs(*args, **kwds)[source]

User Coordinate System context manager.

Write a set of UCS commands and rollback changes when done.

>>> from pygencad.autocad import CommandFile
>>> from StringIO import StringIO
>>> f = StringIO()
>>> script = CommandFile(f)
>>> with script.ucs('ucs w\nucs zaxis', ((0,0,0), (1,1,1)), 2):
...     # Draw a circle at origin pointing to the positive quadrant
...     script.circle((0,0,0), 5)
... 
'l'
>>> print f.getvalue()
ucs w
ucs zaxis
0,0,0
1,1,1
circle 0,0,0 5
ucs p
ucs p
Parameters:
  • command (string) – UCS commands to execute on entry.
  • points (iterable) – A list of points required by the last UCS command.
  • count (number) – How many UCS commands were issued.
CommandFile.set_ucs(command, points=None)[source]

Change the active UCS.

Parameters:
  • command (string) – UCS commands to execute on entry.
  • points (iterable) – A list of points required by the last UCS command.
CommandFile.pop_ucs(count=1)[source]

Rollback the indicated number of UCS changes.

Parameters:count (number) – How many UCS commands need to be rolled back.
CommandFile.point(p, reset=False, mode=None, write=True)[source]

Convert an iterable into a point of the correct format.

The mode argument is currently unsupported, but should support relative, polar, and relative polar coordinate input.

Parameters:
  • p – The point to be converted.
  • reset (boolean) – Optionally append the result of calling the reset method after writing the point.
  • mode (string) – Optional point output mode.
  • write (boolean) – Flag for writing output to script file.
Returns:

The point converted to a string.

CommandFile.points(ps, reset=False, mode=None)[source]

Calls CommandFile.point on each member of an iterable.

The mode Argument is currently unsupported, but should support relative, polar, and relative polar coordinate input.

Parameters:
  • ps – The points to be converted.
  • reset (boolean) – Optionally append the result of calling the reset method after writing all points.
  • mode (string) – Optional point output mode.
CommandFile.reset(write=True)[source]

Write the sequence required to exit the current command.

For Acad this method currently just outputs a newline.

Parameters:write (boolean) – Flag for writing output to script file.
Returns:The command that output by reset as a string.
CommandFile.line(ps, reset=False, mode=None)[source]

Write the Acad line command.

The mode argument is currently unsupported.

Parameters:
  • ps – The end points of the lines.
  • reset (boolean) – Optionally append the result of calling the reset method after writing all points.
  • mode (string) – Optional point output mode.
Returns:

Reference to created object.

CommandFile.polyline(ps, close=True, reset=False, mode=None)[source]

Write the Acad pline command.

Support could be added in the future for drawing arc segments or other special pline settings.

The mode argument is currently unsupported.

Parameters:
  • ps – The ordered points forming the line.
  • close (boolean) – Flag indicating whether the line should end where it started.
  • reset (boolean) – Optionally append the result of calling the reset method after writing all points.
  • mode (string) – Optional point output mode.
Returns:

Reference to created object.

CommandFile.poly3d(ps, close=True, reset=False, mode=None)[source]

Write the Acad 3dpolyline command.

In Acad polylines are strictly 2d in the xy plane of the active UCS. To draw non-planer polylines you must use the 3dpolyline. While 2d plines support all properties, arc segments, and even splines, 3dpolylines are always straight segments, and don’t support line-types (as of Acad2012).

The mode argument is currently unsupported.

Parameters:
  • ps – The ordered points forming the line.
  • close (boolean) – Flag indicating whether the line should end where it started.
  • reset (boolean) – Optionally append the result of calling the reset method after writing all points.
  • mode (string) – Optional point output mode.
Returns:

Reference to created object.

CommandFile.circle(center, radius)[source]

Write the Acad circle command.

Parameters:
  • center (iterable) – Point in a format passable to CommandFile.point.
  • radius (number) – Radius of the circle.
Returns:

Reference to created object.

CommandFile.text(text, p, height=1.0, ang=0, just='tl')[source]

Write a text placement command.

Text is placed as mtext. The text object width is set to 0 (infinite) meaning the text does not automatically wrap. Support for setting width, and setting the active text style, could be added in the future.

Parameters:
  • text (string) – The text to place.
  • p (iterable) – The insertion point in a format passable to CommandFile.point.
  • height (number) – How tall the text lines are.
  • ang (number) – The angle of the text in degrees.
  • just (string) – The justification of the text, a pair of [t, c, b][l, c, r].
Returns:

Reference to created object.

CommandFile.block(name, loc, ang=0, scale=1, attrs=None)[source]

Write a block placement command.

Currently only basic insertion is supported. Setting non-uniform scale factors, setting text values for attribute driven blocks, and setting dynamic block attributes could be added in the future.

The attrs argument is currently unsupported.

Parameters:
  • name (string) – The name of the block in Acad that is to be inserted.
  • loc (iterable) – The block insertion point.
  • ang (number) – The rotation angle of the inserted block in degrees.
  • scale (number) – The uniform scale factor of the inserted block.
  • attrs (mapping) – Attributes to be set for the block after insertion.
Returns:

Reference to created object.

CommandFile.store(name, *els)[source]

Store provided elements to be manipulated later.

For AutoCAD named selection sets are created (AutoCAD has a hard limit of 128 named selection sets). The selection set name will have a ‘!’ prepended, and can be passed to any command expecting a selection. If els contains ‘l’ than only one item (the last drawn) is added to the stored selection. Alternately, if els contains only selections set names, a new joined selection is created.

Parameters:
  • name (string) – The id used to store the selection.
  • *els ('l' for last, or selection set names.) – The elements to store.
Raises:

ValueError if no elements are provided.

Returns:

The name of the selection set.

CommandFile.move(els, base=(0, 0), dest=(0, 0))[source]

Transform the provided elements from base to dest.

Parameters:
  • els (A valid AutoCAD selection string.) – The elements to move.
  • base (iterable) – The base point to transform from.
  • dest (iterable) – The dest point to transform to.
Returns:

Reference to modified objects.

CommandFile.copy(els, base=(0, 0), dest=(0, 0))[source]

Transform duplicates of the provided elements from base to dest.

Parameters:
  • els (A valid AutoCAD selection string.) – The elements to copy.
  • base (iterable) – The base point to transform from.
  • dest (iterable) – The dest point to transform to.
Returns:

Reference to modified objects.

CommandFile.rotate(els, base=(0, 0), ang=0)[source]

Rotate the provided elements from base by angle.

Parameters:
  • els (A valid AutoCAD selection string.) – The elements to rotate.
  • base (iterable) – The base point to transform from.
  • ang (number) – The angle to rotate in degrees (counter-clockwise).
Returns:

Reference to modified objects.

CommandFile.cmd(command, *args)[source]

Write an arbitrary script command.

If the command string contains format expressions, and additional arguments were passed, the command string will be formated using the additional arguments.

>>> from pygencad.commandfile import CommandFile
>>> from StringIO import StringIO
>>> f = StringIO()
>>> with CommandFile(f) as script:
...     script.cmd("command with data: {:0.5f}", 355/113.0)
... 
'l'
>>> print f.getvalue()
command with data: 3.14159
Parameters:
  • command (string) – The command to be written to the script.
  • *args – Values to be formated by the command string.
Returns:

Some reference to any object created.

CommandFile.layer(*args, **kwds)[source]

Script layer context manager.

Activates the provided layer settings, and resets layer state on exit.

>>> from pygencad.commandfile import CommandFile
>>> from StringIO import StringIO
>>> f = StringIO()
>>> with CommandFile(f) as script:
...     with script.layer('layer'):
...         script.cmd("test")
... 
'l'
>>> print f.getvalue() 
Layer:
    lv=layer
    co=None
    lw=None
    lc=None
test
Parameters:
  • *args – Valid Layer arguments.
  • **kwargs – Valid Layer arguments.
CommandFile.pop_layer()[source]

Restores active layer prior to last set_layer call.

CommandFile.scale(els, base=(0, 0), scale=1)[source]

Scale the provided elements from base by scale.

Remember that scaling an axis by -1 is equivalent to mirroring.

Parameters:
  • els (A valid AutoCAD selection string.) – The elements to scale.
  • base (iterable) – The base point to transform from.
  • scale (number) – The scale factor to apply.
Returns:

Reference to modified objects.

CommandFile.set_layer(layer, *args, **kwargs)[source]

Activates the provided layer object or description.

Parameters:
  • layer – A layer object, or a valid Layer name argument.
  • *args – Valid Layer arguments.
  • **kwargs – Valid Layer arguments.
CommandFile.erase(els)[source]

Remove the indicated elements.

Parameters:els (A valid AutoCAD selection string.) – The elements to remove.