Python
BadBit runs Python scripts that draw, query and change the drawing through the
badbit package. The same package works in two ways:
- inside BadBit, in the BadBit Scripts editor (command
SCRIPTEDITOR, aliasSED): you write, run and see the output without installing anything; - from the Python on your machine (a terminal, VS Code, Jupyter), talking to the open BadBit.
In VS Code, the BadBit extension runs and debugs the .py inside the open BadBit and turns
on completion for the package (see the VS Code guide).
Every BadBit operation is a function: badbit.cad.layer.create(...),
badbit.cad.entity.query(...), badbit.suite.command.run(...). The full list, with
parameters, result and an example for each one, is in the
operations reference.
BadBit's Python
The first time you run a script, BadBit downloads its Python (a complete CPython 3.14, about 25 to 37 MB depending on the system) and keeps it for next time; the progress bar appears in the output panel and Cancel stops it. Without internet, the message says so: connect and run again. In companies without internet, IT can put the Python folder next to the program.
The script runs in a separate process: a stuck or failing script never freezes or crashes BadBit. Stop (or Esc) ends the script at once.
Your first script
-
Type
SEDand Enter. BadBit Scripts opens. -
Click New Python and write:
Pythonimport badbit badbit.cad.layer.create(name="Walls", color=1) badbit.cad.entity.create(entities=[ {"type": "polyline", "points": [[0, 0], [500, 0], [500, 400], [0, 400]], "closed": True, "layer": "Walls"}, {"type": "text", "position": [200, 200], "content": "Living room", "height": 20}, ]) print("done") -
Click Run. The rectangle and the text appear in the drawing and "done" appears in the Output panel.
Each call is one undo step (U takes back the last one). If a call fails, what it
did is undone and the script gets a badbit.BadbitError exception with a message
saying what to fix. A script error shows in the output with the line; click the line
to go to it in the editor.
Examples
Count the blocks in the drawing
from collections import Counter
import badbit
count = Counter(e["block"] for e in badbit.entities(types=["insert"]))
for name, n in count.most_common():
print(f"{name}: {n}")badbit.entities(...) goes through every object that matches the filters (types,
layers, window), page by page, whatever the size of the drawing.
Number the texts of a layer
import badbit
texts = [e for e in badbit.entities(types=["text"], layers=["Rooms"], detail=True)]
# Left to right, top to bottom.
texts.sort(key=lambda e: (-e["position"][1], e["position"][0]))
badbit.cad.entity.modify(items=[
{"id": e["id"], "set": {"content": f"{i:02d}"}} for i, e in enumerate(texts, 1)
])A single call changes them all: one undo step.
Export point coordinates to CSV
import csv
import badbit
with open("points.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["id", "x", "y", "layer"])
for e in badbit.entities(types=["point"], detail=True):
x, y = e["position"]
w.writerow([e["id"], x, y, e["layer"]])The file goes to the script's folder (or the current folder, from your own Python).
Run a command as if typed
badbit.command("CIRCLE", (50, 25), "10") # center and radius
badbit.command("LINE", "0,0", "100,0", "") # "" is EnterOptions use the AutoCAD English letters, in any language.
Views, layouts, plotting, files and inquiry
Inquiry returns the numbers with the unit; layouts, views and output are functions too (what writes files needs an absolute path and keeps a backup copy before writing over a file):
r = badbit.cad.draw.rectangle(corner1=[0, 0], corner2=[12, 8])
print(badbit.cad.inquiry.area(ids=r["ids"])["area"]) # 96.0
badbit.cad.layout.create(name="Plans")
badbit.cad.layout.mview(layout="Plans", corner1=[20, 20], corner2=[400, 280], scale=50)
badbit.cad.output.export(path="/Users/ana/Documents/BadBit/plans.pdf", layouts=["Plans"])Filters, other drawings, palettes and printing
The remaining windows are functions too:
circles = badbit.cad.select.filter(filter=[
{"property": "object", "value": "circle"},
{"property": "radius", "operator": "ge", "value": 5},
])["ids"]
diff = badbit.cad.file.compare(path="/Users/ana/Documents/BadBit/plan-rev1.dwg")
print(diff["equal"], len(diff["only_current"]), len(diff["only_other"]))
badbit.cad.content.import_(library=True, content_kind="blocks", names=["Door"],
insert_at=[100, 50])
badbit.cad.output.export(printer="default", copies=2) # prints: cannot be undoneThe Options (badbit.suite.options.get(), badbit.suite.options.set(theme="light")) do not
change AI (MCP), the trusted folders, the Account or updates.
Drawing and modify operations
The drawing and modify commands also exist as functions with named parameters, without prompts (angles in degrees; each call is one undo step):
rect = badbit.cad.draw.rectangle(corner1=[0, 0], corner2=[12, 8])
wall = rect["ids"][0]
badbit.cad.modify.offset(id=wall, distance=0.2, side=[6, 4]) # inside
badbit.cad.modify.rotate(ids=[wall], base=[0, 0], angle=30, copy=True)
badbit.cad.modify.array(ids=[wall], array_type="rectangular", rows=2, columns=3,
row_spacing=10, column_spacing=15, associative=False)
badbit.cad.draw.hatch(ids=[wall], pattern="ANSI31", pattern_scale=2)
badbit.cad.modify.pedit(ids=[wall], action="width", polyline_width=0.05)The answer says what was created, changed and deleted.
Text, dimensions, tables and constraints
Annotation (badbit.cad.annotate), formatting (badbit.cad.format) and parametric drawing
(badbit.cad.parametric) work the same way:
badbit.cad.annotate.text(content="FLOOR PLAN", position=[0, 9], height=0.5)
dim = badbit.cad.annotate.dim_linear(first_origin=[0, 0], second_origin=[12, 0],
dim_line_point=[6, -1.5])
print(dim["dim_texts"][0]) # the text, in the current style
outline = badbit.cad.draw.rectangle(corner1=[0, 0], corner2=[12, 8])["ids"][0]
badbit.cad.parametric.geometric(constraint="horizontal", parts=[{"id": outline}])Dynamic blocks and .scr scripts
The definition of a dynamic block changes without the block editor (each call is one undo
step), and a .scr runs like SCRIPT:
porta = "Door"
largura = badbit.cad.block.parameter_add(
name=porta, parameter_type="linear", base_location=[0, 0], end_location=[900, 0],
parameter_label="Width",
value_set={"increment": 100, "minimum": 600, "maximum": 1200})["node"]
itens = badbit.cad.block.definition(name=porta)["items"]
direita = [i["index"] for i in itens if i["bbox"][2] >= 850] # the right jamb
badbit.cad.block.action_add(
name=porta, parameter=largura, action_type="stretch",
stretch_frame=[[850, -50], [950, -50], [950, 2150], [850, 2150]],
selection_items=direita)
ins = badbit.cad.draw.insert(name=porta, position=[0, 0])["ids"][0]
badbit.cad.block.dynamic_set(id=ins, values={"Width": "1100"})
r = badbit.suite.script.run_commands(script_text="LINE 0,0 100,0 100,50 \nZOOM E\n")
print(r["script_status"], r["output"]["user_content"])A .scr that stops on an error does not undo what it did: r["script_line"] gives the line
and badbit.suite.script.resume() goes on. Attributes go to and come back from a spreadsheet
with badbit.cad.attributes.export(ids=..., path=...) and
badbit.cad.attributes.import_(path=...); drawings close with
badbit.suite.document.close(save=True) and badbit.suite.document.close_all(discard=True);
the model screen splits with badbit.cad.view.vports_set(tile_layout="four_equal").
Asking the person
Like getpoint and ssget in BadBit CAD's LISP, a script can ask for a point, a distance, a
text, an object or a selection. The question appears on the command line, with object
snaps; Esc cancels (the script gets badbit.CancelledError).
import badbit
p = badbit.getpoint("Insertion point:")
radius = badbit.getdist("Radius:", base=p)
badbit.cad.entity.create(entities=[{"type": "circle", "center": p[:2], "radius": radius}])
ids = badbit.ssget(types=["line"]) # "Select objects", Enter ends
print(len(ids), "lines")Also: badbit.getstring("Name:"), badbit.entsel("Pick a text:") and keywords, as in
initget: badbit.getpoint("Next or [Undo]:", keywords="Undo") returns "Undo"
when the person types U.
All at once: transaction and batch
To describe a whole project in one call (one undo step, and nothing applied if a step fails):
import badbit
with badbit.transaction() as t:
badbit.cad.layer.create(name="Axes", color=5)
room = badbit.cad.entity.create(entities=[
{"type": "line", "start": [0, 0], "end": [1000, 0], "layer": "Axes"},
])
badbit.cad.entity.modify(items=[{"id": room["ids"][0], "set": {"color": "red"}}])
print(t.results)Inside the block each call is only recorded; the result of a step (room) can be used
in the next ones. At the end of the block everything goes together. The same without
the block: badbit.batch([("cad.layer.create", {"name": "A"}), ...]).
Any operation by name
badbit.call("cad.layer.create", name="Walls")
for op in badbit.operations("layer"):
print(op["id"], "-", op["summary"])The console
In the Console panel of BadBit Scripts, choose Python and type one line at a
time (badbit is already imported). Load runs the tab in the console: the
functions it defines become available to try.
Third-party packages (pip)
In the BadBit Scripts console (Python), a line that starts with pip (or %pip,
as in IPython) runs pip in a package environment of your own, managed by
BadBit. It does not go to Python:
pip install numpy
pip list
pip show numpy
pip uninstall numpy- Subcommands:
install,uninstall(no prompt),list,show,freezeand--version. Others are refused with a message. - Where packages come from: PyPI, or the index you give (`--index-url
`, or `--no-index --find-links
` to install from a folder of `.whl` files, with no internet). Your computer's pip configuration applies. - The environment: created the first time you use pip (a few seconds, no
internet needed), in the BadBit data folder (
python/venv-3.14), apart from the Python BadBit downloaded. After that, scripts and the console run with it and import what you installed (badbitis still available). A console that was already open restarts to see the packages. - New BadBit versions: with the same Python (3.14), the environment is updated automatically and the packages are kept. When BadBit moves to another Python version, the environment is a new one: install your packages again.
- pip runs on its own, with its output in the console; Stop (or Esc) ends it.
Installing a package runs third-party code with your account's permissions. No BadBit operation runs pip; but a script, or the AI with AI (MCP) on, runs code with your user's permissions, and that code can install packages on its own.
From the Python on your machine
-
Open BadBit. The local channel opens by itself, for your user only: there is nothing to turn on.
-
In your Python (3.10 or newer), install the
badbitpackage from PyPI:Terminalpip install badbitThe badbit package is not on PyPI yet.
Use the package version of your BadBit (
pip install "badbit==2027.0.0b8"for BadBit 2027.0.0-beta.8). The package has no dependencies. -
Run the script as usual. The package finds the open BadBit by itself.
The AI (MCP) switch in Options is only for AI assistants: on or off, it changes
nothing for your scripts. With BadBit closed, the script gets
badbit.NotConnectedError with the explanation.
A newer package with an older BadBit works too: the package asks BadBit for the
operations it has and, if you call one that does not exist yet in the installed
version, you get badbit.OperationUnavailableError saying what to update (the
message is in the system's language; BADBIT_LANGUAGE=en, pt-BR or es picks one).
Batch without a window
To process drawings without opening the program (convert a folder of DXF to DWG, clean up and rename layers in many files, list the blocks), the package starts a BadBit without a window, talks to it and closes it at the end. There is nothing to turn on and nothing to accept: it is your script, as in BadBit Scripts.
from pathlib import Path
import badbit
projects = Path("~/Projects").expanduser()
with badbit.headless():
badbit.suite.document.open(path=projects / "plan.dxf")
badbit.cad.layer.create(name="Notes", color=3)
badbit.suite.document.save(path=projects / "plan.bbd")- It opens and saves files where you ask, with absolute paths; network and Windows device paths are refused. Before writing over a file, it keeps a backup copy next to it.
- The
folders,levelandaccept_all_risksarguments of earlier versions are accepted and ignored, with aDeprecationWarning: you can remove them from the script. - Inside the
with, thebadbit.*functions talk to the BadBit without a window; at the end it is closed and what was not saved is lost. It is also closed on an exception, when Python ends, or if Python is closed by force. timeout(default 900 seconds) limits each request: the one that passes it is cancelled, what it did is undone and the script getsbadbit.RequestTimeoutError.start_timeoutandclose_timeoutlimit starting and closing.- The program is the installed BadBit CAD; to use another one, give
executable=...or theBADBIT_EXECUTABLEenvironment variable. The batch without a window needs BadBit CAD 2027.0.0-beta.8 or newer. .bbd, DXF and DWG: it opens and saves the three, as the program does (DXF and DWG in the version of the file opened, or 2018).
A whole folder
badbit.each_drawing(folder) opens each drawing of the folder in turn (.dxf,
.dwg and .bbd, in name order) and closes it before the next one, without piling
tabs up in memory:
with badbit.headless():
for path in badbit.each_drawing(projects / "plans", skip_errors=True):
badbit.cad.file.purge()
badbit.suite.document.save(path=path.with_suffix(".dwg"))extensions=[".dxf"]picks the extensions;recursive=Truegoes into the subfolders;skip_errors=Trueskips, with a line on the terminal, a drawing that does not open.- What was not saved inside the loop is lost when going to the next one.
- Backup copies (
*.ia-backup-*) are left out. - To close the drawing in view in your own loop:
badbit.suite.document.close(discard=True)(only without a window; in the open program, closing a tab is the person's decision).
From the terminal
The same script, unchanged, runs as a batch from the command line:
python -m badbit run count.py --headless -- ~/Projects/plans--headlessstarts the BadBit without a window for the script (without it, the script talks to the open BadBit);--executable <file>and--timeout <seconds>. The Portuguese names work too:--sem-janela,--programa,--tempo-limite.- The old
--folder,--leveland--accept-all-risks(and their other names, such as--pastaand--nivel) are accepted and ignored, with a note. - What comes after
--goes to the script (sys.argv). - The exit code is the script's (1 if it ends with an error, with the line of the error).
python -m badbit infoshows the package version, the BadBit CAD found and the open one.
A count.py that makes a spreadsheet with the blocks of each drawing:
import csv, sys
from collections import Counter
import badbit
with open("blocks.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["drawing", "block", "count"])
for path in badbit.each_drawing(sys.argv[1]):
counts = Counter(e["block"] for e in badbit.entities(types=["insert"]))
for name, n in counts.most_common():
w.writerow([path.name, name, n])Scripts: always available
Your Python scripts always work, with nothing to turn on and nothing to accept: in
BadBit Scripts, in the Python on your machine with the badbit package, in the VS Code
extension and in the batch without a window (badbit.headless() and python -m badbit run script.py --headless). They are your own code, like LISP. The local channel always
opens with the program, for your user only, and connected scripts do not show on the
status bar.
AI (MCP): turning it on and the risk notice
BadBit's only switch is AI (MCP), in Options > AI (MCP) or with the AI button on the status bar: it lets AI assistants control BadBit and comes turned off. When you turn it on, BadBit shows what the AI can then do (everything you do in BadBit, and run Python and LISP code with your user's permissions) and the risks, and asks for the box I understand the risks and authorize it. It changes nothing for your scripts. The details are in the MCP guide.
Security
- Scripts run with your account's permissions on the computer, like any program. Run only scripts from people you trust.
- The trusted folders and the LISP load warning (SECURELOAD) apply to Python
too: a
.pyoutside them asks before running (Load once, Always load from this folder, Do not load); with SECURELOAD 2, only trusted folders run. - The local channel belongs to your user only, with a new secret code each time BadBit runs: only your own programs, on this computer, can use it.
- In the batch without a window, BadBit opens no channel for other programs (only your script talks to it, through the process's input and output), has no clipboard and never receives the secret code of an open BadBit, not even when the script runs from BadBit Scripts.
- Texts and names coming from the drawing arrive as data (
{"user_content": ...}): treat them as text, never as instructions.