Wprowadzenie do środowiska Python

From FreeCAD Documentation
Revision as of 12:18, 4 November 2023 by Kaktus (talk | contribs) (Created page with "Powoduje to błąd, {{incode|varA}} jest łańcuchem znaków, a {{incode|varB}} jest liczbą całkowitą i interpreter nie wie, co zrobić. Możemy jednak wymusić konwersję między typami:")

Wprowadzenie

To jest krótki poradnik dla osób, dla których Python jest całkowicie nowy. Python to wieloplatformowy język programowania o otwartym kodzie źródłowym. Ma kilka cech, które odróżniają go od innych języków programowania i jest bardzo przystępny dla nowych użytkowników:

  • Został zaprojektowany tak, aby był czytelny dla ludzi, dzięki czemu jest stosunkowo łatwy do nauczenia i zrozumienia.
  • Jest interpretowany, co oznacza, że programy nie muszą być kompilowane przed ich wykonaniem. Kod Pythona może być wykonywany natychmiast, nawet linijka po linijce, jeśli chcesz.
  • Może być osadzony w innych programach jako język skryptowy. FreeCAD posiada wbudowany interpreter Python. Możesz pisać kod Python, aby manipulować częściami FreeCAD. Jest to bardzo potężne, oznacza to, że można budować własne narzędzia.
  • Jest rozszerzalny, można łatwo podłączyć nowe moduły do instalacji Python i rozszerzyć jego funkcjonalność. Na przykład istnieją moduły, które pozwalają środowisku Pyton odczytywać i zapisywać obrazy, komunikować się z Twitterem, planować zadania do wykonania przez system operacyjny itp.

Poniższa instrukcja jest bardzo podstawowym wprowadzeniem i w żadnym wypadku nie jest kompletnym poradnikiem. Mamy jednak nadzieję, że będzie to dobry punkt wyjścia do dalszej eksploracji FreeCAD i jego mechanizmów. Zdecydowanie zachęcamy do wprowadzenia poniższych fragmentów kodu do interpretera Python.

Interpreter

Zwykle, gdy piszesz programy komputerowe, po prostu otwierasz edytor tekstu i lub środowisko programistyczne (które w większości przypadków zawiera edytor tekstu z kilkoma dodatkowymi narzędziami), wpisujesz swój program, następnie kompilujesz go i wykonujesz. Przez większość czasu robisz błędy podczas pisania, więc twój program nie działa. Otrzymujesz komunikat błędu mówiący co poszło źle. Potem wracasz do edytora tekstu, poprawiasz błędy, uruchamiasz ponownie, aż program zacznie działać prawidłowo.

W środowisku Python cały ten proces można wykonać w sposób przezroczysty wewnątrz interpretera Python. Interpreter to okno z wierszem poleceń, w którym można po prostu wpisać kod. Jeśli zainstalowałeś Python na swoim komputerze (pobierz go ze strony Python, jeśli korzystasz z systemu Windows lub Mac, zainstaluj go z repozytorium pakietów jeśli korzystasz z systemu GNU/Linux), będziesz miał interpreter Python w menu startowym. Ale, jak już wspomniano, FreeCAD ma również wbudowany interpreter: konsola Python.

Konsola Python programu FreeCAD

Jeśli jej nie widzisz, kliknij Widok → Panele → Konsola Python. Rozmiar konsoli Python można zmienić, a także ją odblokować.

Interpreter pokazuje wersję Python, a następnie symbol >>, który jest znakiem zachęty. Pisanie kodu w interpreterze jest proste: jedna linia to jedna instrukcja. Po naciśnięciu Enter, linia kodu zostanie wykonana (po natychmiastowej i niewidocznej kompilacji). Na przykład, spróbuj napisać to:

print("hello")

print() to polecenie Python, które oczywiście wypisuje coś na ekranie. Po naciśnięciu Enter, operacja jest wykonywana, a wiadomość "hello" jest drukowana. Jeśli popełnimy błąd, na przykład napiszemy:

print(hello)

Python natychmiast ci to powie. W tym przypadku Python nie wie, czym jest hello. Znaki " " określają, że zawartość jest ciągiem znaków, programistycznym żargonem dla fragmentu tekstu. Bez nich polecenie print() nie rozpoznaje hello. Naciskając strzałkę w górę można wrócić do ostatniej linii kodu i poprawić ją.

Interpreter Python posiada również wbudowany system pomocy. Powiedzmy, że nie rozumiemy, co poszło nie tak z print(hello) i chcemy uzyskać szczegółowe informacje o poleceniu:

help("print")

Otrzymasz długi i kompletny opis wszystkiego, co może zrobić polecenie print().

Teraz, gdy rozumiesz już interpreter Python, możemy przejść do poważniejszych rzeczy.

Przewiń na górę strony

Zmienne

W programowaniu bardzo często zachodzi potrzeba przechowywania wartości pod nazwą. W tym miejscu pojawiają się zmienne. Na przykład, wpisz to:

a = "hello"
print(a)

Prawdopodobnie rozumiesz co się tutaj stało, zapisaliśmy ciąg "hello" pod nazwą a. Teraz, gdy a jest znany, możemy go użyć gdziekolwiek, na przykład w poleceniu print(). Możemy użyć dowolnej nazwy, musimy tylko przestrzegać kilku prostych zasad, takich jak nieużywanie spacji lub znaków interpunkcyjnych i nieużywanie słów kluczowych Python. Na przykład, możemy napisać:

hello = "my own version of hello"
print(hello)

Teraz hello nie jest już niezdefiniowane. Zmienne mogą być modyfikowane w dowolnym momencie, dlatego są nazywane zmiennymi, ich zawartość może się zmieniać. Na przykład:

myVariable = "hello"
print(myVariable)
myVariable = "good bye"
print(myVariable)

Zmieniliśmy wartość myVariable. Możemy również kopiować zmienne:

var1 = "hello"
var2 = var1
print(var2)

Zaleca się nadawanie zmiennym znaczących nazw. Po pewnym czasie nie będziesz pamiętać, co reprezentuje zmienna o nazwie a. Ale jeśli nazwiesz ją na przykład myWelcomeMessage, łatwo zapamiętasz jej przeznaczenie. Dodatkowo, twój kod jest o krok bliżej do bycia samodokumentującym się.

Wielkość liter jest bardzo ważna, myVariable nie jest tym samym co myvariable. Gdybyś wpisał print(myvariable), zwróciłoby to błąd jako niezdefiniowany.

Przewiń na górę strony

Liczby

Oczywiście programy w Python mogą obsługiwać wszystkie rodzaje danych, nie tylko ciągi tekstowe. Jedna rzecz jest ważna, Python musi wiedzieć z jakim rodzajem danych ma do czynienia. W naszym przykładzie print hello widzieliśmy, że polecenie print() rozpoznało nasz ciąg "hello". Używając znaków " ", określiliśmy, że to, co następuje, jest ciągiem tekstowym.

Zawsze możemy sprawdzić typ danych zmiennej za pomocą polecenia type():

myVar = "hello"
type(myVar)

Poinformuje nas, że zawartość myVar to 'str', co jest skrótem od string. Mamy również inne podstawowe typy danych, takie jak liczby całkowite i zmiennoprzecinkowe:

firstNumber = 10
secondNumber = 20
print(firstNumber + secondNumber)
type(firstNumber)

Python wie, że 10 i 20 są liczbami całkowitymi, więc są one przechowywane jako 'int', a Python może zrobić z nimi wszystko, co może zrobić z liczbami całkowitymi. Spójrz na wyniki tego działania:

firstNumber = "10"
secondNumber = "20"
print(firstNumber + secondNumber)

Tutaj zmusiliśmy Pythona do wzięcia pod uwagę, że nasze dwie zmienne nie są liczbami, ale fragmentami tekstu. Python może dodać do siebie dwa fragmenty tekstu, choć w takim przypadku oczywiście nie wykona żadnych działań arytmetycznych. Ale mówiliśmy o liczbach całkowitych. Istnieją również liczby zmiennoprzecinkowe. Różnica polega na tym, że liczby zmiennoprzecinkowe mogą mieć część dziesiętną, a liczby całkowite nie:

var1 = 13
var2 = 15.65
print("var1 is of type ", type(var1))
print("var2 is of type ", type(var2))

Liczby całkowite i zmiennoprzecinkowe mogą być mieszane bez problemów:

total = var1 + var2
print(total)
print(type(total))

Ponieważ var2 jest liczbą zmiennoprzecinkową, interpreter automatycznie decyduje, że wynik również musi być liczbą zmiennoprzecinkową. Istnieją jednak przypadki, w których interpreter nie wie, jakiego typu użyć. Na przykład:

varA = "hello 123"
varB = 456
print(varA + varB)

Powoduje to błąd, varA jest łańcuchem znaków, a varB jest liczbą całkowitą i interpreter nie wie, co zrobić. Możemy jednak wymusić konwersję między typami:

varA = "hello"
varB = 123
print(varA + str(varB))

Now that both variables are strings the operation works. Note that we "stringified" varB at the time of printing, but we didn't change varB itself. If we wanted to turn varB permanently into a string, we would need to do this:

varB = str(varB)

We can also use int() and float() to convert to integer and float if we want:

varA = "123"
print(int(varA))
print(float(varA))

Pewnie zauważyłeś, że użyliśmy polecenia print() na kilka sposobów. Drukowaliśmy zmienne, sumy, kilka rzeczy oddzielonych przecinkami, a nawet wynik innego polecenia z języka Python. Być może zauważyłeś również, że te dwa polecenia:

type(varA)
print(type(varA))

daje ten sam wynik. Dzieje się tak, ponieważ jesteśmy w interpreterze i wszystko jest automatycznie drukowane. Kiedy piszemy bardziej złożone programy, które działają poza interpreterem, nie będą one drukowane automatycznie, więc będziemy musieli użyć polecenia print(). Mając to na uwadze, przestańmy go tutaj używać. Od teraz będziemy po prostu pisać:

myVar = "hello friends"
myVar

Przewiń na górę strony

Lists

Another useful data type is a list. A list is a collection of other data. To define a list we use [ ]:

myList = [1, 2, 3]
type(myList)
myOtherList = ["Bart", "Frank", "Bob"]
myMixedList = ["hello", 345, 34.567]

As you can see a list can contain any type of data. You can do many things with a list. For example, count its items:

len(myOtherList)

Or retrieve one item:

myName = myOtherList[0]
myFriendsName = myOtherList[1]

While the len() command returns the total number of items in a list, the first item in a list is always at position 0, so in our myOtherList "Bob" will be at position 2. We can do much more with lists such as sorting items and removing or adding items.

Interestingly a text string is very similar to a list of characters in Python. Try doing this:

myvar = "hello"
len(myvar)
myvar[2]

Usually what you can do with lists can also be done with strings. In fact both lists and strings are sequences.

Apart from strings, integers, floats and lists, there are more built-in data types, such as dictionaries, and you can even create your own data types with classes.

Przewiń na górę strony

Indentation

One important use of lists is the ability to "browse" through them and do something with each item. For example look at this:

alldaltons = ["Joe", "William", "Jack", "Averell"]
for dalton in alldaltons:
    print(dalton + " Dalton")

We iterated (programming jargon) through our list with the for in command and did something with each of the items. Note the special syntax: the for command terminates with : indicating the following will be a block of one of more commands. In the interpreter, immediately after you enter the command line ending with :, the command prompt will change to ... which means Python knows that there is more to come.

How will Python know how many of the next lines will need to be executed inside the for in operation? For that, Python relies on indentation. The next lines must begin with a blank space, or several blank spaces, or a tab, or several tabs. And as long as the indentation stays the same the lines will be considered part of the for in block. If you begin one line with 2 spaces and the next one with 4, there will be an error. When you have finished, just write another line without indentation, or press Enter to come back from the for in block

Indentation also aids in program readability. If you use large indentations (for example use tabs instead of spaces) when you write a big program, you'll have a clear view of what is executed inside what. We'll see that other commands use indented blocks of code as well.

The for in command can be used for many things that must be done more than once. It can, for example, be combined with the range() command:

serie = range(1, 11)
total = 0
print("sum")
for number in serie:
    print(number)
    total = total + number
print("----")
print(total)

If you have been running the code examples in an interpreter by copy-pasting, you will find the previous block of text will throw an error. Instead, copy to the end of the indented block, i.e. the end of the line total = total + number and then paste in the interpreter. In the interpreter press Enter until the three dot prompt disappears and the code runs. Then copy the final two lines followed by another Enter. The final answer should appear.

If you type into the interpreter help(range) you will see:

range(...)
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers

Here the square brackets denote an optional parameter. However all are expected to be integers. Below we will force the step parameter to be an integer using int():

number = 1000
for i in range(0, 180 * number, int(0.5 * number)):
    print(float(i) / number)

Another range() example:

alldaltons = ["Joe", "William", "Jack", "Averell"]
for n in range(4):
    print(alldaltons[n], " is Dalton number ", n)

The range() command also has that strange particularity that it begins with 0 (if you don't specify the starting number) and that its last number will be one less than the ending number you specify. That is, of course, so it works well with other Python commands. For example:

alldaltons = ["Joe", "William", "Jack", "Averell"]
total = len(alldaltons)
for n in range(total):
    print(alldaltons[n])

Another interesting use of indented blocks is with the if command. This command executes a code block only if a certain condition is met, for example:

alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Joe" in alldaltons:
    print("We found that Dalton!!!")

Of course this will always print the sentence, but try replacing the second line with:

if "Lucky" in alldaltons:

Then nothing is printed. We can also specify an else statement:

alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Lucky" in alldaltons:
    print("We found that Dalton!!!")
else:
    print("Such Dalton doesn't exist!")

Przewiń na górę strony

Functions

There are very few standard Python commands and we already know several of them. But you can create your own commands. In fact, most of the additional modules that you can plug into your Python installation do just that, they add commands that you can use. A custom command in Python is called a function and is made like this:

def printsqm(myValue):
    print(str(myValue) + " square meters")

printsqm(45)

The def() command defines a new function, you give it a name, and inside the parenthesis you define the arguments that the function will use. Arguments are data that will be passed to the function. For example, look at the len() command. If you just write len(), Python will tell you it needs an argument. Which is obvious: you want to know the length of something. If you write len(myList) then myList is the argument that you pass to the len() function. And the len() function is defined in such a way that it knows what to do with this argument. We have done the same thing with our printsqm function.

The myValue name can be anything, and it will only be used inside the function. It is just a name you give to the argument so you can do something with it. By defining arguments you also to tell the function how many to expect. For example, if you do this:

printsqm(45, 34)

there will be an error. Our function was programmed to receive just one argument, but it received two, 45 and 34. Let's try another example:

def sum(val1, val2):
    total = val1 + val2
    return total

myTotal = sum(45, 34)

Here we made a function that receives two arguments, sums them, and returns that value. Returning something is very useful, because we can do something with the result, such as store it in the myTotal variable.

Przewiń na górę strony

Modules

Now that you have a good idea of how Python works, you will need to know one more thing: How to work with files and modules.

Until now, we have written Python instructions line by line in the interpreter. This method is obviously not suitable for larger programs. Normally the code for Python programs is stored in files with the .py extension. Which are just plain text files and any text editor (Linux gedit, emacs, vi or even Windows Notepad) can be used to create and edit them.

There are several of ways to execute a Python program. In Windows, simply right-click your file, open it with Python, and execute it. But you can also execute it from the Python interpreter itself. For this, the interpreter must know where your program is. In FreeCAD the easiest way is to place your program in a folder that FreeCAD's Python interpreter knows by default, such as FreeCAD's user Mod folder:

  • On Linux it is usually /home/<username>/.local/share/FreeCAD/Mod/ (version 0.20 and above) or /home/<username>/.FreeCAD/Mod/ (version 0.19 and below).
  • On Windows it is %APPDATA%\FreeCAD\Mod\, which is usually C:\Users\<username>\Appdata\Roaming\FreeCAD\Mod\.
  • On macOS it is usually /Users/<username>/Library/Application Support/FreeCAD/Mod/.

Let's add a subfolder there called scripts and then write a file like this:

def sum(a,b):
    return a + b

print("myTest.py succesfully loaded")

Save the file as myTest.py in the scripts folder, and in the interpreter window write:

import myTest

without the .py extension. This will execute the contents of the file, line by line, just as if we had written it in the interpreter. The sum function will be created, and the message will be printed. Files containing functions, like ours, are called modules.

When we write a sum() function in the interpreter, we execute it like this:

sum(14, 45)

But when we import a module containing a sum() function the syntax is a bit different:

myTest.sum(14, 45)

That is, the module is imported as a "container", and all its functions are inside that container. This is very useful, because we can import a lot of modules, and keep everything well organized. Basically when you see something.somethingElse, with a dot in between, then this means somethingElse is inside something.

We can also import our sum() function directly into the main interpreter space:

from myTest import *
sum(12, 54)

Almost all modules do that: they define functions, new data types and classes that you can use in the interpreter or in your own Python modules, because nothing prevents you from importing other modules inside your module!

How do we know what modules we have, what functions are inside and how to use them (that is, what kind of arguments they need)? We have already seen that Python has a help() function. Doing:

help("modules")

will give us a list of all available modules. We can import any of them and browse their content with the dir() command:

import math
dir(math)

We'll see all the functions contained in the math module, as well as strange stuff named __doc__, __file__, __name__. Every function in a well made module has a __doc__ that explains how to use it. For example, we see that there is a sin() function inside the math module. Want to know how to use it?

print(math.sin.__doc__)

It may not be evident, but on either side of doc are two underscore characters.

And finally one last tip: When working on new or existing code, it is better to not use the FreeCAD macro file extension, .FCMacro, but instead use the standard .py extension. This is because Python doesn't recognize the .FCMacro extension. If you use .py your code can be easily loaded with import, as we have already seen, and also reloaded with importlib.reload():

import importlib
importlib.reload(myTest)

Istnieje jednak alternatywa:

exec(open("C:/PathToMyMacro/myMacro.FCMacro").read())

Przewiń na górę strony

Rozpoczęcie pracy z FreeCAD

Mamy nadzieję, że masz teraz wyobrażenie o tym, jak działa Python i możesz zacząć odkrywać, co FreeCAD ma do zaoferowania. Wszystkie funkcje Python FreeCAD są dobrze zorganizowane w różnych modułach. Niektóre z nich są już załadowane (zaimportowane) podczas uruchamiania FreeCAD. Wystarczy spróbować:

dir()

Przewiń na górę strony

Uwagi

  • FreeCAD został pierwotnie zaprojektowany do pracy ze środowiskiem Python 2. Ponieważ Python 2 osiągnął koniec swojego życia w 2020 r., przyszły rozwój FreeCAD będzie odbywał się wyłącznie w Pythonie 3, a kompatybilność wsteczna nie będzie obsługiwana.
  • Znacznie więcej informacji na temat Pythona można znaleźć w oficjalnym przewodniku po Pythonie i oficjalnym dokumencie referencyjnym Python.

Przewiń na górę strony