How to `import FreeCAD` in CLI (python)
How can I import FreeCAD
from the python console?
I’m trying to write a script that can manipulate a given FreeCAD file, but I can’t even get FreeCAD imported into the python console on a system where FreeCAD is installed.
user@disp7637:~$ sudo dpkg -l | grep -i freecad
ii freecad 0.19.1+dfsg1-2+deb11u1 all Extensible Open Source CAx program
ii freecad-common 0.19.1+dfsg1-2+deb11u1 all Extensible Open Source CAx program - common files
ii freecad-python3 0.19.1+dfsg1-2+deb11u1 amd64 Extensible Open Source CAx program - Python 3 binaries
ii libfreecad-python3-0.19 0.19.1+dfsg1-2+deb11u1 amd64 Extensible Open Source CAx program - Python 3 library files
user@disp7637:~$
user@disp7637:~$ python3
Python 3.9.2 (default, Feb 28 2021, 17:03:44)
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import FreeCAD
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'FreeCAD'
>>> import freecad
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'freecad'
>>>
I am running Debian 11
user@disp7637:~$ cat /etc/issue
Debian GNU/Linux 11 n l
user@disp7637:~$
How can I import FreeCAD
in the python console?
Ah, I think the post you’re referring to is overselling things a bit when it says
There is also possibility to import FreeCAD as a Python module but this is more complex.
FreeCAD in itself embeds python to give access to its internal state to scripts running within in the FreeCAD process.
So, things like import order start to matter. Anyways, here we go:
Because the modules are so interlinked with FreeCAD, they’re not installed to python standard module paths; instead, you will find them in /usr/lib/freecad-python3/lib
on debian. So,
from sys import path as syspath
syspath.append("/usr/lib/freecad-python3/lib")
syspath.append("/usr/share/freecad/Mod/")
import FreeCAD
import Draft
By the way, other distros more stubbornly use architectural names for these subfolders, so on Fedora and related distros, the path happens to be /usr/lib64/freecad/lib64
, at least on x86_64.