Introduction à l'utilisation de la connexion Archicad-Python : Différence entre versions

De Wiki-Cadlink
Sauter à la navigation Sauter à la recherche
(Comment apprendre python?)
Ligne 1 : Ligne 1 :
(tutoriel initialement rédigé par [https://www.archi-cadlink.fr/memberlist.php?mode=viewprofile&u=70 MathiasJ] sur le forum [https://www.archi-cadlink.fr/ Archi-cadlink] puis remis en forme ici.)
+
((tutorial originally written by [https://www.archi-cadlink.fr/memberlist.php?mode=viewprofile&u=70 MathiasJ] on the [https://www.archi-cadlink.fr/ Archi-cadlink] forum and then re-formatted here).  
 
== Introduction ==
 
== Introduction ==
=== Qu'est ce que python? ===
+
=== What is python? ===
C'est un langage de programmation particulièrement utilisé pour l’automatisation de tâches simples mais fastidieuses. Il a été créé en 1991 et en est aujourd'hui à la version 3.12 (date du post). De manière générale, on parle de version 3 pour la version actuelle. C'est celle qui est utilisée pour archicad.
+
It is a programming language particularly used for the automation of simple but tedious tasks. It was created in 1991 and is now at version 3.12 (date of the post). In general, we speak of version 3 for the current version. It is the one used for archicad.
  
Pour utiliser python, il faut l'installer (voir le site officiel https://www.python.org/).
+
To use python, you need to install it (voir le site officiel https://www.python.org/).
  
=== Comment travailler avec python sur archicad ? ===
+
=== How to work with python in archicad? ===
 +
 
 +
* Install the latest version of the python language on the official website (Latest version 3.XX)
 +
* Activate Python in the experimental options (Options > Working environment > Other options & check the box " Activate Python Palette")
 +
* Display the Python palette now available.
 +
* Follow the indications of the palette to finalize the installation.
  
* Installer la dernière version du langage python sur le site officiel (Dernière version 3.XX)
 
* Activer Python dans les options expérimentales (Options > Environnement de travail > Autres options & cocher la case « Activer palette Python Palette»)
 
* Afficher la palette python maintenant accessible.
 
* Suivre les indications de la palette pour finaliser l'installation.
 
  
 
<gallery>
 
<gallery>
Ligne 18 : Ligne 19 :
 
</gallery>
 
</gallery>
  
=== Comment marche la connexion? ===
+
=== How does the connection work? ===
La connexion marche en utilisant la palette python.
+
The connection works by using the python palette.
  
Cette palette est composée de deux parties: une partie où l'on sélectionne ses scripts (en haut) et on lance le script voulu , et une partie nommée "console" ou l'ordinateur va vous donner des informations.
+
This palette is composed of two parts: a part where you select your scripts (on top) and launch the desired script, and a part named "console" where the computer will give you information.
  
==== La Partie script ====
+
==== The script section ====
On sélectionne l'icone dossier et on indique où se trouvent les scripts à utiliser. Un bouton permet de supprimer le dossier, et un autre sert à actualiser la liste.
+
We select the folder icon and indicate where the scripts to be used are located. A button is used to delete the folder, and another one is used to update the list.
  
 
[[Fichier:Python3.png|thumb|left]]
 
[[Fichier:Python3.png|thumb|left]]
 
<br clear=all>
 
<br clear=all>
  
Pour lancer un script, il suffit de sélectionner le script choisi (1), et de cliquer sur lancer (2). On peut aussi double cliquer sur le nom du script pour le lancer.  
+
To launch a script, just select the chosen script (1), and click on launch (2). You can also double click on the script name to launch it.  
  
 
[[Fichier:Python4.png|thumb|left]]
 
[[Fichier:Python4.png|thumb|left]]
 
<br clear=all>
 
<br clear=all>
  
==== La Partie console ====
+
==== The console section ====
C'est une partie très importante pour l'utilisateur du script et indispensable pour le 'codeur'.
+
This is a very important part for the user of the script and indispensable for the coder.
  
On peut y retrouver une indication de lancement du script (1) les informations liées à l'activation du script (Par exemple des informations souhaitées comme des quantités, ou subies comme des rapports d'erreurs)(2), et si le script a bien fini son travail (3).
+
You can find here an indication of the launch of the script (1), the information related to the activation of the script (for example, desired information such as quantities, or informations such as error reports)(2), and if the script has finished its work (3).
  
 
[[Fichier:Python5.png|thumb|left]]
 
[[Fichier:Python5.png|thumb|left]]
 
<br clear=all>
 
<br clear=all>
  
=== Comment créer/modifier un script? ===
+
=== How to create/modify a script? ===
 
+
For this, any text editor is needed (Notepad on PC for example). On Mac, you can double click on the script to open a dedicated code editor that gives you rudimentary tools to modify the script (see screenshot below), such as coloring according to the type, the number of the selected line, the possibility to "launch" the script.
Pour cela, tout éditeur de texte suffit (Bloc note sur PC par exemple). Sous Mac, on peut en double cliquant sur le script ouvrir un éditeur de code dédié qui donne des outils rudimentaires pour modifier le script (voir capture d'écran ci-dessous), comme la coloration selon le type, le numéro de la ligne sélectionnée, la possibilité de "lancer" le script.
 
  
 
[[Fichier:Python6.png|thumb|left]]
 
[[Fichier:Python6.png|thumb|left]]
 
<br clear=all>
 
<br clear=all>
  
Toutefois, il est recommandé de travailler sur un éditeur de code dédié.
+
However, it is recommended to work on a dedicated code editor.
Je vous recommande Visual Studio Code qui marche sur Mac et PC et qui possède une extension permettant de travailler aussi sur du GDL.
+
I recommend Visual Studio Code which works on Mac and PC (which has an extension allowing to work on GDL.)
Les avantages pour ce type d'outil sont nombreux.
+
The advantages of this type of tool are numerous.
  
 
[[Fichier:Python7.png|thumb|left]]
 
[[Fichier:Python7.png|thumb|left]]
 
<br clear=all>
 
<br clear=all>
  
Certains pour coder en général, d'autres spécifiques à la connexion python/archicad.
+
Some for coding in general, some specific to the python/archicad connection.
Par exemple:
+
For example:
* L'ensemble des lignes sont numérotés (les bugs indiquent souvent à quelle ligne le script a buggé, ce qui aide à le corriger),
+
* All lines are numbered (bugs often indicate which line the script bugged, which helps to fix it),
* Lors d'erreurs "grossières" (une parenthèse oubliée, un retour à la ligne manquant...), le logiciel alerte et aide à éviter les erreurs bêtes.
+
* In case of "big" errors (a forgotten parenthesis, a missing line break...), the software alerts and helps to avoid stupid mistakes.
* Après avoir installé le package dédié (https://pypi.org/project/archicad/#description), le logiciel reconnait l'ensemble des commandes disponibles, avec des informations complémentaires qui aident à les utiliser (sur les besoins de la commande, et ce qui résultera de l'utilisation de cette commande).
+
* After installing the dedicated package (https://pypi.org/project/archicad/#description), the software recognizes all the available commands, with additional information that helps to use them (on the needs of the command, and what will result from using this command).
  
 
[[Fichier:Python8.png|thumb|left]]
 
[[Fichier:Python8.png|thumb|left]]
 
<br clear=all>
 
<br clear=all>
 
+
For example, on Get2DBOundingBoxes, we learn that it is a command, that it needs the identifiers of the elements to be retrieved in the form ElementArrayItem and that it will give in return a list containing the 2D outlines of the elements or errors if there is none.
Par exemple, sur Get2DBOundingBoxes, on apprends que c'est une commande, qu'il lui faut les identifiants des éléments à récupérer sous la forme ElementArrayItem et qu'elle donnera en retour une liste contenant les contours 2D des éléments ou des erreurs s'il n'y en a pas.
 
  
  
 
=== HTTP & JSON ===
 
=== HTTP & JSON ===
  
Une des première chose à savoir, c'est que python n'agit pas directement sur archicad, mais passe via Http en utilisant des messages au format JSON (https://fr.wikipedia.org/wiki/JavaScript_Object_Notation) .
+
archicad, but passes via Http using messages in JSON format (https://fr.wikipedia.org/wiki/JavaScript_Object_Notation).
 
 
Graphisoft propose un package pour python qui "cache" la communication en JSON.
 
  
Par exemple, si on utilise la commande GetAllPropertyIds qui permet de récupérer l'ensemble des identifiant des propriétés d'un fichier archicad, il faudra écrire en python:
+
Graphisoft offers a package for python that "hides" the communication in JSON.
  
 +
For example, if you use the GetAllPropertyIds command which allows you to retrieve all the property identifiers of an archicad file, you will have to write in python:
 
<pre>
 
<pre>
 
acc.GetAllPropertyIds("UserDefined")
 
acc.GetAllPropertyIds("UserDefined")
 
</pre>
 
</pre>
  
Ce qui sera traduit par le "package" en JSON sous cette forme:
+
This will be translated by the "package" into JSON in this form:
  
 
<pre>
 
<pre>
Ligne 91 : Ligne 89 :
 
</pre>
 
</pre>
  
Et le résultat donnera quelque chose qui ressemblera à ça (une liste d'identifiant unique - Les GUID - correspondant pour chacun à une propriété d'archicad):
+
And the result will look like this (a list of unique identifiers - GUIDs - each corresponding to an archicad property):
  
 
<pre>
 
<pre>
Ligne 158 : Ligne 156 :
 
</pre>
 
</pre>
  
Le résultat peux paraitre un peu indigeste, mais cette forme de code en JSON permet de conserver une structure hiérarchique.
+
The result may look a bit cumbersome, but this form of JSON code allows to keep a hierarchical structure.
Par exemple si on copie colle la partie "résultat" et qu'on la colle dans un "viewer JSON" trouvable sur internet, les lignes de codes donnent çà:
+
For example, if you copy and paste the "result" part into a JSON viewer that you can find on the internet, the lines of code look like this:
  
 
[[Fichier:Python9.png|thumb|left]]
 
[[Fichier:Python9.png|thumb|left]]
 
<br clear=all>
 
<br clear=all>
  
Conclusion: les résultat qu'on reçoit peuvent apparaitre au premier abord peu clairs, mais on peut en extraire les données qui nous interessent!
+
Conclusion: the results we receive may seem unclear at first, but we can extract the data we are interested in!
De même, avant de donner des valeurs au script, il faut les "empaqueter" de manière adéquate.
+
Also, before giving values to the script, we have to "package" them properly.
  
==== Pourquoi ne pas avoir créé une passerelle directe sans utiliser JSON? ====
+
==== Why didn't they create a direct connection without using JSON? ====
  
Lors de la première bêta, la connexion se faisait directement par python, sans intermédiaire.
+
During the first beta, the connection was made via python, without any intermediary.
Le choix s'est finalement porté sur HTTP/JSON pour laisser l'opportunité de développer ultérieurement des passerelles avec n'importe quel langage informatique. Il "suffirait" de créer un nouvel package qui permet de produire du code en JSON.
+
The choice was finally made to use HTTP/JSON in order to leave the opportunity to develop bridges with any computer language later on. It would be "enough" to create a new package that allows to produce code in JSON.
  
== Comment apprendre python? ==
+
== How do I learn python? ==
Je n'ai pas un "gros niveau", j'ai essayé plusieurs fois de m'y mettre, et j'ai trouvé enfin une source assez efficace en anglais qui s’appelle ''Automate the Boring Stuff with Python''. C'est un livre (en anglais) qui a la particularité d'être disponible gratuitement et légalement sur un site internet : https://automatetheboringstuff.com/
+
I don't have a "high level", I tried several times to get into it, and I finally found a quite effective resource in English called ''Automate the Boring Stuff with Python''.  
 +
It's a book that has the particularity to be available for free and legally on a website : https://automatetheboringstuff.com/
  
Pour (re)créer le script sur le total des surfaces de zones, je n'ai eu besoin d'apprendre que finalement peu de concepts propre à python. Ci-dessous les chapitres que j'ai lu (et dont j'ai suivi les petits exercices).
+
Here are the chapters I read (and followed the small exercises)
Vous pouvez surement trouver de la documentation/tuto en Français, surtout depuis que Python peut être enseigné (une option si j'ai bien compris?) au Lycée.
+
=== The basics ===
 
 
=== Les basiques ===
 
 
https://automatetheboringstuff.com/2e/chapter1/
 
https://automatetheboringstuff.com/2e/chapter1/
  
* Les types de données (entiers, décimaux, chaîne ce qui donne en entier integers, Floating point numbers, strings)
+
* Data types (integers, floats, strings )
* La création et l'utilisation de variable en utilisant le signe =
+
* The creation and use of variables using the = sign
* La création de commentaires avec le symbole #
+
* The creation of comments with the # symbol
* Des fonctions importantes comme len() pour mesurer un nombre d'éléments et surtout la fonction print() qui va être la base de l'élaboration du script sous python. C'est la fonctions print() qui va permettre d'afficher des informations dans la console d'archicad
+
* Important functions like len() to measure a number of elements and especially the print() function which is going to be the basis of the script development under python. It's the print() function that will allow to display information in the archicad console
  
=== Les instructions conditionnelles ===
+
=== Conditional instructions ===
 
https://automatetheboringstuff.com/2e/chapter2/
 
https://automatetheboringstuff.com/2e/chapter2/
  
* Les opérateurs de comparaison, en particulier la différence entre == (vérification d'égalité) et = (attribution de valeur)
+
* Comparison operators, in particular the difference between == (equality check) and = (value assignment)
* Les différentes conditions de type "If" "else" "elif" "while" "break" les boucles basées sur "for"...
+
* The different conditions of type "If" "else" "elif" "while" "break" loops based on "for"...
* L'import de modules (des fonctions complémentaires à python) qu'il faut "appeler" pour pouvoir utiliser
+
* Import of modules (additional functions to python) that must be called.
  
=== Les fonctions ===
+
=== Functions ===
 
https://automatetheboringstuff.com/2e/chapter3/
 
https://automatetheboringstuff.com/2e/chapter3/
  
=== Les listes ===
+
=== Lists ===
 
https://automatetheboringstuff.com/2e/chapter4/
 
https://automatetheboringstuff.com/2e/chapter4/
Les listes sont une façon de stocker des données. Chaque donnée à un index et une valeur. Les index sont des entiers et la première valeur d'une liste a pour index 0 (et pas 1).
+
Lists are a way to store data. Each data has an index and a value. Indexes are integers and the first value of a list has index 0 (not 1).
  
Il faut apprendre comment récupérer une valeur à partir d'un (ou de plusieurs) index, l'ajout ou la suppression de valeurs dans cette liste.
+
You have to learn how to retrieve a value from one (or more) indexes, adding or deleting values in this list.
  
=== Les dictionnaires ===
+
=== Dictionnary ===
 
https://automatetheboringstuff.com/2e/chapter5/
 
https://automatetheboringstuff.com/2e/chapter5/
  
Les dictionnaires sont une autre façon de stocker des données. au lieu d'avoir index sous forme de nombre entier, chaque valeur est associée à une "clé". Cette clé peut être de n'importe quel type.
+
Dictionaries are another way of storing data. Instead of having indexes in integer form, each value is associated with a "key". This key can be of any type.
  
=== La modification des "chaines" ===
+
=== Strings modifications ===
 
https://automatetheboringstuff.com/2e/chapter6/
 
https://automatetheboringstuff.com/2e/chapter6/
  
== Ou en est la connexion python/archicad ==
+
== What is the status of the python/archicad connection ? ==
 
+
The possibilities are (still) limited.
Les possibilités sont (encore) limitées.
+
The archicad/python connection appeared in archicad 24, some functions appeared in 25 (access to bearer/non-bearer information; interior/exterior...) and in 26 (Possibility to retrieve the identifiers of the elements selected by the user...)
La connexion archicad/python est apparue en archicad 24, quelques fonctions sont apparues en 25 (accès aux informations porteur/non porteur; interieur/extérieur...) et en 26 (Possibilité de récupérer les identifiant des éléments sélectionnés par l'utilisateur, accès aux classifications des éléments...)
 
  
De manière générale, les utilisateurs de cette connexion trouvent que le développement de cette partie d'archicad est très lente.
+
In general, the users of this connection find that the development of this part of archicad is very slow.
Le développeur qui a mis en place cette connexion est partie depuis de chez Graphisoft.
 
  
Il y'a quand même un indice sur la poursuite du développement de ce côté, c'est la RoadMap présentée par graphisoft qui indique de l'automatisation pour 2025.
+
There is however a clue on the continuation of the development on this side, it is the RoadMap presented by Graphisoft which indicates automation for 2025.
  
 
[[Fichier:Python10.jpeg|thumb|left]]
 
[[Fichier:Python10.jpeg|thumb|left]]
 
<br clear=all>
 
<br clear=all>
  
=== Que peut-on faire exactement? ===
+
===What exactly can we do?===
  
Pour savoir ce qu'il est possible de faire, il faut regarder:
+
To know what is possible, you have to look at:
  
* le site dédié à l'interface JSON (voir précédent post) : https://archicadapi.graphisoft.com/JSONInterfaceDocumentation/#Introduction
+
* the site dedicated to the JSON interface : https://archicadapi.graphisoft.com/JSONInterfaceDocumentation/#Introduction
* le site dédié à l'"empaqueteur" python (voir précédent post) : https://archicadapi.graphisoft.com/archicadPythonPackage/archicad.html
+
* the site dedicated to the python "packer" : https://archicadapi.graphisoft.com/archicadPythonPackage/archicad.html
  
Le site pour JSON est un peu plus digeste et donne un bon aperçu.
+
The site for JSON is a bit more easily understandable and gives a good overview.
La majorité des commandes commencent par "Get" suivi d'un texte. Ce sont des commandes pour récupérer des informations. Par exemple récupérer le nom d'un calque, d'une propriété, la valeur de cette propriétén etc...
+
Most of the commands start with "Get" followed by a text. These are commands to get information. For example get the name of :
 +
a layer, a property, the value of this property etc...
  
Les commandes qui vont réellement agir dans archicad sont beaucoup moins nombreuses.
+
The commands that will really act in Archicad are much less numerous.
  
La majorité de ces commandes permettent de modifier les vues et les mises en pages:
+
The majority of these commands allow you to modify views and layouts:
  
 
<pre>
 
<pre>
Ligne 248 : Ligne 244 :
 
</pre>
 
</pre>
  
Et pour le reste, seulement deux commandes:
+
And for the rest, only two commands:
  
 
<pre>
 
<pre>
Ligne 255 : Ligne 251 :
 
</pre>
 
</pre>
  
L'une pour modifier des paramètres d'un élément archicad (propriété personnalisée ou paramètre intégré (BuiltIn) comme les calques...) l'autre (et seulement depuis archicad 26) les classification des éléments.
+
One to modify parameters of an archicad element (custom property or built-in parameter (BuiltIn) like layers...) the other is the classification of elements.
  
Ca reste peu!
+
It's not much!
  
 
=== Tapir ===
 
=== Tapir ===
 
https://www.archicad-api.com/
 
https://www.archicad-api.com/
  
Des utilisateur d'archicad ont décidé de développer en opensource un plugin permettant d'utiliser dans Grasshopper ( Outil du logiciel Rhinoceros) les possibilités offertes par le plugin python.
+
Some archicad users decided to develop an opensource plugin to use in Grasshopper (Rhinoceros software tool) the possibilities offered by the python plugin.
  
Pour augmenter les capacité de ce plugin, ils ont décidé d'améliorer le plugin python en offrant d'autres commandes au logiciel.
+
To increase the capabilities of this plugin, they decided to improve the python plugin by offering other commands to the software.
  
Par exemple, ils ont ajouté la possibilité de récupérer les informations projet (ce qui n'est pas possible dans la version de base).
+
For example, they added the possibility to retrieve project informations (which is not possible in the basic version).
  
Le développement se reposant sur des bénévole, ce n'est pas très rapide, mais il semblerait que pour des développeur s'y connaissant en C++, la possibilité de créer de nouvelles fonctionnalités ne soit pas très compliqué, et un ancien développeur de graphisoft a partagé un tutoriel à ce sujet dans le discord du projet.
+
Since the development is based on volunteers, it is not very fast, but it seems that for developers who know C++, the possibility to create new features is not very complicated, and a former developer of graphisoft shared a tutorial about it in the project discord.
  
== La suite... ==
+
== More... ==
[[Premier script en python, un exemple expliqué de A à Z]]
+
[[]]

Version du 28 février 2023 à 23:27

((tutorial originally written by MathiasJ on the Archi-cadlink forum and then re-formatted here).

Introduction

What is python?

It is a programming language particularly used for the automation of simple but tedious tasks. It was created in 1991 and is now at version 3.12 (date of the post). In general, we speak of version 3 for the current version. It is the one used for archicad.

To use python, you need to install it (voir le site officiel https://www.python.org/).

How to work with python in archicad?

  • Install the latest version of the python language on the official website (Latest version 3.XX)
  • Activate Python in the experimental options (Options > Working environment > Other options & check the box " Activate Python Palette")
  • Display the Python palette now available.
  • Follow the indications of the palette to finalize the installation.


How does the connection work?

The connection works by using the python palette.

This palette is composed of two parts: a part where you select your scripts (on top) and launch the desired script, and a part named "console" where the computer will give you information.

The script section

We select the folder icon and indicate where the scripts to be used are located. A button is used to delete the folder, and another one is used to update the list.

Python3.png


To launch a script, just select the chosen script (1), and click on launch (2). You can also double click on the script name to launch it.

Python4.png


The console section

This is a very important part for the user of the script and indispensable for the coder.

You can find here an indication of the launch of the script (1), the information related to the activation of the script (for example, desired information such as quantities, or informations such as error reports)(2), and if the script has finished its work (3).

Python5.png


How to create/modify a script?

For this, any text editor is needed (Notepad on PC for example). On Mac, you can double click on the script to open a dedicated code editor that gives you rudimentary tools to modify the script (see screenshot below), such as coloring according to the type, the number of the selected line, the possibility to "launch" the script.

Python6.png


However, it is recommended to work on a dedicated code editor. I recommend Visual Studio Code which works on Mac and PC (which has an extension allowing to work on GDL.) The advantages of this type of tool are numerous.

Python7.png


Some for coding in general, some specific to the python/archicad connection. For example:

  • All lines are numbered (bugs often indicate which line the script bugged, which helps to fix it),
  • In case of "big" errors (a forgotten parenthesis, a missing line break...), the software alerts and helps to avoid stupid mistakes.
  • After installing the dedicated package (https://pypi.org/project/archicad/#description), the software recognizes all the available commands, with additional information that helps to use them (on the needs of the command, and what will result from using this command).
Python8.png


For example, on Get2DBOundingBoxes, we learn that it is a command, that it needs the identifiers of the elements to be retrieved in the form ElementArrayItem and that it will give in return a list containing the 2D outlines of the elements or errors if there is none.


HTTP & JSON

archicad, but passes via Http using messages in JSON format (https://fr.wikipedia.org/wiki/JavaScript_Object_Notation).

Graphisoft offers a package for python that "hides" the communication in JSON.

For example, if you use the GetAllPropertyIds command which allows you to retrieve all the property identifiers of an archicad file, you will have to write in python:

acc.GetAllPropertyIds("UserDefined")

This will be translated by the "package" into JSON in this form:

{
    "command": "API.GetAllPropertyIds",
    "parameters": {
        "propertyType": "UserDefined"
    }
}

And the result will look like this (a list of unique identifiers - GUIDs - each corresponding to an archicad property):

{
    "succeeded": true,
    "result": {
        "propertyIds": [
            {
                "propertyId": {
                    "guid": "E480E81E-EDE3-43FC-9C52-B55A4CA1A85C"
                }
            },
            {
                "propertyId": {
                    "guid": "13A61253-66A9-4494-9393-9E8F2E19D55E"
                }
            },
            {
                "propertyId": {
                    "guid": "BCB5813F-2115-4B8B-A12F-16CFE37C7B7F"
                }
            },
            {
                "propertyId": {
                    "guid": "6F4A46AC-AE91-47E6-BF4A-9F9AB01A4986"
                }
            },
            {
                "propertyId": {
                    "guid": "F6F67733-1DC1-442A-8CF4-ACD2DF7E62C6"
                }
            },
            {
                "propertyId": {
                    "guid": "52D7923A-E5D7-47DF-9319-834B2CB68A6C"
                }
            },
            {
                "propertyId": {
                    "guid": "331D26A3-8168-460C-B7F5-0FA11B596B60"
                }
            },
            {
                "propertyId": {
                    "guid": "78B73923-1B87-460B-8D9E-6E3041CF38D6"
                }
            },
            {
                "propertyId": {
                    "guid": "2FAB57AB-40D6-4B7B-A7F7-31FAE42BCFBD"
                }
            },
            {
                "propertyId": {
                    "guid": "3D9EF415-8D5E-42C3-999F-3CE138DF341F"
                }
            },
            {
                "propertyId": {
                    "guid": "9CC16F4D-9754-B744-B3F8-20BA074A3B2D"
                }
            }
        ]
    }
}

The result may look a bit cumbersome, but this form of JSON code allows to keep a hierarchical structure. For example, if you copy and paste the "result" part into a JSON viewer that you can find on the internet, the lines of code look like this:

Python9.png


Conclusion: the results we receive may seem unclear at first, but we can extract the data we are interested in! Also, before giving values to the script, we have to "package" them properly.

Why didn't they create a direct connection without using JSON?

During the first beta, the connection was made via python, without any intermediary. The choice was finally made to use HTTP/JSON in order to leave the opportunity to develop bridges with any computer language later on. It would be "enough" to create a new package that allows to produce code in JSON.

How do I learn python?

I don't have a "high level", I tried several times to get into it, and I finally found a quite effective resource in English called Automate the Boring Stuff with Python. It's a book that has the particularity to be available for free and legally on a website : https://automatetheboringstuff.com/

Here are the chapters I read (and followed the small exercises)

The basics

https://automatetheboringstuff.com/2e/chapter1/

  • Data types (integers, floats, strings )
  • The creation and use of variables using the = sign
  • The creation of comments with the # symbol
  • Important functions like len() to measure a number of elements and especially the print() function which is going to be the basis of the script development under python. It's the print() function that will allow to display information in the archicad console

Conditional instructions

https://automatetheboringstuff.com/2e/chapter2/

  • Comparison operators, in particular the difference between == (equality check) and = (value assignment)
  • The different conditions of type "If" "else" "elif" "while" "break" loops based on "for"...
  • Import of modules (additional functions to python) that must be called.

Functions

https://automatetheboringstuff.com/2e/chapter3/

Lists

https://automatetheboringstuff.com/2e/chapter4/ Lists are a way to store data. Each data has an index and a value. Indexes are integers and the first value of a list has index 0 (not 1).

You have to learn how to retrieve a value from one (or more) indexes, adding or deleting values in this list.

Dictionnary

https://automatetheboringstuff.com/2e/chapter5/

Dictionaries are another way of storing data. Instead of having indexes in integer form, each value is associated with a "key". This key can be of any type.

Strings modifications

https://automatetheboringstuff.com/2e/chapter6/

What is the status of the python/archicad connection ?

The possibilities are (still) limited. The archicad/python connection appeared in archicad 24, some functions appeared in 25 (access to bearer/non-bearer information; interior/exterior...) and in 26 (Possibility to retrieve the identifiers of the elements selected by the user...)

In general, the users of this connection find that the development of this part of archicad is very slow.

There is however a clue on the continuation of the development on this side, it is the RoadMap presented by Graphisoft which indicates automation for 2025.

Python10.jpeg


What exactly can we do?

To know what is possible, you have to look at:

The site for JSON is a bit more easily understandable and gives a good overview. Most of the commands start with "Get" followed by a text. These are commands to get information. For example get the name of : a layer, a property, the value of this property etc...

The commands that will really act in Archicad are much less numerous.

The majority of these commands allow you to modify views and layouts:

DeleteNavigatorItems
RenameNavigatorItem
MoveNavigatorItem
CloneProjectMapItemToViewMap
CreateViewMapFolder
CreateLayoutSubset
CreateLayout
SetLayoutSettings

And for the rest, only two commands:

SetClassificationsOfElements
SetPropertyValuesOfElements

One to modify parameters of an archicad element (custom property or built-in parameter (BuiltIn) like layers...) the other is the classification of elements.

It's not much!

Tapir

https://www.archicad-api.com/

Some archicad users decided to develop an opensource plugin to use in Grasshopper (Rhinoceros software tool) the possibilities offered by the python plugin.

To increase the capabilities of this plugin, they decided to improve the python plugin by offering other commands to the software.

For example, they added the possibility to retrieve project informations (which is not possible in the basic version).

Since the development is based on volunteers, it is not very fast, but it seems that for developers who know C++, the possibility to create new features is not very complicated, and a former developer of graphisoft shared a tutorial about it in the project discord.

More...

[[]]