python
Inhaltsverzeichnis
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 installierenpip install(innerhalb venv): abhängigkeiten für ein projekt in einem venv installieren (abhängigkeiten stehen üblicherweise in einerrequirements.txtdatei)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)
- main.py
#!/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"
> 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):
- liste.py
#!/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]
- test.py
#!/usr/bin/python print 'hi' print 'hi' * 3 print 'hi' * 3 + 'ho' print 'hi' + 'ho'
> ./test.py hi hihihi hihihiho hiho
Argumente
- arguments.py
#!/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/arguments.py
#!/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
> vi rechnen.py
- 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
- fibonacci.py
#!/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)
- /home/bin/ersetzen_zeichen.py
#!/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
- /home/bin/ersetzen_dateiinhalt.py
#!/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
- /home/bin/greptest.py
#!/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
- /home/bin/cattest.py
#!/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/
- /home/bin/splittest.py
#!/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)
- server.py
#!/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())
- client.py
#!/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
- 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 <ubuntu-devel-discuss@lists.ubuntu.com> Original-Maintainer: Debian OpenStack <team+openstack@tracker.debian.org> 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
- mysql-test_no_tls.py
#!/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()
- mysql-test_+_tls.py
#!/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 - Einführung in Python 3: Für Ein- und Umsteiger
- ISBN-10: 3864904447 - Python Crashkurs: Eine praktische, projektbasierte Programmiereinführung
- ISBN-10: 3864904447 - Python 3: Das umfassende Handbuch: Sprachgrundlagen, Objektorientierung, Modularisierung
Links
siehe auch:
Videos
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()
/home/http/wiki/data/pages/python.txt · Zuletzt geändert: von david
