FreeCAD Scripting Basics/sv: Difference between revisions

From FreeCAD Documentation
(Created page with "===Tolken=== Från tolken så har du åtkomst till alla dina systeminstallerade pythonmoduler, såväl som FreeCAD's inbyggda moduler, och alla extra FreeCAD moduler som du in...")
(Updating to match new version of source page)
(33 intermediate revisions by 2 users not shown)
Line 1: Line 1:
<languages/>
{{docnav|[[Python scripting tutorial|Python scripting tutorial]]|[[Mesh Scripting|Mesh Scripting]]}}

== Python skript i FreeCAD ==
== Python skript i FreeCAD ==


Line 5: Line 8:
I dess nuvarande läge, så har FreeCAD emellertid mycket få "nativa" kommandon för att interagera på dina 3D objekt, huvudsakligen därför att den fortfarande är i ett tidigt utvecklingsstadium, men också för att filosofin bakom den är mer att erbjuda en plattform för CAD utveckling än en skräddarsydd användarapplikation. Men lättheten med python skript inuti FreeCAD kommer troligen att hjälpa mycket för att snabbt se ny funktionalitet utvecklas av "expertanvändare", eller, typiskt, användare som kan lite pythonprogrammering, som, hoppas vi, du själv.
I dess nuvarande läge, så har FreeCAD emellertid mycket få "nativa" kommandon för att interagera på dina 3D objekt, huvudsakligen därför att den fortfarande är i ett tidigt utvecklingsstadium, men också för att filosofin bakom den är mer att erbjuda en plattform för CAD utveckling än en skräddarsydd användarapplikation. Men lättheten med python skript inuti FreeCAD kommer troligen att hjälpa mycket för att snabbt se ny funktionalitet utvecklas av "expertanvändare", eller, typiskt, användare som kan lite pythonprogrammering, som, hoppas vi, du själv.


<div class="mw-translate-fuzzy">
Om du inte kan något om python, så rekommenderar vi att du letar efter övningar på internet, och tar en snabbtitt på dess struktur. Python är ett mycket lättlärt språk, speciellt eftersom det kan köras inuti en tolk, där allt från enkla kommandon till kompletta program kan köras direkt, utan något bahov för kompilering. FreeCAD har en inbyggd tolk.
Om du inte kan något om python, så rekommenderar vi att du letar efter övningar på internet, och tar en snabbtitt på dess struktur. Python är ett mycket lättlärt språk, speciellt eftersom det kan köras inuti en tolk, där allt från enkla kommandon till kompletta program kan köras direkt, utan något bahov för kompilering. FreeCAD har en inbyggd tolk.
Om du inte ser fönstret "Rapportvy", som visas nedan, så kan du få fram den genom att klicka på Vy -> Vyer -> Rapportvy.
Om du inte ser fönstret "Rapportvy", som visas nedan, så kan du få fram den genom att klicka på Vy -> Vyer -> Rapportvy.
</div>


===Tolken===
===Tolken===
Från tolken så har du åtkomst till alla dina systeminstallerade pythonmoduler, såväl som FreeCAD's inbyggda moduler, och alla extra FreeCAD moduler som du installerat senare. Skärmdumpen nedan visar python tolken:
Från tolken så har du åtkomst till alla dina systeminstallerade pythonmoduler, såväl som FreeCAD's inbyggda moduler, och alla extra FreeCAD moduler som du installerat senare. Skärmdumpen nedan visar python tolken:


[[Image:screenshot_pythoninterpreter.jpg|The FreeCAD Python interpreter]]
[[Image:screenshot_pythoninterpreter.jpg|FreeCAD python tolken]]


Från tolken kan du köra pythonkod, lista igenom tillgängliga klasser och funktioner. FreeCAD erbjuder en väldigt smidig klasslistare för utforskning av din nya FreeCAD värld: När du skriver namnet på en känd klass följt av en punkt (vilket innebär att du vill addera något från den klassen), så öppnas en klasslistare, där du kan navigera mellan tillgängliga underklasser och metoder. När du väljer något, så visas en associerad hjälptext (om den finns):
From the interpreter, you can execute Python code and browse through the available classes and functions. FreeCAD provides a very handy class browser for exploration of your new FreeCAD world: When you type the name of a known class followed by a period (meaning you want to add something from that class), a class browser window opens, where you can navigate between available subclasses and methods. When you select something, an associated help text (if it exists) is displayed:


[[Image:screenshot_classbrowser.jpg|The FreeCAD class browser]]
[[Image:screenshot_classbrowser.jpg|FreeCAD klasslistare]]


So, start here by typing '''App.''' or '''Gui.''' and see what happens. Another more generic Python way of exploring the content of modules and classes is to use the 'print dir()' command. For example, typing '''print dir()''' will list all modules currently loaded in FreeCAD. '''print dir(App)''' will show you everything inside the App module, etc.
, starta här genom att skriva '''App.''' eller '''Gui.''' och se vad som händer. Ett annat mer allmänt python-sätt att utforska modul- och klassinnehåll är att använda print dir() kommandot. Till exempel, genom att skriva '''print dir()''' kommer alla moduler som för närvarande är laddade i FreeCAD att listas. '''print dir(App)''' kommer att visa dig allt inuti App modulen, etc.


En annan användbar egenskap hos tolken är möjligheten att backa i kommandohistorian och hämta en kod-rad som du skrivit tidigare. För att navigera i kommandohistorian, använd CTRL+UPP-PIL eller CTRL+NED-PIL.
Another useful feature of the interpreter is the possibility to go back through the command history and retrieve a line of code that you already typed earlier. To navigate through the command history, just use CTRL+UP or CTRL+DOWN.


Genom att högerklicka i tolkfönstret, så har du flera andra alternativ, som att kopiera hela historian (användbart för att göra en experimentskript, och sedan kunna spara det), eller att sätta in ett filnamn med full sökväg.
By right-clicking in the interpreter window, you also have several other options, such as copy the entire history (useful when you want to experiment with things before making a full script of them), or insert a filename with complete path.


<div class="mw-translate-fuzzy">
===Python Help===
===Python Hjälp===
In the FreeCAD Help menu, you'll find an entry labeled 'Python help', which will open a browser window containing a complete, realtime-generated documentation of all Python modules available to the FreeCAD interpreter, including Python and FreeCAD built-in modules, system-installed modules, and FreeCAD additional modules. The documentation available there depends on how much effort each module developer put into documenting his code, but usually Python modules have a reputation for being fairly well documented. Your FreeCAD window must stay open for this documentation system to work.
I FreeCAD Hjälpmenyn, så hittar du en menypunkt som heter "Python hjälp", vilken kommer att öppna ett webbfönster som innehåller en komplett, realtidsgenererad dokumentation över alla python moduler som finns tillgänglig för FreeCAD tolken, inklusive python inbyggda FreeCAD moduler, system-installerade moduler, och extra FreeCAD moduler. Den dokumentation som fills tillgänglig där beror på hur mycket arbete varje modulutvecklare lägger på att dokumentera sin kod, men vanligtvis her pythonmoduler ett rykte om sig att vara ganska väldokumenterade. Ditt FreeCAD fönster måste vara öppet för att detta dokumentationssystem ska fungera.
</div>


==Built-in modules==
==Inbyggda moduler==
Since FreeCAD is designed to be run without a Graphical User Interface (GUI), almost all its functionality is separated into 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 names 'FreeCAD' and 'FreeCADGui' respectively.
Eftersom FreeCAD är designat för att kunna köras utan ett grafiskt användargränssnitt, så är nästan all dess funktionalitet uppdelat i två grupper: Kärnfunktioner, benämnda App, och gränssnittsfunktioner, benämnda Gui. våra två inbyggda FreeCAD huvudmoduler kallas för App och Gui. Dessa två moduler kan även kommas åt av skript utanför tolken, genom de respektive namnen FreeCAD och FreeCADGui.


* I '''App modulen''', så hittar du allt som är relaterat till själva applikationen, som metoder för att öppna eller stänga filer, och till dokumenten, som att ställa in det aktiva dokumentet eller lista dess innehåll.
* 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.


* I '''Gui modulen''', så hittar du verktyg för åtkomst och hantering av gränssnittselement, som arbetsbänkarna och dears verktygslådor, och mer intressant, den grafiska representationen av allt FreeCAD innehåll.
* In the '''Gui module''', you'll find tools for accessing and managing Gui elements, like the workbenches and their toolbars, and, more interestingly, the graphical representation of all FreeCAD content.


Att lista allt innehåll av dessa moduler är en lite improduktiv uppgift, eftersom de växer ganska snabbt tillsammans med FreeCAD's utveckling. Men de två erbjudna listverktygen (klasslistaren och python hjälpen) ska alltid ge dig en komplett och uppdaterad dokumentation av dessa moduler.
Listing all the content of those modules is a bit counter-productive task, since they grow quite fast with FreeCAD development. But the two browsing tools provided (the class browser and the Python help) should give you, at any moment, complete and up-to-date documentation of these modules.


===The App and Gui objects===
===App och Gui objekten===
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, (like faces color, drawing mode) that are stored in a corresponding Gui object.
Som vi sade, är allt i FreeCAD uppdelat mellan kärna och representation. Detta inkluderar även 3D objekten. Du kan komma åt objektens definierande egenskaper (kallade features i FreeCAD) via App modulen, och ändra det sätt som de representeras skärmen via Gui modulen. Till exempel, en kub har egenskaper som definierar den, som bredd, längd, höjd som sparas i ett App objekt, och representationsegenskaper, som ytfärg, ritläge, som lagras i ett motsvarande Gui objekt.


Detta sätt att göra det på tillåter ett mycket brett användningsområde, som att låta algoritmer endast arbeta på den definierande delen av objekten, utan att behöva bry sig om någon visuell del, eller även att skicka dokumentets innehåll till icke-grafiska applikationer, som listor, räkneark eller elementanalyser.
This way of doing things allows a very wide range of uses, like having algorithms work only on the definition 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, there exists a corresponding Gui object. Infact the document itself has both 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 re-generated every time an App object is marked as 'to be recomputed' (for example when one of its parameters changes), so changes you might have made directly to the Gui object may be lost.
För varje App objekt i ditt dokument, existerar det ett motsvarande Gui objekt. Själva dokumentet har faktiskt också ett App och ett Gui objekt. Detta är förstås endast giltigt när du kör FreeCAD med dess fulla gränssnitt. I kommando-linje versionen, så existerar inget gränssnitt, endast App objekt är tillgängliga. Notera att Gui delen av objekt genereras igen varje gång som ett App objekt är markerat som "att omberäknas" (till exempel när en av dess parametrar har ändrats), ändringar som du har gjort direkt Gui objektet kan förloras.


To access the App part of something, you type:
För att komma åt App delen av något, så skriver du:
{{Code|code=
<syntaxhighlight>
myObject = App.ActiveDocument.getObject("ObjectName")
myObject = App.ActiveDocument.getObject("ObjectName")
}}
</syntaxhighlight>
där "ObjektNamn är namnet på ditt objekt. Du kan också skriva:
where "ObjectName" is the name of your object. You can also type:
{{Code|code=
<syntaxhighlight>
myObject = App.ActiveDocument.ObjectName
myObject = App.ActiveDocument.ObjectName
}}
</syntaxhighlight>
To access the Gui part of the same object, you type:
För att komma åt Gui delen av samma objekt, skriv:
{{Code|code=
<syntaxhighlight>
myViewObject = Gui.ActiveDocument.getObject("ObjectName")
myViewObject = Gui.ActiveDocument.getObject("ObjectName")
}}
</syntaxhighlight>
där "ObjektNamn är namnet på ditt objekt. Du kan också skriva:
where "ObjectName" is the name of your object. You can also type:
{{Code|code=
<syntaxhighlight>
myViewObject = App.ActiveDocument.ObjectName.ViewObject
myViewObject = App.ActiveDocument.ObjectName.ViewObject
}}
</syntaxhighlight>
Om vi inte har något gränssnitt (vi är till exempel i kommandoradsläge), så kommer den sista raden att returnera None.
If we have no GUI (for example we are in command-line mode), the last line will return 'None'.


=== The Document objects ===
=== Dokument objekten ===
I FreeCAD så finns allt ditt arbete i Dokument. Ett dokument innehåller din geometri och kan sparas till en fil. Flera dokument kan öppnas samtidigt. Dokumentet, som geometrin som finns i den, har App och Gui objekt. App objekt innehåller dina geometridefinitioner, medan Gui objekt innehåller ditt dokuments olika vyer Du kan öppna flera fönster, där varje fönster visar ditt arbete med en annan zoomfaktor eller synvinkel. Dessa vyer är en del av Gui objektet i ditt dokument.
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.


För att komma åt App delen i det aktiva dokumentet, skriv:
To access the App part the currently open (active) document, you type:
{{Code|code=
<syntaxhighlight>
myDocument = App.ActiveDocument
myDocument = App.ActiveDocument
}}
</syntaxhighlight>
För att skapa ett nytt dokument, skriv:
To create a new document, type:
{{Code|code=
<syntaxhighlight>
myDocument = App.newDocument("Document Name")
myDocument = App.newDocument("Document Name")
}}
</syntaxhighlight>
För att komma åt Gui delen i det aktiva dokumentet, skriv:
To access the Gui part the currently open (active) document, you type:
{{Code|code=
<syntaxhighlight>
myGuiDocument = Gui.ActiveDocument
myGuiDocument = Gui.ActiveDocument
}}
</syntaxhighlight>
För att komma åt nuvarande vy, skriv:
To access the current view, you type:
{{Code|code=
<syntaxhighlight>
myView = Gui.ActiveDocument.ActiveView
myView = Gui.ActiveDocument.ActiveView
}}
</syntaxhighlight>
== Using additional modules ==
== Using additional modules ==
The FreeCAD and FreeCADGui modules are solely responsibles for creating and managing objects in the FreeCAD document. They don't actually do anything such as creating or modifying geometry. That is because that geometry can be of several types, and so it is managed by additional modules, each responsible for managing a certain geometry type. For example, the [[Part Module]] uses the OpenCascade kernel, and therefore is able to create and manipulate [http://en.wikipedia.org/wiki/Boundary_representation B-rep] type geometry, which is what OpenCascade is built for. The [[Mesh Module]] is able to build and modify mesh objects. That way, FreeCAD is able to handle a wide variety of object types, that can all coexist in the same document, and new types could be added easily in the future.
The FreeCAD and FreeCADGui modules are solely responsibles for creating and managing objects in the FreeCAD document. They don't actually do anything such as creating or modifying geometry. That is because that geometry can be of several types, and so it is managed by additional modules, each responsible for managing a certain geometry type. For example, the [[Part Module|Part Module]] uses the OpenCascade kernel, and therefore is able to create and manipulate [http://en.wikipedia.org/wiki/Boundary_representation B-rep] type geometry, which is what OpenCascade is built for. The [[Mesh Module|Mesh Module]] is able to build and modify mesh objects. That way, FreeCAD is able to handle a wide variety of object types, that can all coexist in the same document, and new types could be added easily in the future.


=== Creating objects ===
=== Creating objects ===
Each module has its own way to treat its geometry, but one thing they usually all can do is create objects in the document. But the FreeCAD document is also aware of the available object types provided by the modules:
Each module has its own way to treat its geometry, but one thing they usually all can do is create objects in the document. But the FreeCAD document is also aware of the available object types provided by the modules:
{{Code|code=
<syntaxhighlight>
FreeCAD.ActiveDocument.supportedTypes()
FreeCAD.ActiveDocument.supportedTypes()
}}
</syntaxhighlight>
will list you all the possible objects you can create. For example, let's create a mesh (treated by the mesh module) and a part (treated by the part module):
will list you all the possible objects you can create. For example, let's create a mesh (treated by the mesh module) and a part (treated by the part module):
{{Code|code=
<syntaxhighlight>
myMesh = FreeCAD.ActiveDocument.addObject("Mesh::Feature","myMeshName")
myMesh = FreeCAD.ActiveDocument.addObject("Mesh::Feature","myMeshName")
myPart = FreeCAD.ActiveDocument.addObject("Part::Feature","myPartName")
myPart = FreeCAD.ActiveDocument.addObject("Part::Feature","myPartName")
}}
</syntaxhighlight>
The first argument is the object type, the second the name of the object. Our two objects look almost the same: They don't contain any geometry yet, and most of their properties are the same when you inspect them with dir(myMesh) and dir(myPart). Except for one, myMesh has a "Mesh" property and "Part" has a "Shape" property. That is where the Mesh and Part data are stored. For example, let's create a Part cube and store it in our myPart object:
The first argument is the object type, the second the name of the object. Our two objects look almost the same: They don't contain any geometry yet, and most of their properties are the same when you inspect them with dir(myMesh) and dir(myPart). Except for one, myMesh has a "Mesh" property and "Part" has a "Shape" property. That is where the Mesh and Part data are stored. For example, let's create a Part cube and store it in our myPart object:
{{Code|code=
<syntaxhighlight>
import Part
import Part
cube = Part.makeBox(2,2,2)
cube = Part.makeBox(2,2,2)
myPart.Shape = cube
myPart.Shape = cube
}}
</syntaxhighlight>
You could try storing the cube inside the Mesh property of the myMesh object, it will return an error complaining of the wrong type. That is because those properties are made to store only a certain type. In the myMesh's Mesh property, you can only save stuff created with the Mesh module. Note that most modules also have a shortcut to add their geometry to the document:
You could try storing the cube inside the Mesh property of the myMesh object, it will return an error complaining of the wrong type. That is because those properties are made to store only a certain type. In the myMesh's Mesh property, you can only save stuff created with the Mesh module. Note that most modules also have a shortcut to add their geometry to the document:
{{Code|code=
<syntaxhighlight>
import Part
import Part
cube = Part.makeBox(2,2,2)
cube = Part.makeBox(2,2,2)
Part.show(cube)
Part.show(cube)
}}
</syntaxhighlight>
=== Modifying objects ===
=== Modifying objects ===
Modifying an object is done the same way:
Modifying an object is done the same way:
{{Code|code=
<syntaxhighlight>
import Part
import Part
cube = Part.makeBox(2,2,2)
cube = Part.makeBox(2,2,2)
myPart.Shape = cube
myPart.Shape = cube
}}
</syntaxhighlight>
Now let's change the shape by a bigger one:
Now let's change the shape by a bigger one:
{{Code|code=
<syntaxhighlight>
biggercube = Part.makeBox(5,5,5)
biggercube = Part.makeBox(5,5,5)
myPart.Shape = biggercube
myPart.Shape = biggercube
}}
</syntaxhighlight>
=== Querying objects ===
=== Querying objects ===
You can always look at the type of an object like this:
You can always look at the type of an object like this:
{{Code|code=
<syntaxhighlight>
myObj = FreeCAD.ActiveDocument.getObject("myObjectName")
myObj = FreeCAD.ActiveDocument.getObject("myObjectName")
print myObj.Type
print myObj.TypeId
}}
</syntaxhighlight>
or know if an object is derived from one of the basic ones (Part Feature, Mesh Feature, etc):
or know if an object is derived from one of the basic ones (Part Feature, Mesh Feature, etc):
{{Code|code=
<syntaxhighlight>
print myObj.isDerivedFrom("Part::Feature")
print myObj.isDerivedFrom("Part::Feature")
}}
</syntaxhighlight>
Now you can really start playing with FreeCAD! To look at what you can do with the [[Part Module]], read the [[Topological data scripting|Part scripting]] page, or the [[Mesh Scripting]] page for working with the [[Mesh Module]]. Note that, although the Part and Mesh modules are the most complete and widely used, other modules such as the [[Draft Module]] also have [[Draft API|scripting]] APIs that can be useful to you. For a complete list of each modules and their available tools, visit the [[:Category:API]] section.
Now you can really start playing with FreeCAD! To look at what you can do with the [[Part Module|Part Module]], read the [[Topological data scripting|Part scripting]] page, or the [[Mesh Scripting|Mesh Scripting]] page for working with the [[Mesh Module|Mesh Module]]. Note that, although the Part and Mesh modules are the most complete and widely used, other modules such as the [[Draft Module|Draft Module]] also have [[Draft API|scripting]] APIs that can be useful to you. For a complete list of each modules and their available tools, visit the [[:Category:API|Category:API]] section.


<div class="mw-translate-fuzzy">
{{docnav|Python scripting tutorial|Mesh Scripting}}
{{docnav/sv|Introduction to Python/sv|Mesh Scripting/sv}}
</div>

{{Userdocnavi}}

[[Category:Poweruser Documentation/sv]]

[[Category:Python Code]]


[[Category:Poweruser Documentation]]


{{clear}}
{{clear}}
<languages/>

Revision as of 19:11, 30 March 2019

Python skript i FreeCAD

FreeCAD är byggt från grunden att helt och hållet kunna kontrolleras av python skript. Nästan alla delar av FreeCAD som gränssnittet, sceninnehållet, och även representationen av detta innehåll i 3d vyerna kan kommas åt från den inbyggda pythontolken eller från dina egna skript. Resultatet av detta är att FreeCAD troligen är en av de mest anpassningsbara konstruktionsapplikationerna som finns idag.

I dess nuvarande läge, så har FreeCAD emellertid mycket få "nativa" kommandon för att interagera på dina 3D objekt, huvudsakligen därför att den fortfarande är i ett tidigt utvecklingsstadium, men också för att filosofin bakom den är mer att erbjuda en plattform för CAD utveckling än en skräddarsydd användarapplikation. Men lättheten med python skript inuti FreeCAD kommer troligen att hjälpa mycket för att snabbt se ny funktionalitet utvecklas av "expertanvändare", eller, typiskt, användare som kan lite pythonprogrammering, som, hoppas vi, du själv.

Om du inte kan något om python, så rekommenderar vi att du letar efter övningar på internet, och tar en snabbtitt på dess struktur. Python är ett mycket lättlärt språk, speciellt eftersom det kan köras inuti en tolk, där allt från enkla kommandon till kompletta program kan köras direkt, utan något bahov för kompilering. FreeCAD har en inbyggd tolk. Om du inte ser fönstret "Rapportvy", som visas nedan, så kan du få fram den genom att klicka på Vy -> Vyer -> Rapportvy.

Tolken

Från tolken så har du åtkomst till alla dina systeminstallerade pythonmoduler, såväl som FreeCAD's inbyggda moduler, och alla extra FreeCAD moduler som du installerat senare. Skärmdumpen nedan visar python tolken:

FreeCAD python tolken

Från tolken kan du köra pythonkod, lista igenom tillgängliga klasser och funktioner. FreeCAD erbjuder en väldigt smidig klasslistare för utforskning av din nya FreeCAD värld: När du skriver namnet på en känd klass följt av en punkt (vilket innebär att du vill addera något från den klassen), så öppnas en klasslistare, där du kan navigera mellan tillgängliga underklasser och metoder. När du väljer något, så visas en associerad hjälptext (om den finns):

FreeCAD klasslistare

Så, starta här genom att skriva App. eller Gui. och se vad som händer. Ett annat mer allmänt python-sätt att utforska modul- och klassinnehåll är att använda print dir() kommandot. Till exempel, genom att skriva print dir() så kommer alla moduler som för närvarande är laddade i FreeCAD att listas. print dir(App) kommer att visa dig allt inuti App modulen, etc.

En annan användbar egenskap hos tolken är möjligheten att backa i kommandohistorian och hämta en kod-rad som du skrivit tidigare. För att navigera i kommandohistorian, använd CTRL+UPP-PIL eller CTRL+NED-PIL.

Genom att högerklicka i tolkfönstret, så har du flera andra alternativ, som att kopiera hela historian (användbart för att göra en experimentskript, och sedan kunna spara det), eller att sätta in ett filnamn med full sökväg.

Python Hjälp

I FreeCAD Hjälpmenyn, så hittar du en menypunkt som heter "Python hjälp", vilken kommer att öppna ett webbfönster som innehåller en komplett, realtidsgenererad dokumentation över alla python moduler som finns tillgänglig för FreeCAD tolken, inklusive python inbyggda FreeCAD moduler, system-installerade moduler, och extra FreeCAD moduler. Den dokumentation som fills tillgänglig där beror på hur mycket arbete varje modulutvecklare lägger på att dokumentera sin kod, men vanligtvis her pythonmoduler ett rykte om sig att vara ganska väldokumenterade. Ditt FreeCAD fönster måste vara öppet för att detta dokumentationssystem ska fungera.

Inbyggda moduler

Eftersom FreeCAD är designat för att kunna köras utan ett grafiskt användargränssnitt, så är nästan all dess funktionalitet uppdelat i två grupper: Kärnfunktioner, benämnda App, och gränssnittsfunktioner, benämnda Gui. Så våra två inbyggda FreeCAD huvudmoduler kallas för App och Gui. Dessa två moduler kan även kommas åt av skript utanför tolken, genom de respektive namnen FreeCAD och FreeCADGui.

  • I App modulen, så hittar du allt som är relaterat till själva applikationen, som metoder för att öppna eller stänga filer, och till dokumenten, som att ställa in det aktiva dokumentet eller lista dess innehåll.
  • I Gui modulen, så hittar du verktyg för åtkomst och hantering av gränssnittselement, som arbetsbänkarna och dears verktygslådor, och mer intressant, den grafiska representationen av allt FreeCAD innehåll.

Att lista allt innehåll av dessa moduler är en lite improduktiv uppgift, eftersom de växer ganska snabbt tillsammans med FreeCAD's utveckling. Men de två erbjudna listverktygen (klasslistaren och python hjälpen) ska alltid ge dig en komplett och uppdaterad dokumentation av dessa moduler.

App och Gui objekten

Som vi sade, så är allt i FreeCAD uppdelat mellan kärna och representation. Detta inkluderar även 3D objekten. Du kan komma åt objektens definierande egenskaper (kallade features i FreeCAD) via App modulen, och ändra det sätt som de representeras på skärmen via Gui modulen. Till exempel, en kub har egenskaper som definierar den, som bredd, längd, höjd som sparas i ett App objekt, och representationsegenskaper, som ytfärg, ritläge, som lagras i ett motsvarande Gui objekt.

Detta sätt att göra det på tillåter ett mycket brett användningsområde, som att låta algoritmer endast arbeta på den definierande delen av objekten, utan att behöva bry sig om någon visuell del, eller även att skicka dokumentets innehåll till icke-grafiska applikationer, som listor, räkneark eller elementanalyser.

För varje App objekt i ditt dokument, så existerar det ett motsvarande Gui objekt. Själva dokumentet har faktiskt också ett App och ett Gui objekt. Detta är förstås endast giltigt när du kör FreeCAD med dess fulla gränssnitt. I kommando-linje versionen, så existerar inget gränssnitt, så endast App objekt är tillgängliga. Notera att Gui delen av objekt genereras igen varje gång som ett App objekt är markerat som "att omberäknas" (till exempel när en av dess parametrar har ändrats), så ändringar som du har gjort direkt på Gui objektet kan förloras.

För att komma åt App delen av något, så skriver du:

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

där "ObjektNamn är namnet på ditt objekt. Du kan också skriva:

myObject = App.ActiveDocument.ObjectName

För att komma åt Gui delen av samma objekt, skriv:

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

där "ObjektNamn är namnet på ditt objekt. Du kan också skriva:

myViewObject = App.ActiveDocument.ObjectName.ViewObject

Om vi inte har något gränssnitt (vi är till exempel i kommandoradsläge), så kommer den sista raden att returnera None.

Dokument objekten

I FreeCAD så finns allt ditt arbete i Dokument. Ett dokument innehåller din geometri och kan sparas till en fil. Flera dokument kan öppnas samtidigt. Dokumentet, som geometrin som finns i den, har App och Gui objekt. App objekt innehåller dina geometridefinitioner, medan Gui objekt innehåller ditt dokuments olika vyer Du kan öppna flera fönster, där varje fönster visar ditt arbete med en annan zoomfaktor eller synvinkel. Dessa vyer är en del av Gui objektet i ditt dokument.

För att komma åt App delen i det aktiva dokumentet, skriv:

myDocument = App.ActiveDocument

För att skapa ett nytt dokument, skriv:

myDocument = App.newDocument("Document Name")

För att komma åt Gui delen i det aktiva dokumentet, skriv:

myGuiDocument = Gui.ActiveDocument

För att komma åt nuvarande vy, skriv:

myView = Gui.ActiveDocument.ActiveView

Using additional modules

The FreeCAD and FreeCADGui modules are solely responsibles for creating and managing objects in the FreeCAD document. They don't actually do anything such as creating or modifying geometry. That is because that geometry can be of several types, and so it is managed by additional modules, each responsible for managing a certain geometry type. For example, the Part Module uses the OpenCascade kernel, and therefore is able to create and manipulate B-rep type geometry, which is what OpenCascade is built for. The Mesh Module is able to build and modify mesh objects. That way, FreeCAD is able to handle a wide variety of object types, that can all coexist in the same document, and new types could be added easily in the future.

Creating objects

Each module has its own way to treat its geometry, but one thing they usually all can do is create objects in the document. But the FreeCAD document is also aware of the available object types provided by the modules:

FreeCAD.ActiveDocument.supportedTypes()

will list you all the possible objects you can create. For example, let's create a mesh (treated by the mesh module) and a part (treated by the part module):

myMesh = FreeCAD.ActiveDocument.addObject("Mesh::Feature","myMeshName")
myPart = FreeCAD.ActiveDocument.addObject("Part::Feature","myPartName")

The first argument is the object type, the second the name of the object. Our two objects look almost the same: They don't contain any geometry yet, and most of their properties are the same when you inspect them with dir(myMesh) and dir(myPart). Except for one, myMesh has a "Mesh" property and "Part" has a "Shape" property. That is where the Mesh and Part data are stored. For example, let's create a Part cube and store it in our myPart object:

import Part
cube = Part.makeBox(2,2,2)
myPart.Shape = cube

You could try storing the cube inside the Mesh property of the myMesh object, it will return an error complaining of the wrong type. That is because those properties are made to store only a certain type. In the myMesh's Mesh property, you can only save stuff created with the Mesh module. Note that most modules also have a shortcut to add their geometry to the document:

import Part
cube = Part.makeBox(2,2,2)
Part.show(cube)

Modifying objects

Modifying an object is done the same way:

import Part
cube = Part.makeBox(2,2,2)
myPart.Shape = cube

Now let's change the shape by a bigger one:

biggercube = Part.makeBox(5,5,5)
myPart.Shape = biggercube

Querying objects

You can always look at the type of an object like this:

myObj = FreeCAD.ActiveDocument.getObject("myObjectName")
print myObj.TypeId

or know if an object is derived from one of the basic ones (Part Feature, Mesh Feature, etc):

print myObj.isDerivedFrom("Part::Feature")

Now you can really start playing with FreeCAD! To look at what you can do with the Part Module, read the Part scripting page, or the Mesh Scripting page for working with the Mesh Module. Note that, although the Part and Mesh modules are the most complete and widely used, other modules such as the Draft Module also have scripting APIs that can be useful to you. For a complete list of each modules and their available tools, visit the Category:API section.

Introduction to Python/sv
Mesh Scripting/sv