Scripting PartDesign Workbench

From FreeCAD Documentation

Introduction

Here we will explain to you how to control the PartDesign using a script. Be sure to browse the Scripting section and the FreeCAD Scripting Basics pages if you need more information about how Python scripting works in FreeCAD. If you are new to Python, it is a good idea to first read the Introduction to Python.


"""Script to replicate Part Design Tutorial Example.

https://wiki.freecadweb.org/Basic_Part_Design_Tutorial

This code was written for this wiki page:

https://wiki.freecad.org/Scripting_PartDesign_Workbench

Name: 20230302_pdtut_ew.py

Author: Carlo Dormeletti - edwilliams16
Copyright: 2023
Licence: CC BY-NC-ND 4.0

"""
import os

import FreeCAD  # noqa
import FreeCADGui  # noqa
import Sketcher
import Part

from FreeCAD import Placement, Rotation  # noqa

V3d = FreeCAD.Vector

def activate_doc(doc_name):
    """Activate a specific document."""
    FreeCAD.setActiveDocument(doc_name)
    FreeCAD.ActiveDocument = FreeCAD.getDocument(doc_name)
    FreeCADGui.ActiveDocument = FreeCADGui.getDocument(doc_name)
    print(f"Document: {doc_name} activated")


def clear_doc(doc_name):
    """Clear the document deleting all the objects.

    Parameters:
    name       type        description
    doc_name   string      document name
    """
    doc = FreeCAD.getDocument(doc_name)
    try:
        while len(doc.Objects) > 0: 
            doc.removeObject(doc.Objects[0].Name)
    except Exception as e:
        print(f'Exception:  {e}')


def setview(doc):
    """Rearrange View."""
    try:
        doc_v = FreeCAD.Gui.activeView()
        FreeCAD.Gui.SendMsgToActiveView("ViewFit")
        doc_v.viewAxometric()
    except Exception:
        pass


def check_exist(doc_name):
    """Check the existence of a FC document named doc_name.

    If it not exist create one.
    """
    try:
        doc = FreeCAD.getDocument(doc_name)
    except NameError:
        doc = FreeCAD.newDocument(doc_name)

    return doc


# CODE start here

# Some handy abbreviations

VEC0 = V3d(0, 0, 0)
ROT0 = Rotation(0, 0, 0)

See also