====== Python ======
1990: Python (1): 1990
2000: Python 2.0: 2000
2008: Python 3.0: 2008
2010: Python 2.7: 2010
2017: Instagram wechselte zu 100% auf Python 3.5
2020: seit 01. Jan. 2020 gibt es keinen Support für Python-2 mehr
===== venv =====
* es wird stark empfohlen, venv in python zu nutzen
* um pakete mit pip global zu installieren ist venv jedoch unpraktisch, dafür gibt es pipx, welches ein separates venv für das jeweilige paket managed, d.h.
* ''pipx install'': pakete installieren
* ''pip install'' (innerhalb venv): abhängigkeiten für ein projekt in einem venv installieren (abhängigkeiten stehen üblicherweise in einer ''requirements.txt'' datei)
* ''pip install'' (außerhalb venv): vermeiden wenn möglich
relevante python pakete in debian
sudo apt install python-is-python3 python3 python3-pip python3-venv pipx
paket mit pipx installieren
(black ist übrigens ein super python formatter, es ist sowas wie das gofmt von python)
pipx install black
venv erstellen
mkdir /tmp/python-venv-demo
cd /tmp/python-venv-demo
type python
python -m venv .venv
. .venv/bin/activate
type python
touch requirements.txt
pip install -r requirements.txt
python -c 'print("hello world")'
deactivate
type python
===== best practices =====
sicherstellen, dass der main code nur ausgeführt wird, wenn die datei als programm ausgeführt wird, nicht wenn sie als modul importiert wird (das macht der ''%%__name__ == "__main__"%%'' check)
#!/usr/bin/env python3
def main():
print("Hello World!")
if __name__ == "__main__":
main()
===== allgemeines =====
# lsb_release -d
Description: Ubuntu 18.04.4 LTS
# apt search python | egrep ^python[0-9][.][0-9][/]
python2.7/bionic-updates,now 2.7.17-1~18.04 amd64
python3.6/bionic-updates,now 3.6.9-1~18.04 amd64
python3.7/bionic-updates 3.7.5-2~18.04 amd64
python3.8/bionic-updates,now 3.8.0-3~18.04 amd64
# apt install python3.8/bionic-updates
# ls -lha /usr/bin/python /etc/alternatives/python
lrwxrwxrwx 1 root root 9 Apr 16 2018 /usr/bin/python -> python2.7
# update-alternatives --install /usr/bin/python python /usr/bin/python3.8 10
# ls -lha /usr/bin/python /etc/alternatives/python
lrwxrwxrwx 1 root root 18 Mär 12 18:19 /etc/alternatives/python -> /usr/bin/python3.8
lrwxrwxrwx 1 root root 24 Mär 12 18:19 /usr/bin/python -> /etc/alternatives/python
===== Die bekanntesten Unterschiede zwischen Python-2 und Python-3 =====
* Python 2
* "print" war noch ein Schlüsselwort
* print "Hallo Welt!"
* Python 3
* "print" ist jetzt eine Funktion
* print("Hallo Welt!")
* "range" verhält sich jetzt wie das "xrange" aus Python2
* "xrange" gibt es nicht mehr
* Exception wird jetzt ohne Komma geschrieben, statt dessen jetzt mit "as"
* Divisionen sind jetzt immer vom Type "float"
* Bibliotheken haben keine Großbuchstaben mehr
===== Beispiele =====
==== Equivalent zu "set -x" ====
* [[http://stackoverflow.com/questions/15760381/equivalent-for-set-x-in-python]]
> python -m trace -t your_script.py
==== als erstes ====
== Vergleich
= Zuweisung
> größer als
< kleiner als
// Division mit Rest - nur die ganze Zahl wird ausgegeben
% Division mit Rest - nur der "Rest" wird ausgegeben
** Potenz - "2**10" (1024) entspricht 2^10
[] Liste (ähnlich einem Array)
siehe [[https://www.tutorialspoint.com/python/python_variable_types.htm]] ganz unten
s = str(sys.argv[1])
print("String: %s" % s)
i = int(sys.argv[1])
print("Integer: %d" % s)
f = float(sys.argv[1])
print("Float: %f" % s)
r = repr(sys.argv[1])
print("String: %r" % r)
Beispiel zu Liste (Listen kann man auch in Listen haben):
#!/usr/bin/python
#
# Beispiel zu Liste
#
v = [1,2,3,4]
print v
print v[2]
v = v + [5]
print v
v = v + [8,13]
print v
v.append(42)
print v
> ./liste.py
[1, 2, 3, 4]
3
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 8, 13]
[1, 2, 3, 4, 5, 8, 13, 42]
#!/usr/bin/python
print 'hi'
print 'hi' * 3
print 'hi' * 3 + 'ho'
print 'hi' + 'ho'
> ./test.py
hi
hihihi
hihihiho
hiho
==== Print ====
=== Argumente ===
* [[http://www.python-kurs.eu/sys_modul.php]]
#!/usr/bin/python
import sys
print sys.argv
print "oder mit for-Schleife:"
for i in range(len(sys.argv)):
if i == 0:
print "Skriptname: %s" % sys.argv[0]
else:
print "%d. Argument: %s" % (i,sys.argv[i])
> python arguments.py ARG1 ARG2 ARG3
#!/usr/local/bin/python3.7
import sys
print(sys.argv)
print("oder mit for-Schleife:")
for i in range(len(sys.argv)):
if i == 0:
print("Skriptname: %s" % sys.argv[0])
else:
print("%d. Argument: %s" % (i,sys.argv[i]))
> /usr/local/bin/arguments.py ARG1 ARG2 ARG3
['/usr/local/bin/arguments.py', 'ARG1', 'ARG2', 'ARG3']
oder mit for-Schleife:
Skriptname: /usr/local/bin/arguments.py
1. Argument: ARG1
2. Argument: ARG2
3. Argument: ARG3
=== Rechnen ===
* [[http://docs.python.org/2/tutorial/inputoutput.html]]
> vi rechnen.py
#!/usr/bin/python
for x in range(1,11):
print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)
> python rechnen.py
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
#!/usr/bin/python
#
# Fibonacci - Reihe
#
y=0
z=1
for i in range(1,11):
x=y
y=z
z=x+y
print '{0:4d}'.format(z)
> ./fibonacci.py
1
2
3
5
8
13
21
34
55
89
==== suchen und ersetzen (SED) ====
#!/usr/bin/env python
#------------------------------------------------------------------------------#
#
# Dieses Skript ersetzt Zeichen in einer Zeichenkette
#
#------------------------------------------------------------------------------#
#
# https://lzone.de/examples/Python%20re.sub
#
# ersetzen
#
# ${0} [Zeichenkette] [suchen] [Ersatz]
#
# /home/bin/ersetzen_dateiinhalt.py Film.mpg .mpg e
#
#------------------------------------------------------------------------------#
import sys
import re
zeichenkette = sys.argv[1]
suchen = sys.argv[2]
ersatz = sys.argv[3]
ret = re.sub(suchen,ersatz, zeichenkette) # hier wird ersetzt
print ret
#!/usr/bin/env python
#------------------------------------------------------------------------------#
#
# Dieses Skript ersetzt Zeichen in einer Datei
#
#------------------------------------------------------------------------------#
#
# https://lzone.de/examples/Python%20re.sub
#
# ersetzen
#
# ${0} [Datei] [suchen] [Ersatz]
#
# echo "Film.mpg" > /tmp/test
# /home/bin/ersetzen_dateiinhalt.py /tmp/test .mpg e
#
#------------------------------------------------------------------------------#
import sys
import re
datei = sys.argv[1]
suchen = sys.argv[2]
ersatz = sys.argv[3]
with open (datei, "r") as myfile:
s=myfile.read()
ret = re.sub(suchen,ersatz, s) # hier wird ersetzt
print ret
==== GREP ====
#!/usr/bin/env python
import re
eingabe = "Apfel Birne Banane Kirsche Pflaume"
treffer = re.findall(r'.* Banane', eingabe)[0]
print treffer;
print "--------------------------------------"
treffer = re.search(r'Banane .*', eingabe)
print treffer.group();
> /home/bin/greptest.py
Apfel Birne Banane
--------------------------------------
Banane Kirsche Pflaume
==== CAT ====
#!/usr/bin/env python
# https://www.hdm-stuttgart.de/~maucher/Python/html/EingabeAusgabe.html
import sys
datei = sys.argv[1]
fin = open(datei, mode='r')
for line in fin:
#print line
sys.stdout.write(line)
fin.close()
==== SPLIT ====
[[https://www.mkyong.com/python/python-how-to-split-a-string/]]
#!/usr/bin/python
alphabet = "a b c d e f g"
data = alphabet.split() #split string into a list
for temp in data:
print temp
print "--------------------------------------"
data = alphabet.split(" ",0)
for temp in data:
print temp
print "--------------------------------------"
data = alphabet.split(" ",2)
for temp in data:
print temp
print "--------------------------------------"
data = alphabet.split(" ",-1)
for temp in data:
print temp
> /home/bin/splittest.py
a
b
c
d
e
f
g
--------------------------------------
a b c d e f g
--------------------------------------
a
b
c d e f g
--------------------------------------
a
b
c
d
e
f
g
==== UDP Socket communication (bind/connect) ====
#!/usr/bin/env python
from socket import socket, AF_INET, SOCK_DGRAM
# socket.AF_INET: IPv4
# socket.AF_INET6: IPv6
# socket.AF_UNIX: unix sockets
# socket.SOCK_DGRAM: datagram (UDP)
udp_socket = socket(AF_INET, SOCK_DGRAM)
# bind creates a server (listener)
# connect creates a client
udp_socket.bind(("127.0.0.1", 64512))
while True:
# reads up to 1024 Bytes
message, address = udp_socket.recvfrom(1024)
# decode() converts bytes[] to a String
print("Message from " + str(address) + " with text: " + message.decode())
#!/usr/bin/env python
from socket import socket, AF_INET, SOCK_DGRAM
# socket.AF_INET: IPv4
# socket.AF_INET6: IPv6
# socket.AF_UNIX: unix sockets
# socket.SOCK_DGRAM: datagram (UDP)
udp_socket = socket(AF_INET, SOCK_DGRAM)
# bind creates a server (listener)
# connect creates a client
udp_socket.connect(("127.0.0.1", 64512))
while True:
message = input("Enter message: ")
# encode() converts a String to bytes[]
udp_socket.send(message.encode())
===== MySQL =====
* [[https://github.com/PyMySQL/PyMySQL/|GitHub - PyMySQL]]
* [[https://pymysql.readthedocs.io/en/latest/modules/cursors.html|PyMySQL Cursor Objects]]
* [[https://codestory.de/11463/stellen-sie-mit-pymysql-eine-verbindung-zur-mysql-datenbank-in-python-her#1098461|Stellen Sie mit PyMySQL eine Verbindung zur MySQL-Datenbank in Python her]]
* Python-shebang (Linux/Ubuntu 22.04): ''#!/usr/bin/python3''
# apt show python3-pymysql
Package: python3-pymysql
Version: 1.0.2-1ubuntu1.22.04.1
Priority: optional
Section: python
Source: python-pymysql
Origin: Ubuntu
Maintainer: Ubuntu Developers
Original-Maintainer: Debian OpenStack
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Installed-Size: 170 kB
Depends: python3:any
Recommends: python3-cryptography
Suggests: python-pymysql-doc
Homepage: https://github.com/PyMySQL/PyMySQL/
Download-Size: 38.4 kB
APT-Sources: http://de.archive.ubuntu.com/ubuntu jammy-updates/main amd64 Packages
Description: Pure-Python MySQL Driver - Python 3.x
This package contains a pure-Python MySQL client library. The goal of PyMySQL
is to be a drop-in replacement for MySQLdb and work on CPython, PyPy,
IronPython and Jython.
.
This package contains the Python 3.x module.
> apt install python3-pymysql
#!/usr/bin/python3
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(
user='benutzer',
password='geheimes_PassWort',
host='192.168.3.146',
port=3306,
database='mysql',
connect_timeout=10,
autocommit='True',
cursorclass=pymysql.cursors.DictCursor
)
print ("connect successful!!")
try:
print ("================================================================================")
with connection.cursor() as cursor:
# SQL
sql = "SELECT Host,User,ssl_type,ssl_cipher,max_connections,max_user_connections,plugin,max_statement_time FROM user;"
# Den AbfragenBefehl implementieren (Execute Query).
cursor.execute(sql)
print ("cursor.description: ", cursor.description)
print()
for row in cursor:
print(row)
print ("================================================================================")
finally:
# Die Verbindung schließen (Close connection).
connection.close()
#!/usr/bin/python3
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(
user='benutzer',
password='geheimes_PassWort',
host='192.168.3.146',
port=3306,
database='mysql',
ssl={"fake_flag_to_enable_tls":True},
ssl_ca='/var/lib/mysql/ca.pem',
connect_timeout=10,
autocommit='True',
cursorclass=pymysql.cursors.DictCursor
)
print ("connect successful!!")
try:
print ("================================================================================")
with connection.cursor() as cursor:
# SQL-Variablen
sql = "SHOW VARIABLES LIKE '%ssl%';"
# Den AbfragenBefehl implementieren (Execute Query).
cursor.execute(sql)
print ("cursor.description: ", cursor.description)
print()
for row in cursor:
print(row)
print ("================================================================================")
with connection.cursor() as cursor:
# SQL-Status
sql = "SHOW STATUS LIKE '%ssl%';"
# Den AbfragenBefehl implementieren (Execute Query).
cursor.execute(sql)
print ("cursor.description: ", cursor.description)
print()
for row in cursor:
print(row)
print ("================================================================================")
finally:
# Die Verbindung schließen (Close connection).
connection.close()
===== Bücher =====
* ISBN-10: 3446452087 - [[https://www.amazon.de/dp/3446452087|Einführung in Python 3: Für Ein- und Umsteiger]]
* ISBN-10: 3864904447 - [[https://www.amazon.de/dp/3864904447|Python Crashkurs: Eine praktische, projektbasierte Programmiereinführung]]
* ISBN-10: 3864904447 - [[https://www.amazon.de/dp/3836258641|Python 3: Das umfassende Handbuch: Sprachgrundlagen, Objektorientierung, Modularisierung]]
===== Links =====
siehe auch:
* [[https://www.python-kurs.eu/|Python-Kurs]]
* [[https://www.tutorialspoint.com/python/|Python - Tutorial]]
* [[http://www.python-forum.de/|Das deutsche Python-Forum]]
* [[http://wiki.python.org/moin/SimplePrograms]]
* [[http://wiki.python.org/moin/BeginnersGuide/Examples]]
* [[http://wiki.python.org/moin/BeginnersGuide/Programmers?action=AttachFile&do=get&target=Tutorial.txt]]
* [[http://wiki.python.org/moin/BeginnersGuide/Programmers/SimpleExamples]]
===== Videos =====
* [[https://www.youtube.com/watch?v=mNcexeCI-G4&list=PLNmsVeXQZj7q0ao69AIogD94oBgp3E9Zs&index=2|Python Tutorial #2 - Zahlen]]
* [[http://weitz.de/haw-videos/]]
* [[https://www.youtube.com/watch?v=tZcYkeffmGs&list=PLb0zKSynM2PBYzz6l37rWH3B_n_7P40QP|Mathematik für Informatiker (mit Python)]]
* [[https://www.youtube.com/watch?v=BhtnlKOC-0s&feature=youtu.be&list=PLb0zKSynM2PBYzz6l37rWH3B_n_7P40QP|Funktionen, Kurven und Flächen visualisieren in Python und Jupyter]] (Grafen)
* [[https://www.youtube.com/watch?v=EmLzMYr6uHU|Nicht-euklidische Geometrien (Weihnachtsvorlesung 2017, Teil 3 von 4)]]
* [[https://www.youtube.com/watch?v=tZcYkeffmGs&list=PLb0zKSynM2PBYzz6l37rWH3B_n_7P40QP|Python: Variablen]]
* [[https://www.youtube.com/watch?v=5TzqfheD3rQ|Die Mandelbrotmenge]]
* [[https://www.youtube.com/watch?v=vWz5d6FZsbk|Ägyptische Brüche (und zwei ungelöste mathematische Probleme)]]
===== Raspberry Pi 5 =====
==== Pins schalten ====
//Das ist nur ein Code-Schnipsel, an dem zu erkennen ist, dass die Pin-Steuerung beim Pi 5 jetzt anders erfolgt als es beim Pi4 war.//
import os
from gpiozero import OutputDevice, PWMOutputDevice
class MotorController:
def __init__(self, ena_pin, in1_pin, in2_pin, enb_pin, in3_pin, in4_pin):
self.ENA = PWMOutputDevice(ena_pin)
self.IN1 = OutputDevice(in1_pin)
self.IN2 = OutputDevice(in2_pin)
self.ENB = PWMOutputDevice(enb_pin)
self.IN3 = OutputDevice(in3_pin)
self.IN4 = OutputDevice(in4_pin)
print("INIT OK")
def set_motor(self, motor, direction, speed):
"""
Motor steuern.
motor: 'A1', 'A2', 'B1' oder 'B2'
direction: 'forward' oder 'backward'
speed: Geschwindigkeit (0-1)
"""
if motor == 'A1':
self.ENA.value = speed
if direction == 'forward':
self.IN1.on()
self.IN2.off()
elif direction == 'backward':
self.IN1.off()
self.IN2.on()
elif motor == 'B1':
self.ENB.value = speed
if direction == 'forward':
self.IN3.on()
self.IN4.off()
elif direction == 'backward':
self.IN3.off()
self.IN4.on()
elif motor == 'A2':
self.ENA.value = speed
if direction == 'forward':
self.IN1.on()
self.IN2.off()
elif direction == 'backward':
self.IN1.off()
self.IN2.on()
elif motor == 'B2':
self.ENB.value = speed
if direction == 'forward':
self.IN3.on()
self.IN4.off()
elif direction == 'backward':
self.IN3.off()
self.IN4.on()
def stop_motor(self, motor):
"""
Motor stoppen.
motor: 'A1', 'A2', 'B1' oder 'B2'
"""
if motor == 'A1' or motor == 'A2':
self.ENA.value = 0
self.IN1.off()
self.IN2.off()
elif motor == 'B1' or motor == 'B2':
self.ENB.value = 0
self.IN3.off()
self.IN4.off()