Básicos de Guionización FreeCAD

From FreeCAD Documentation

guiones Python en FreeCAD

FreeCAD está construido desde cero para que sea totalmente controlado por guiones (scripts) Python. Casi todas las partes de FreeCAD como la interfaz, el contenido de la escena, e incluso la representación de ese contenido en las vistas 3d, son accesibles desde el intérprete de Python incorporado, o desde sus propios scripts. Como resultado, FreeCAD es, probablemente, una de las aplicaciones de diseño ingenieril más personalizables disponibles en la actualidad.

En su estado actual, sin embargo, FreeCAD tiene muy pocos comandos "nativos" para interactuar sobre los objetos 3D. Sobre todo porque se encuentra todavía en fase temprana de desarrollo, pero también porque la filosofía que hay detrás es más para proporcionar una plataforma para el desarrollo CAD que una aplicación de usuario "a medida". Pero la facilidad de usar guiones Python dentro FreeCAD probablemente ayudará a que pronto veamos funcionalidades nuevas que desarrollen los "usuarios avanzados", o, más abundantes, los usuarios que conocen un poco de programación Python, como usted, Eso esperamos.

Si usted no está familiarizado con Python, le recomendamos buscar tutoriales en Internet, y echar un rápido vistazo a su estructura. Python es un lenguaje muy fácil de aprender, sobre todo porque se puede ejecutar dentro de un intérprete, donde tanto comandos simples como programas completos pueden ejecutarse sobre la marcha, sin necesidad de compilar nada. FreeCAD ha incorporado un intérprete de Python.

El intérprete

Desde el intérprete, puede acceder a todos los módulos de python instalados en el sistema, así como a los módulos FreeCAD incorporados, y a todos los módulos adicionales FreeCAD que pueda instalar más tarde. La imagen siguiente muestra el intérprete de Python:

The FreeCAD python interpreter

Desde el intérprete, puede ejecutar código Python y navegar a través de las clases y funciones disponibles. FreeCAD proporciona un navegador de clases muy útil para la exploración de su nuevo mundo FreeCAD. Cuando se escribe el nombre de una clase conocida seguido de un espacio (significando que quiere añadir algo de esa clase), se abre una ventana de navegador de clases, donde se puede navegar entre las subclases y métodos disponibles. Cuando se selecciona algo, un texto de ayuda asociado (si existe) se mostrará:

The FreeCAD class browser

Así que, comienza por aquí escribiendo Aplicación. OGui. Y vea qué pasa. Otra forma más genérica de exploración de los contenidos de los módulos y las clases Python es usar el comando print dir(). Por ejemplo, escribiendo print dir() listará todos los módulos cargados en FreeCAD. print Dir(App) le mostrará todo el interior del módulo App, etc

Otra característica útil del intérprete es la posibilidad de volver atrás en el historial de comandos y recuperar una línea de código que ya ha escrito antes. Para navegar en la historia de comandos, sólo tiene que utilizar CTRL +flecha arriba o CTRL + flecha ABAJO.

Al hacer clic derecho en la ventana del intérprete, también tiene otras opciones, tales como copia de toda la historia (útil para experimentar con algo, y luego hacer un guión con todo ello), o insertar el nombre de un archivo con su ruta completa.

Ayuda de Python

En el menú Ayuda de FreeCAD, encontrará una entrada llamada "ayuda Python", que abrirá una ventana que contiene una documentación completa, generada en tiempo real, de todos los módulos de Python a disposición del intérprete FreeCAD, incluyendo Python y módulos propios de FreeCAD, los módulos instalados por el sistema, y los módulos FreeCAD adicionales. La documentación disponible depende del esfuerzo que cada desarrollador de módulos puso en documentar su código pero, en general, los módulos Python tienen la reputación de estar bastante bien documentados. Su ventana FreeCAD debe permanecer abierta para que este sistema de documentación funcione.

Built-in modules

Since FreeCAD is designed to be run without Graphic User Interface, almost all its functionality is separated in two groups: Core functionality, named App, and Gui functionality, named Gui. So, our two main FreeCAD built-in modules are called App and Gui. These two modules can also be accessed from scripts outside of the interpreter, by the respective names of FreeCAD and FreeCADGui.

  • In the App module, you'll find everything related to the application itself, like methods for opening or closing files, and to the documents, like setting the active document or listing their contents.
  • In the Gui module, you'll find tools for accessing and managing Gui elements, like the workbenches and their toolbars, and, more interesting, the graphical representation of all FreeCAD content.

Listing all the content of those modules is a bit counter-productive task, since they grow quite fast along FreeCAD development. But the two browsing tools provided (the class browser and the python help) should give you, at any moment, a complete and up-to-date documentation of these modules.

The App and Gui objects

As we said, in FreeCAD, everything is separated between core and representation. This includes the 3D objects too. You can access defining properties of objects (called features in FreeCAD) via the App module, and change the way they are represented on screen via the Gui module. For example, a cube has properties that define it, like width, length, height, that are stored in an App object, and representation properties, such as faces color, drawing mode, that are stored in a corresponding Gui object.

This way of doing allows a very wide range of uses, like having algorithms work only on the defining part of features, without the need to care about any visual part, or even redirect the content of the document to non-graphical application, such as lists, spreadsheets, or element analysis.

For every App object in your document, exists a corresponding Gui object. The document itself, actually, also has App and a Gui objects. This, of course, is only valid when you run FreeCAD with its full interface. In the command-line version, no GUI exists, so only App objects are availible. Note that the Gui part of objects is generated again everytime an App object is marked as "to be recomputed" (for example when one of its parameters changed), so changes you might have done directly to the Gui object might get lost.

to access the App part of something, you type:

myObject = App.ActiveDocument.getObject("ObjectName")

where "ObjectName is the name of your object. You can also type:

myObject = App.ActiveDocument.ObjectName

to access the Gui part of the same object, you type:

myViewObject = Gui.ActiveDocument.getObject("ObjectName")

where "ObjectName is the name of your object. You can also type:

myViewObject = App.ActiveDocument.ObjectName.ViewObject

If we have no GUI (for example we are in command line mode), the last line will return None.

The Document objects

In FreeCAD all your work resides inside Documents. A document contains your geometry and can be saved to a file. Several documents can be opened at the same time. The document, like the geometry contained inside, has App and Gui objects. App object contains your actual geometry definitions, while the Gui object contains the different views of your document. You can open several windows, each one viewing your work with a different zoom factor or point of view. These views are all part of your document's Gui object.

To access the App part the currently open (active) document, you type:

myDocument = App.ActiveDocument

To create a new document, type:

myDocument = App.newDocument("Document Name")

To access the Gui part the currently open (active) document, you type:

myGuiDocument = Gui.ActiveDocument

To access the current view, you type:

myView = Gui.ActiveDocument.ActiveView



Introduction to python/es
Mesh Scripting/es