commit message from python script

This commit is contained in:
2023-04-11 17:21:48 +02:00
parent 5eb0811319
commit c0ae9cc93d
184 changed files with 3725 additions and 31 deletions

0
Dienstag/User_modify.py Normal file → Executable file
View File

0
Dienstag/func.py Normal file → Executable file
View File

0
Dienstag/func_summe.py Normal file → Executable file
View File

0
Dienstag/nutzer.py Normal file → Executable file
View File

0
Dienstag/zahlen.py Normal file → Executable file
View File

0
Donnerstag/__pycache__/decorators.cpython-39.pyc Normal file → Executable file
View File

0
Donnerstag/__pycache__/vectors.cpython-39.pyc Normal file → Executable file
View File

0
Donnerstag/check_zip.py Normal file → Executable file
View File

0
Donnerstag/curry.py Normal file → Executable file
View File

0
Donnerstag/decorators.py Normal file → Executable file
View File

0
Donnerstag/fakultät.py Normal file → Executable file
View File

0
Donnerstag/fibonacci.py Normal file → Executable file
View File

0
Donnerstag/taxi.py Normal file → Executable file
View File

0
Donnerstag/temp_var.py Normal file → Executable file
View File

0
Donnerstag/v_calc.py Normal file → Executable file
View File

0
Donnerstag/vectors.py Normal file → Executable file
View File

0
Freitag/__pycache__/decorators.cpython-39.pyc Normal file → Executable file
View File

0
Freitag/__pycache__/mathematik.cpython-39.pyc Normal file → Executable file
View File

0
Freitag/__pycache__/utilities.cpython-39.pyc Normal file → Executable file
View File

0
Freitag/check_env.py Normal file → Executable file
View File

0
Freitag/db_con.py Normal file → Executable file
View File

0
Freitag/db_select.py Normal file → Executable file
View File

0
Freitag/decorators.py Normal file → Executable file
View File

0
Freitag/ext_ip.py Normal file → Executable file
View File

0
Freitag/fakultät.py Normal file → Executable file
View File

0
Freitag/fibonacci.py Normal file → Executable file
View File

0
Freitag/insert_all.py Normal file → Executable file
View File

0
Freitag/mathematik.py Normal file → Executable file
View File

0
Freitag/test_fak.py Normal file → Executable file
View File

0
Freitag/utilities.py Normal file → Executable file
View File

View File

@@ -0,0 +1,8 @@
#! /usr/bin/env python3
def myprint():
print("Ausgabe aus einer Funktion")
print("-" * 30)
myprint()

View File

@@ -0,0 +1,8 @@
#! /usr/bin/env python3
def myprint(text, amount):
print(text)
print("-" * amount)
myprint("Ausgabe aus Funktion", 25)

View File

@@ -0,0 +1,11 @@
#! /usr/bin/env python3
def myprint(text: str, amount: int, greeting):
print(greeting)
print(text)
print("-" * amount)
greeting = "Moin"
myprint("Ausgabe aus Funktion", 25, greeting)

View File

@@ -0,0 +1,16 @@
#! /usr/bin/env python3
def myprint(text: str, amount: int):
global greeting
print(greeting)
print(text)
print("-" * amount)
# ACHTUNG: Hier wird globale Variable ueberschrieben
greeting = "Hallo"
greeting = "Moin"
myprint("Ausgabe aus Funktion", 25)
print(greeting)

View File

@@ -0,0 +1,21 @@
#! /usr/bin/env python3
def myprint(text: "Text der Ausgabe", amount: int = 10, greeting: str ="Hallo"):
print(greeting)
print(text)
print("-" * amount)
def connect(host='localhost', port='80', proto='tcp'):
pass
greeting = "Moin"
myprint("Ausgabe aus Funktion", 25, greeting)
myprint("Ausgabe aus Funktion", 25)
myprint("Ausgabe aus Funktion")
myprint("Ausgabe aus Funktion", 10, "Moin")
myprint("Ausgabe aus Funktion", greeting="Moin")
# Parameter als Keyword Argument
myprint(greeting="Moin", text="Ausgabe aus Funktion")

View File

@@ -0,0 +1,13 @@
#! /usr/bin/env python3
def summe(a: int, b: int, c=0, d=None) -> int:
result = a + b + c
if d is not None:
result += d
return result
print("1. Summe:", summe(1, 2))
print("2. Summe:", summe(1, 2, 3, 4))

View File

@@ -0,0 +1,21 @@
#! /usr/bin/env python3
def summe(values: 'List of ints') -> int:
# Um den Seiteneffekt zu verhindern
# values = values.copy()
result = 0
while len(values):
result += values.pop()
return result
#print("1. Summe:", summe(1, 2))
#print("2. Summe:", summe(1, 2, 3, 4))
print("1. Summe:", summe([1, 2]))
print("2. Summe:", summe([1, 2, 3, 4]))
mylist = [1, 1, 2, 3, 5]
print("3. Summe:", summe(mylist))
print(mylist)

View File

@@ -0,0 +1,19 @@
#! /usr/bin/env python3
def summe(values: 'List of ints') -> int:
result = 0
for v in values:
result += v
return result
#print("1. Summe:", summe(1, 2))
#print("2. Summe:", summe(1, 2, 3, 4))
print("1. Summe:", summe([1, 2]))
print("2. Summe:", summe([1, 2, 3, 4]))
mylist = [1, 1, 2, 3, 5]
print("3. Summe:", summe(mylist))
print(mylist)

View File

@@ -0,0 +1,20 @@
#! /usr/bin/env python3
# *values sammelt alle weiteren Positionsparameter in einem Tupel auf
def summe(a, b, *values: 'List of ints') -> int:
result = a + b
for v in values:
result += v
return result
print("1. Summe:", summe(1, 2))
print("2. Summe:", summe(1, 2, 3, 4))
mylist = [1, 1, 2, 3, 5]
# *mylist konvertiert hier die Werte in eine Liste von Positionsparametern
print("3. Summe:", summe(*mylist))
print(mylist)
# print("4. Summe:", summe(*range(10)))

View File

@@ -0,0 +1,22 @@
#! /usr/bin/env python3
# *values sammelt alle weiteren Positionsparameter in einem Tupel auf
def summe(a, b, *values: 'List of ints', default=0) -> int:
result = default
result += a + b
for v in values:
result += v
return result
print("1. Summe:", summe(1, 2))
print("2. Summe:", summe(1, 2, 3, 4))
mylist = [1, 1, 2, 3, 5]
# *mylist konvertiert hier die Werte in eine Liste von Positionsparametern
print("3. Summe:", summe(*mylist))
print(mylist)
# print("4. Summe:", summe(*range(10)))
print("5. Summe:", summe(*mylist, default=100))

View File

@@ -0,0 +1,33 @@
#! /usr/bin/env python3
# *values sammelt alle weiteren Positionsparameter in einem Tupel auf
# **kwargs sammelst alle weiteren Keyword Arguments als Dictionary auf
def summe(a, b, *values: 'List of ints', default=0, **kwargs) -> int:
result = default
result += a + b
for v in values:
result += v
# 1. Variante: Alle kwargs in Iteration verarbeiten
#for key, value in kwargs:
# pass
# 2. Variante: Einzelne Werte in kwargs selbst verarbeiten
#if 'city' in kwargs:
# print("Hier in", kwargs['city'])
# 3. Variante: kwargs blind an tieferliegende Funktion weitergeben
# conn = lower.connect(p1, p2, p3, host='localhost', **kwargs)
return result
print("1. Summe:", summe(1, 2))
print("2. Summe:", summe(1, 2, 3, 4))
mylist = [1, 1, 2, 3, 5]
# *mylist konvertiert hier die Werte in eine Liste von Positionsparametern
print("3. Summe:", summe(*mylist))
print(mylist)
# print("4. Summe:", summe(*range(10)))
print("5. Summe:", summe(*mylist, default=100))
print("6. Summe:", summe(*mylist, default=100, city="Essen", foo="bar"))

View File

@@ -0,0 +1,17 @@
#! /usr/bin/env python3
def kubik(n):
return n ** 3
def kugelvolumen(r):
pi = 3.1415
volumen = 4/3 * pi * r ** 3
return volumen
calc = kugelvolumen
kugelvolumen = kubik
print(kugelvolumen(2))
kugelvolumen = None
print(calc(2))

View File

@@ -0,0 +1,16 @@
#! /usr/bin/env python3
def kubik(n):
return n ** 3
def kugelvolumen(r):
pi = 3.1415
volumen = 4/3 * pi * r ** 3
return volumen
funclist = [kubik, kugelvolumen]
print(funclist[0](2))
print(funclist[1](2))

View File

@@ -0,0 +1,13 @@
#! /usr/bin/env python3
usernames = ['nutzer14',
'sshd',
'Debian-gdm',
'debian-tor',
'GeoClue',
'Root',
'bin'
]
for user in sorted(usernames, key=(lambda s: s.lower())):
print(user)

View File

@@ -0,0 +1,61 @@
#! /usr/bin/env python3
def read_file(path: str) -> "List of lines":
f = open(path, 'r')
# f.read(buflen) - binary read
# f.readline() - 1 Textzeile lesen -> str
# f.readlines() - alle Textzeilen lesen -> list
# f ist gleichzeitig Iterator
# 1. Variante: explizite for-Schleife
lines = []
for line in f.readlines():
lines.append(line.rstrip())
# 2. Variante: Mit Hilfe von Lambda und f als Iterator
#lines = list(map(lambda s: s.rstrip(), f))
# 3. Variante: Klassenfunktion rstrip und f als Iterator
#lines = list(map(str.rstrip, f))
# 4. Variante: Mit List Comprehension und f als Iterator
#lines = [line.rstrip() for line in f]
f.close()
print(lines)
def parse_passwd_line(line: str) -> "Dict of passwd details":
pass
def build_userlist(lines) -> "List of user dicts":
pass
def print_userlist_sorted_by_username(userlist):
pass
def print_userlist_sorted_by_uid(userlist):
pass
def main():
# Dictionary mit Ausgabe-Funktionen als Referenz
output_functions = {
'username': print_userlist_sorted_by_username,
'uid': print_userlist_sorted_by_uid,
}
# Zum Test diese spezielle Ausgabe-Funktion verwenden
# 'username' kommt spaeter von der Kommandozeile
outfunc = output_functions['username']
lines = read_file("/etc/passwd")
userlist = build_userlist(lines)
outfunc(userlist)
main()

View File

@@ -0,0 +1,78 @@
#! /usr/bin/env python3
def read_file(path: str) -> "List of lines":
# File-Objekt ist gleichzeitig Context-Manager,
# schliesst beim Verlassen des Kontextes automatisch den File-Deskriptor
with open(path, 'r') as f:
# f.read(buflen) - binary read
# f.readline() - 1 Textzeile lesen -> str
# f.readlines() - alle Textzeilen lesen -> list
# f ist gleichzeitig Iterator
# 1. Variante: explizite for-Schleife
lines = []
for line in f.readlines():
lines.append(line.rstrip())
# 2. Variante: Mit Hilfe von Lambda und f als Iterator
#lines = list(map(lambda s: s.rstrip(), f))
# 3. Variante: Klassenfunktion rstrip und f als Iterator
#lines = list(map(str.rstrip, f))
# 4. Variante: Mit List Comprehension und f als Iterator
#lines = [line.rstrip() for line in f]
return lines
def parse_passwd_line(line: str) -> "Dict of passwd details":
parts = line.split(':') # erzeugt List of Strings
# userdict = {'username': parts[0], ...}
# https://de.wikipedia.org/wiki/GECOS-Feld
userdict = dict(username=parts[0],
uid=parts[2],
gid=parts[3],
gecos=parts[4],
home=parts[5],
shell=parts[6])
return userdict
def build_userlist(lines) -> "List of user dicts":
result = []
for line in lines:
result.append(parse_passwd_line(line))
return result
def print_userlist_sorted_by_username(userlist):
for user in userlist:
print(user['username'], user['uid'], user['gecos'])
def print_userlist_sorted_by_uid(userlist):
pass
def main():
# Dictionary mit Ausgabe-Funktionen als Referenz
output_functions = {
'username': print_userlist_sorted_by_username,
'uid': print_userlist_sorted_by_uid,
}
# Zum Test diese spezielle Ausgabe-Funktion verwenden
# 'username' kommt spaeter von der Kommandozeile
outfunc = output_functions['username']
lines = read_file("/etc/passwd")
userlist = build_userlist(lines)
# print(userlist) # Kontrollausgabe
outfunc(userlist)
main()

View File

@@ -0,0 +1,82 @@
#! /usr/bin/env python3
def read_file(path: str) -> "List of lines":
# File-Objekt ist gleichzeitig Context-Manager,
# schliesst beim Verlassen des Kontextes automatisch den File-Deskriptor
with open(path, 'r') as f:
# f.read(buflen) - binary read
# f.readline() - 1 Textzeile lesen -> str
# f.readlines() - alle Textzeilen lesen -> list
# f ist gleichzeitig Iterator
# 1. Variante: explizite for-Schleife
lines = []
for line in f.readlines():
lines.append(line.rstrip())
# 2. Variante: Mit Hilfe von Lambda und f als Iterator
#lines = list(map(lambda s: s.rstrip(), f))
# 3. Variante: Klassenfunktion rstrip und f als Iterator
#lines = list(map(str.rstrip, f))
# 4. Variante: Mit List Comprehension und f als Iterator
#lines = [line.rstrip() for line in f]
return lines
def parse_passwd_line(line: str) -> "Dict of passwd details":
parts = line.split(':') # erzeugt List of Strings
# userdict = {'username': parts[0], ...}
# https://de.wikipedia.org/wiki/GECOS-Feld
userdict = dict(username=parts[0],
uid=parts[2],
gid=parts[3],
gecos=parts[4],
home=parts[5],
shell=parts[6])
return userdict
def build_userlist(lines) -> "List of user dicts":
result = []
for line in lines:
result.append(parse_passwd_line(line))
return result
def print_userlist_sorted_by_username(userlist):
# Sorted iteriert ueber die userlist und
# ruft fuer jedes Element key(elem) auf
# also e im Lambda-Ausdruck ist Element der Liste (also der Userdict)
# Sorted baut Shadow-Liste mit Sortierkriterien auf
for user in sorted(userlist, key=lambda e: e['username'].lower()):
print(user['username'], user['uid'], user['gecos'])
def print_userlist_sorted_by_uid(userlist):
for user in sorted(userlist, key=lambda e: e['uid']):
print(user['username'], user['uid'], user['gecos'])
def main():
# Dictionary mit Ausgabe-Funktionen als Referenz
output_functions = {
'username': print_userlist_sorted_by_username,
'uid': print_userlist_sorted_by_uid,
}
# Zum Test diese spezielle Ausgabe-Funktion verwenden
# 'username' kommt spaeter von der Kommandozeile
outfunc = output_functions['username']
lines = read_file("/etc/passwd")
userlist = build_userlist(lines)
# print(userlist) # Kontrollausgabe
outfunc(userlist)
main()

View File

@@ -0,0 +1,85 @@
#! /usr/bin/env python3
def read_file(path: str) -> "List of lines":
# File-Objekt ist gleichzeitig Context-Manager,
# schliesst beim Verlassen des Kontextes automatisch den File-Deskriptor
with open(path, 'r') as f:
# f.read(buflen) - binary read
# f.readline() - 1 Textzeile lesen -> str
# f.readlines() - alle Textzeilen lesen -> list
# f ist gleichzeitig Iterator
# 1. Variante: explizite for-Schleife
lines = []
for line in f.readlines():
lines.append(line.rstrip())
# 2. Variante: Mit Hilfe von Lambda und f als Iterator
#lines = list(map(lambda s: s.rstrip(), f))
# 3. Variante: Klassenfunktion rstrip und f als Iterator
#lines = list(map(str.rstrip, f))
# 4. Variante: Mit List Comprehension und f als Iterator
#lines = [line.rstrip() for line in f]
return lines
def parse_passwd_line(line: str) -> "Dict of passwd details":
parts = line.split(':') # erzeugt List of Strings
# userdict = {'username': parts[0], ...}
# https://de.wikipedia.org/wiki/GECOS-Feld
userdict = dict(username=parts[0],
uid=int(parts[2]),
gid=int(parts[3]),
realname=parts[4].split(',')[0],
gecos=parts[4],
home=parts[5],
shell=parts[6])
return userdict
def build_userlist(lines) -> "List of user dicts":
result = []
for line in lines:
result.append(parse_passwd_line(line))
return result
def print_userlist_sorted_by_username(userlist):
# Sorted iteriert ueber die userlist und
# ruft fuer jedes Element key(elem) auf
# also e im Lambda-Ausdruck ist Element der Liste (also der Userdict)
# Sorted baut Shadow-Liste mit Sortierkriterien auf
for user in sorted(userlist, key=lambda e: e['username'].lower()):
print(user['username'], user['uid'], user['realname'])
def print_userlist_sorted_by_uid(userlist):
for user in sorted(userlist, key=lambda e: e['uid']):
# printf("%5d", intvar)
print("{:5} {:32} {}".format(user['uid'], user['username'], user['realname']))
def main():
# Dictionary mit Ausgabe-Funktionen als Referenz
output_functions = {
'username': print_userlist_sorted_by_username,
'uid': print_userlist_sorted_by_uid,
}
# Zum Test diese spezielle Ausgabe-Funktion verwenden
# 'username' kommt spaeter von der Kommandozeile
# outfunc = output_functions['username']
outfunc = output_functions['uid']
lines = read_file("/etc/passwd")
userlist = build_userlist(lines)
# print(userlist) # Kontrollausgabe
outfunc(userlist)
main()

View File

@@ -0,0 +1,9 @@
#! /usr/bin/env python3
zahlen = []
value = 1
for c in "abcdefghijk":
zahlen.append(value)
value += 1
print(zahlen)

View File

@@ -0,0 +1,10 @@
#! /usr/bin/env python3
zahlen = []
value = 1
while value <= 10:
zahlen.append(value)
value += 1
# Else-Block wird ausgefuehrt, wenn Bedingung irgendwann False ergibt
else:
print(zahlen)

View File

@@ -0,0 +1,8 @@
#! /usr/bin/env python3
zahlen = []
for i in range(10):
zahlen.append(i + 1)
# Else-Block wird ausgefuehrt, wenn Bedingung irgendwann False ergibt
else:
print(zahlen)

View File

@@ -0,0 +1,8 @@
#! /usr/bin/env python3
zahlen = []
for i in range(1, 11):
zahlen.append(i)
# Else-Block wird ausgefuehrt, wenn Bedingung irgendwann False ergibt
else:
print(zahlen)

View File

@@ -0,0 +1,8 @@
#! /usr/bin/env python3
zahlen = []
for i in range(1, 11, 2):
zahlen.append(i)
# Else-Block wird ausgefuehrt, wenn Bedingung irgendwann False ergibt
else:
print(zahlen)

View File

@@ -0,0 +1,11 @@
#! /usr/bin/env python3
zahlen = []
for i in range(1, 11, 2):
zahlen.append(i)
# Else-Block wird ausgefuehrt, wenn Bedingung irgendwann False ergibt
else:
print(zahlen)
mylist = list(range(1, 11, 2))
print(mylist)

View File

@@ -0,0 +1,11 @@
#! /usr/bin/env python3
mylist = list(range(1, 11, 2))
print(mylist)
# Aufgabe: Neue Liste erstellen mit 3. Potzenz der Werte aus mylist
liste_m = [i**3 for i in mylist]
print(liste_m)
print([i**3 for i in mylist])

View File

@@ -0,0 +1,21 @@
#! /usr/bin/env python3
def kubik(n):
return n ** 3
def kugelvolumen(r):
pi = 3.1415
volumen = 4/3 * pi * r ** 3
return volumen
mylist = list(range(1, 11, 2))
# Aufgabe: Neue Liste erstellen mit 3. Potzenz der Werte aus mylist
liste_m = [kubik(i) for i in mylist]
print(liste_m)
volumina = [kugelvolumen(i) for i in mylist]
print(volumina)

View File

@@ -0,0 +1,33 @@
#! /usr/bin/env python3
def kubik(n):
return n ** 3
def kugelvolumen(r):
pi = 3.1415
volumen = 4/3 * pi * r ** 3
return volumen
def create_array(func, iterable):
new_list = [func(i) for i in iterable]
return new_list
mylist = list(range(1, 11, 2))
# Aufgabe: Schreibe Funktion create_array mit 2 Parametern:
# 1. Funktionspointer
# 2. Iterable (z.B. mylist)
# Funktion soll neue Liste erstellen auf Basis des Iterables und jedes
# Element an den Funktionspointer als Aufruf uebergeben
klist = create_array(kubik, mylist)
volumina = create_array(kugelvolumen, mylist)
print(klist)
print(volumina)
print('-'.join(create_array(str, mylist)))
print('-'.join(map(str, mylist)))

View File

@@ -0,0 +1,36 @@
#! /usr/bin/env python3
def kubik(n):
return n ** 3
def kugelvolumen(r):
pi = 3.1415
volumen = 4/3 * pi * r ** 3
return volumen
def create_array(func, iterable):
new_list = [func(i) for i in iterable]
return new_list
mylist = list(range(1, 11, 2))
# Aufgabe: Schreibe Funktion create_array mit 2 Parametern:
# 1. Funktionspointer
# 2. Iterable (z.B. mylist)
# Funktion soll neue Liste erstellen auf Basis des Iterables und jedes
# Element an den Funktionspointer als Aufruf uebergeben
klist = create_array(kubik, mylist)
volumina = create_array(kugelvolumen, mylist)
print(klist)
print(volumina)
print('-'.join(create_array(str, mylist)))
# print('-'.join(mylist))
print('-'.join(map(str, mylist)))
# print('-'.join(map(kugelvolumen, mylist)))
print('-'.join(map(str, map(kugelvolumen, mylist))))

View File

@@ -0,0 +1,45 @@
#! /usr/bin/env python3
def kubik(n):
return n ** 3
def kugelvolumen(r):
pi = 3.1415
volumen = 4/3 * pi * r ** 3
return volumen
def create_array(func, iterable):
new_list = [func(i) for i in iterable]
return new_list
def inc3(i):
return i + 3
def inc_5(i):
return i + 5
mylist = list(range(1, 11, 2))
print(list(map(kubik, mylist)))
# print('-'.join(create_array(str, mylist)))
print('-'.join(map(str, mylist)))
print(list(map(inc3, mylist)))
# Lambda-Ausdruck ist leichtgewichtige Funktion (Lightweight function)
print(list(map(lambda n:n + 3, mylist)))
print(create_array(lambda n:n + 3, mylist))
def quad(n):
return n ** 4
func = lambda n: n ** 4
print("2 hoch 4:", func(2))
print("2 hoch 4:", quad(2))
# Lambda-Ausdruck direkt aufrufen
print((lambda n: n ** 4)(2))

View File

@@ -0,0 +1,21 @@
#! /usr/bin/env python3
# Aufgabe: Bilde die Summe aller Zahlen von 1 bis 512 die durch 3 oder 5
# teilbar sind
def summe(*values: 'List of ints') -> int:
result = 0
for v in values:
result += v
return result
# Kontrollausgabe: Alle Zahlen von 1 bis 512 inkl.
print(list(range(1, 512)))
# Kontrollausgabe: Alle Zahlen, die durch 3 oder 5 teilbar sind
print(list(filter(lambda n: n % 5 == 0 or n % 3 == 0, range(1, 512))))
print(sum(filter(lambda n: n % 5 == 0 or n % 3 == 0, range(1, 512))))
print(summe(*filter(lambda n: n % 5 == 0 or n % 3 == 0, range(1, 512))))

Binary file not shown.

View File

@@ -0,0 +1,31 @@
"""
Name des Moduls (Kopfzeile)
Ausfuehrliche Beschreibung des Moduls
"""
import sys
def argv_value(param: str, default: str = None) -> str:
"""
Ermittelt den Wert eines Parameters auf der Kommandozeile
'param' entspricht dem Parameter, nach dem gesucht wird,
mit fuehrendem dash. etc. foo bar bla fasel :p
'default' plus Beschreibung dazu, bin zu faul
Beispiel:
value = argv_value('-o', 'pprint')
"""
for idx, val in enumerate(sys.argv):
if val == param:
if idx+1 < len(sys.argv) and not sys.argv[idx+1].startswith('-'):
return sys.argv[idx+1]
return default
# python3 -m argv # Aufruf des Moduls als Hauptprogramm
if __name__ == '__main__':
print("Wert von -o :", argv_value('-o'))
print("Kommandozeile :", sys.argv[1:])

View File

@@ -0,0 +1,10 @@
#! /usr/bin/env python3
from vectors import Vector
v1 = Vector()
v2 = Vector()
print(v1)
print(v2)
print("0x{:12x}".format(id(v1)))
print("0x{:12x}".format(id(v2)))

View File

@@ -0,0 +1,10 @@
#! /usr/bin/env python3
from vectors import Vector
v1 = Vector()
print(v1)
v1.test()
v1.test(1, 2, 3)
print(v1.test)

View File

@@ -0,0 +1,16 @@
#! /usr/bin/env python3
from vectors import Vector
v1 = Vector(1, 2, 3)
v2 = Vector(4, 0, 1)
print(v1)
# Achtung: Zugriff von aussen auf Objekt-Interna sollten vermieden werden
# print(v1.local_values)
# Besser: Nur ueber passende Getter zugreifen
print(v1.get_values())
#v2 = "Kill"
#v2 = None
del v2 # Loescht gleichzeitig Name v2 aus aktuellem Scope
print("Jetzt wurde gerade v2 freigegeben")

View File

@@ -0,0 +1,15 @@
#! /usr/bin/env python3
from vectors import Vector
v1 = Vector(1, 2, 3)
v2 = Vector(4, 0, 1)
print(v1)
print(len(v1))
# v3 = v1.skalarmultiplikation(3)
v3 = v1 * 3 # wird daraus v1.__mul__(3)
print("v3 =", v3, type(v3))
v4 = v1 + v2 # wird daraus v1.__add__(v2)
print("v4 =", v4, type(v4))

View File

@@ -0,0 +1,14 @@
#! /usr/bin/env python3
from vectors import Vector2
v1 = Vector2(1, 3)
v2 = Vector2(2, 0)
v3 = v1 + v2
print("v3:", v3, type(v3))
v4 = v2 * 4
print("v4:", v4, type(v4))
print("Klasse von v4:", v4.info())

View File

@@ -0,0 +1,21 @@
#! /usr/bin/env python3
from vectors import Vector2, Vector9
v1 = Vector2(1, 3)
v2 = Vector2(2, 0)
print(v1.__str__())
print(Vector2.__str__(v1))
print(v1.static())
print(Vector2.static())
print(v1.static)
print(Vector2.static)
print(v1.__str__)
print(Vector2.__str__)
# v9 = Vector9(1,2,3)
# v1 + "Quatsch"

View File

@@ -0,0 +1,32 @@
#! /usr/bin/env python3
def inc_generator(n):
"""
Increment-Generator mit Currying (Closure)
"""
return lambda i: i + n
def inc_generator_full(n):
"""
Increment-Generator mit Currying (Closure)
"""
def inner_function(i):
return i + n
return inner_function
inc3 = inc_generator(3)
inc9 = inc_generator(9)
#print(inc3)
print(inc3(10))
print(inc9(10))
print('-' * 30)
inc3 = inc_generator_full(3)
inc9 = inc_generator_full(9)
#print(inc3)
print(inc3(10))
print(inc9(10))
print(inc_generator(10)(10))
print(inc_generator_full(10)(10))

View File

@@ -0,0 +1,30 @@
internal_counter_dict = {}
def counter(func):
def counting(*args, **kwargs):
counting.callcount += 1
return func(*args, **kwargs)
# counting ist "nur" ein Objekt, kann daher auch Attribute halten
counting.callcount = 0
# Alternativ: Funktionsreferenz als Dictionary-Key verwenden
internal_counter_dict[counting] = 0
return counting
def get_counter(func):
try:
return func.callcount
except:
return None
def reset_counter(func):
try:
# Folgende Zeile verhindert das Setzen bei nicht dekorierten Funcs
func.callcount
func.callcount = 0
except:
pass

View File

@@ -0,0 +1,24 @@
#! /usr/bin/env python3
from decorators import counter, get_counter
# Dekorator sorgt dafuer, dass Python nach Compiler in der Ausfuehrung
# die Funktion fak veraendert:
#
# fak = counter(fak)
# fak = counter(<urspruengliche Funktionsreferenz>)
@counter
def fak(n):
if type(n) is not int or n < 0:
raise TypeError("Illegal type")
if n == 0:
return 1
return n * fak(n-1)
# reset_counter(fak)
print("6! =", fak(6))
print("Anzahl Aufrufe:", get_counter(fak))
# reset_counter(print)

View File

@@ -0,0 +1,15 @@
#! /usr/bin/env python3
def fibonacci(n):
if n == 1:
return 1
if n == 2:
return 1
# Rekursiver Funktionsaufruf
return fibonacci(n - 1) + fibonacci(n - 2)
print("fib(5) =", fibonacci(5))
print("fib(10) =", fibonacci(10))
print("fib(40) =", fibonacci(40))

View File

@@ -0,0 +1,24 @@
#! /usr/bin/env python3
from decorators import counter, get_counter, reset_counter
@counter
def fibonacci(n):
if n == 1:
return 1
if n == 2:
return 1
# Rekursiver Funktionsaufruf
return fibonacci(n - 1) + fibonacci(n - 2)
reset_counter(fibonacci)
print("fib(5) =", fibonacci(5))
print("Anzahl Funktionsaufrufe:", get_counter(fibonacci))
reset_counter(fibonacci)
print("fib(10) =", fibonacci(10))
print("Anzahl Funktionsaufrufe:", get_counter(fibonacci))
reset_counter(fibonacci)
print("fib(40) =", fibonacci(40))
print("Anzahl Funktionsaufrufe:", get_counter(fibonacci))

View File

@@ -0,0 +1,21 @@
#! /usr/bin/env python3
def fibonacci(n):
if n == 1:
return 1
if n == 2:
return 1
# Rekursiver Funktionsaufruf
# return fibonacci(n - 1) + fibonacci(n - 2)
fn_1, fn_2 = 1, 1
for i in range(n-2):
fn_1, fn_2 = fn_1 + fn_2, fn_1
return fn_1
print("fib(5) =", fibonacci(5))
print("fib(10) =", fibonacci(10))
print("fib(40) =", fibonacci(40))

View File

@@ -0,0 +1,31 @@
#! /usr/bin/env python3
# yield in Funktion erzeugt automatisch Iterator(-Generator)
# yield gibt innerhalb einer Iteration einen Wert zurueck
# und haelt die Funktion an, damit dort bei der naechsten
# Iteration weiter gearbeitet werden kann
def fibonacci_folge(n):
if n >= 1:
#print("yield 1 (fib(1))")
yield 1
if n >= 2:
#print("yield 1 (fib(2))")
yield 1
fn_1, fn_2 = 1, 1
for i in range(n-2):
fn_1, fn_2 = fn_1 + fn_2, fn_1
#print("yield {} (fib({}))".format(fn_1, i+3))
yield fn_1
#for n in range(1,31):
# print(fibonacci(n))
for fib in fibonacci_folge(30):
print(fib)
# Keine konkreten Werte mehr, sondern Generator-Objekt
# print(fibonacci_folge(30))
# print(list(fibonacci_folge(30)))
# print([i for i in fibonacci_folge(30)])

View File

@@ -0,0 +1,32 @@
#! /usr/bin/env python3
# yield in Funktion erzeugt automatisch Iterator(-Generator)
# yield gibt innerhalb einer Iteration einen Wert zurueck
# und haelt die Funktion an, damit dort bei der naechsten
# Iteration weiter gearbeitet werden kann
def fibonacci_folge(n):
if n >= 1:
#print("yield 1 (fib(1))")
yield 1
if n >= 2:
#print("yield 1 (fib(2))")
yield 1
fn_1, fn_2 = 1, 1
for i in range(n-2):
fn_1, fn_2 = fn_1 + fn_2, fn_1
#print("yield {} (fib({}))".format(fn_1, i+3))
yield fn_1
#for n in range(1,31):
# print(fibonacci(n))
# enumerate liefert Tupel aus Schleifendurchlaufsnummer und Wert
for nr, fib in enumerate(fibonacci_folge(30)):
print(nr+1, fib)
# Keine konkreten Werte mehr, sondern Generator-Objekt
# print(fibonacci_folge(30))
# print(list(fibonacci_folge(30)))
# print([i for i in fibonacci_folge(30)])

View File

@@ -0,0 +1,28 @@
#! /usr/bin/env python3
# yield in Funktion erzeugt automatisch Iterator(-Generator)
# yield gibt innerhalb einer Iteration einen Wert zurueck
# und haelt die Funktion an, damit dort bei der naechsten
# Iteration weiter gearbeitet werden kann
def fibonacci_folge(n):
if n >= 1:
#print("yield 1 (fib(1))")
yield 1, 1
if n >= 2:
#print("yield 1 (fib(2))")
yield 2, 1
fn_1, fn_2 = 1, 1
for i in range(n-2):
fn_1, fn_2 = fn_1 + fn_2, fn_1
#print("yield {} (fib({}))".format(fn_1, i+3))
yield i+3, fn_1
for nr, fib in fibonacci_folge(30):
print(nr, fib)
# Keine konkreten Werte mehr, sondern Generator-Objekt
# print(fibonacci_folge(30))
# print(list(fibonacci_folge(30)))
# print([i for i in fibonacci_folge(30)])

View File

@@ -0,0 +1,28 @@
#! /usr/bin/env python3
#[(lambda i: i + 1)(n) for n in range(10)]
#[ i + 1 for i in range(10)]
# Achtung: Joey hat sich in den Fuss geschossen!
# Es scheint, als waere n in der Comprehension eine Referenz
# und nicht in jedem Schleifendurchlauf eine neue Variable
# Daher funktioniert Currying hier nicht
mylist = [(lambda i: i + n) for n in range(10)]
#print(mylist)
print(mylist[5](10))
print(mylist[8](10))
mylist = [lambda i: print(n) for n in range(10)]
print(mylist[5](10))
n = 100
print(mylist[5](10))
print("-" * 30)
mylist = []
for n in range(10):
mylist.append(lambda i: i + n)
print(mylist[5](10))
print(mylist[8](10))

View File

@@ -0,0 +1,14 @@
#! /usr/bin/env python3
for i in range(5):
if i == 1:
print(i, "Taxi")
else:
print(i, "Taxen")
print("-" * 30)
for i in range(5):
print(i, "Taxi" if i == 1 else "Taxen")
text = "Taxi" if i == 1 else "Taxen"

View File

@@ -0,0 +1,100 @@
"""
Mathematische Vektoren als Klassen
__funktionen__ sind Magic Methods
"""
class VectorError(Exception):
pass
class VectorTypeError(VectorError):
pass
# implizit wird automatisch von Super-Oberklasse object geerbt
class Vector():
values = () # Achtung: Klassenvariable (Fallback fuer self.values)
def __init__(self, *values):
"Initialisierung: 1. Funktion nach Erzeugen des Objekts"
self.my_values = values
self.values = 0 # legt lokale Variable in self an
def __del__(self):
"Destruktor: Letzte Funktion vor Freigabe des Speichers"
try:
print("Ein Objekt wird freigegeben ({})".format(self.my_values))
except AttributeError:
print("Ein Objekt wird freigegeben (unknown)")
def __len__(self):
return len(self.my_values) # ruft intern self.my_values.__len__() auf
def __str__(self):
return type(self).__name__ + str(self.my_values)
def get_values(self):
return self.my_values
def __mul__(self, factor):
#self.get_values() # self.my_values
mylist = [v * factor for v in self.get_values()]
# *mylist expandiert Liste in Positionsparameter
return type(self)(*mylist)
def __add__(self, other):
#if type(self) != type(other):
# raise VectorTypeError("Addition nur mit gleichen Klassen")
if not isinstance(self, Vector) or not isinstance(other, Vector):
raise VectorTypeError("Addition nur von Vektoren")
if len(self) != len(other):
raise VectorTypeError("Vektoren ungleicher Laenge")
summenwerte = []
for a, b in zip(self.get_values(), other.get_values()):
summenwerte.append(a + b)
return type(self)(*summenwerte)
def __sub__(self, other):
return type(self)(*[a-b for a, b in \
zip(self.get_values(), other.get_values())])
def test(*args):
print("Aufruf von objekt-orientierter Funktion test")
# 1. Element im Tupel ist Objekt selbst
print(args)
def poly(self, *args):
"Beispiel fuer Polymorphismus in Python"
if len(args) == 1:
# 1-stellige Verarbeitung
if type(args[0]) is str:
print("Stringverarbeitung")
elif type(args[0]) is int or type(args[0]) is float:
print("Arbeit mit Zahlen")
elif len(args) == 2:
# 2-stellige Verarbeitung
self.poly_2param(*args)
elif len(args) == 0:
# 0-stellige Verarbeitung
Vector.poly_0param(self, *args)
else:
pass
@classmethod
def info(cls):
return cls.__name__
@staticmethod
def static():
return "statische Methode"
class Vector2(Vector):
def __init__(self, val1, val2):
# Vector.__init__(self, val1, val2)
# sucht in der Hierarchie der Oberklassen nach der passenden Funktion
super().__init__(val1, val2)
class Vector9(Vector):
def __init__(self, *values):
if len(values) != 9:
raise VectorTypeError("9 elements required")
super().__init__(*values)

View File

@@ -0,0 +1,15 @@
#! /usr/bin/env python3
def endless():
"Endless Range Replacement"
start = 0
while True:
yield start
start += 1
it1 = range(10, 15)
it2 = range(100, 105)
# Zip iteriert ueber alle angegebenen Iterables parallel
for a, b, idx in zip(it1, it2, endless()):
print(idx, a, b)

View File

@@ -0,0 +1,66 @@
#! /usr/bin/env python3
a = 10
b = 13
print(a, b)
# Inhalt der Variablen a und b vertauschen
tmp = a
a = b
b = tmp
print(a, b)
def foo(i):
"Gibt 3 Werte als Tupel zurueck"
inc = i + 1
add = i + i
mul = i * i
ergebnis = [inc, add, mul]
ergebnis = (inc, add, mul)
# return ergebnis
# Automatisches pack -> erzeugt Tupel
return inc, add, mul
# Sieht aus wie Mehrfachzuweisung, ist es aber nicht ;-)
a, b = b, a
# Anwendung z.B. bei regulaeren Ausdruecken:
# ip_address, oktett = match.groups()
print(a, b)
a, b, c, d, e = 10, 20, 30, 40, 50
print(a, b, c, d, e)
# Automatisches pack -> erzeugt Tupel
whut = 10, 20, 30, 40, 50
print(whut)
mytuple = (10, 13, 14, 15, 16)
# Automatisches unpack, Werte werden paarweise zugewiesen
a, b, c, d, e = mytuple
print(a, b, c, d, e)
mylist = [23, 24, 25, 26, 27]
a, b, c, d, e = mylist
print(a, b, c, d, e)
*a, b, c, d, e = 10, 20, 30, 40, 50, 60
print(a, b, c, d, e)
a, b, c, d, *e = 10, 20, 30, 40, 50, 60
print(a, b, c, d, e)
a, b, c, *d, e = 10, 20, 30, 40, 50, 60
print(a, b, c, d, e)
a, b, c = foo(10)
result = foo(10)
print(a, b, c)
print(result)
print(*result) # *result erzeugt Menge von Positionsparametern
e = 6, 7, 8, 9, 10, 11, mytuple
print(e)
print(*e)

View File

@@ -0,0 +1,31 @@
#! /usr/bin/env python3
import sys
import pymysql
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
# Zum Testen in der Shell
# mysql -h notebook14 -u python -pvilla inventory
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def main():
db = db_connect(credentials)
# Verbindung sauber trennen
db.close()
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory')
hide_exception(main)

View File

@@ -0,0 +1,13 @@
#! /usr/bin/env python3
import datetime
strings = [
'2022-11-25 16:04:57',
'2022-11-25 10:10:00',
'2022-11-22 13:01:02',
'2022-10-26 14:02:05',
]
timestamp = datetime.datetime.fromisoformat(strings[0])
print(timestamp.timestamp())

View File

@@ -0,0 +1,46 @@
internal_counter_dict = {}
def counter(func):
def counting(*args, **kwargs):
counting.callcount += 1
return func(*args, **kwargs)
# counting ist "nur" ein Objekt, kann daher auch Attribute halten
counting.callcount = 0
# Alternativ: Funktionsreferenz als Dictionary-Key verwenden
internal_counter_dict[counting] = 0
return counting
def get_counter(func):
try:
return func.callcount
except:
return None
def reset_counter(func):
try:
# Folgende Zeile verhindert das Setzen bei nicht dekorierten Funcs
func.callcount
func.callcount = 0
except:
pass
def trace(func):
# In tracing steht Objekt func via Currying zur Verfuegung
# tracing = <funktionsobjekt>
def tracing(*args, **kwargs):
tracing.level += 1
print(' '*(tracing.level*4)+"BEGIN function", func.__name__, args[0])
result = func(*args, **kwargs)
print(' '*(tracing.level*4)+"END function", func.__name__, args[0])
tracing.level -= 1
return result
tracing.level = 0
return tracing

View File

@@ -0,0 +1,51 @@
#! /usr/bin/env python3
import requests
from pprint import pprint
# http://ip.jsontest.com/
# https://luonnotar.infodrom.org/json/
def get_external_ip():
url = 'https://luonnotar.infodrom.org/json/'
# .get = GET, .post = POST, .put = PUT, .delete = DELETE, .options = OPTIONS
response = requests.get(url)
# print(response)
# print(type(response))
# print(response.status_code)
if response.status_code != 200:
raise Exception("HTTP Status is " + str(response.status_code))
# print(response.content)
# print(type(response.content))
# print("Content-type der Antwort:", response.headers['Content-Type'])
# Konvertierung bytes nach str
#text = response.content.decode()
#print(text)
# Falls die Antwort ein Text ist:
#print(response.text)
# import json
# local_data = json.loads(json_string) # erzeugt Python-Datenstruktur
# json_string = json.dumps(data) # erzeugt JSON-String der Daten
if 'application/json' not in response.headers['content-type']:
raise Exception("Content-Type is not application/json")
# Falls der Content-Type application/json ist
data = response.json()
# Verschachtelte Struktur am Besten einmal mit Pretty-Printer ausgeben
# pprint(data)
return data['ip']['remote']
# data werden url-encoded key=value&key2=value2&key3=value3
# json wird automatisch in JSON kodiert
# response = requests.post(URL, data={...}, json={...}
ip = get_external_ip()
print("Aktuelle externe IP-Adresse:", ip)

14
Lehrer/pythonkurs/Freitag/fak Executable file
View File

@@ -0,0 +1,14 @@
#! /usr/bin/env python3
from decorators import trace
# Python erzeugt daraus
# fak = trace(fak)
@trace
def fak(n):
if n == 0:
return 1
return n * fak(n-1)
print(fak(6))

View File

@@ -0,0 +1,101 @@
#! /usr/bin/env python3
import sys
import pymysql
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def list_hosts(connection):
cursor = connection.cursor()
# Simple: SELECT * FROM hosts
sql = """
SELECT name, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
# TODO: cursor.description enthaelt die Feldnamen
# cursor.fetchone()
# cursor.fetchall()
# cursor ist Iterator
for row in cursor:
print("{0:20} {2:15} {1}".format(*row))
# for name, domain, address in cursor:
# pass
def add_host_variante_0_unvollstaendig(connection, name, domain, address):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(name, domain, address)
def add_host_variante_1_unvollstaendig(connection, *args):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(*args)
def add_host(connection, data):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{name}', '{domain}', '{address}')
""".format(**data)
cursor.execute(sql)
connection.commit()
def add_host_flexi(connection, data, table='hosts'):
cursor = connection.cursor()
sql = """
INSERT INTO {table}
(name, domain, address)
VALUES ('{name}', '{domain}', '{address}')
""".format(table=table, **data)
cursor.execute(sql)
connection.commit()
def main():
db = db_connect(credentials)
# list_hosts(db)
row = dict(name='notebook99',
domain='linuxhotel.de',
address='192.168.1.299')
add_host(db, row)
# add_host(db, 'notebook99', 'linuxhotel.de', '192.168.1.299')
# add_host(db, name='notebook99', domain='linuxhotel.de', a='192.168.1.299')
# db_insert(db, 'hosts', row) # noch allgemeiner
# Verbindung sauber trennen
db.close()
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory')
hide_exception(main)

View File

@@ -0,0 +1,106 @@
#! /usr/bin/env python3
import sys
import pymysql
# import sqlite3 as dbdriver
# import psycopg2 as dbdriver
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def list_hosts(connection):
cursor = connection.cursor()
# Simple: SELECT * FROM hosts
sql = """
SELECT name, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
# TODO: cursor.description enthaelt die Feldnamen
# cursor.fetchone()
# cursor.fetchall()
# cursor ist Iterator
for row in cursor:
print("{0:20} {2:15} {1}".format(*row))
# for name, domain, address in cursor:
# pass
def add_host_variante_0_unvollstaendig(connection, name, domain, address):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(name, domain, address)
def add_host_variante_1_unvollstaendig(connection, *args):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(*args)
# Achtung: https://xkcd.com/327/
def add_host(connection, data):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES (%s, %s, %s)
"""
# Platzhalter %s erfordert Tupel mit passenden Werten
# In der Datenbank-Schicht wird passend maskiert
cursor.execute(sql, (data['name'], data['domain'], data['address']))
connection.commit()
def add_host_flexi(connection, data, table='hosts'):
cursor = connection.cursor()
sql = """
INSERT INTO {table}
(name, domain, address)
VALUES ('{name}', '{domain}', '{address}')
""".format(table=table, **data)
cursor.execute(sql)
connection.commit()
def main():
db = db_connect(credentials)
# list_hosts(db)
row = dict(name="'notebook99');DELETE FROM hosts; --",
domain='linuxhotel.de',
address='192.168.1.299')
add_host(db, row)
# add_host(db, 'notebook99', 'linuxhotel.de', '192.168.1.299')
# add_host(db, name='notebook99', domain='linuxhotel.de', a='192.168.1.299')
# db_insert(db, 'hosts', row) # noch allgemeiner
# Verbindung sauber trennen
db.close()
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory')
hide_exception(main)

View File

@@ -0,0 +1,106 @@
#! /usr/bin/env python3
import sys
import pymysql
# import sqlite3 as dbdriver
# import psycopg2 as dbdriver
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def list_hosts(connection):
cursor = connection.cursor()
# Simple: SELECT * FROM hosts
sql = """
SELECT name, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
# TODO: cursor.description enthaelt die Feldnamen
# cursor.fetchone()
# cursor.fetchall()
# cursor ist Iterator
for row in cursor:
print("{0:20} {2:15} {1}".format(*row))
# for name, domain, address in cursor:
# pass
def add_host_variante_0_unvollstaendig(connection, name, domain, address):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(name, domain, address)
def add_host_variante_1_unvollstaendig(connection, *args):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(*args)
# Achtung: https://xkcd.com/327/
def add_host(connection, data):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES (%(name)s, %(domain)s, %(address)s)
"""
# Platzhalter %(name)s erfordert Dict mit passenden Keys
# In der Datenbank-Schicht wird passend maskiert
cursor.execute(sql, data)
connection.commit()
def add_host_flexi(connection, data, table='hosts'):
cursor = connection.cursor()
sql = """
INSERT INTO {table}
(name, domain, address)
VALUES ('{name}', '{domain}', '{address}')
""".format(table=table, **data)
cursor.execute(sql)
connection.commit()
def main():
db = db_connect(credentials)
# list_hosts(db)
row = dict(name='notebook99',
domain='linuxhotel.de',
address='192.168.1.299')
add_host(db, row)
# add_host(db, 'notebook99', 'linuxhotel.de', '192.168.1.299')
# add_host(db, name='notebook99', domain='linuxhotel.de', a='192.168.1.299')
# db_insert(db, 'hosts', row) # noch allgemeiner
# Verbindung sauber trennen
db.close()
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory')
hide_exception(main)

View File

@@ -0,0 +1,126 @@
#! /usr/bin/env python3
import sys
import pymysql
# import sqlite3 as dbdriver
# import psycopg2 as dbdriver
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def list_hosts(connection):
cursor = connection.cursor()
# Simple: SELECT * FROM hosts
sql = """
SELECT name, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
# TODO: cursor.description enthaelt die Feldnamen
# cursor.fetchone()
# cursor.fetchall()
# cursor ist Iterator
for row in cursor:
print("{0:20} {2:15} {1}".format(*row))
# for name, domain, address in cursor:
# pass
def add_host_variante_0_unvollstaendig(connection, name, domain, address):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(name, domain, address)
def add_host_variante_1_unvollstaendig(connection, *args):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(*args)
# Achtung: https://xkcd.com/327/
def add_host(connection, data):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES (%(name)s, %(domain)s, %(address)s)
"""
# Platzhalter %(name)s erfordert Dict mit passenden Keys
# In der Datenbank-Schicht wird passend maskiert
cursor.execute(sql, data)
connection.commit()
def add_host_flexi(connection, data, table='hosts'):
cursor = connection.cursor()
sql = """
INSERT INTO {table}
(name, domain, address)
VALUES ('{name}', '{domain}', '{address}')
""".format(table=table, **data)
cursor.execute(sql)
connection.commit()
def db_insert_into(connection, table, data):
columns = []
values = []
for col in data.keys():
col = col.replace("'", '') # gegen SQL Injection
columns.append(col)
values.append('%('+col+')s')
# values.append('%({})s'.format(col))
sql = """
INSERT INTO {table}
({columns})
VALUES ({placeholder})
""".format(
table=table,
columns=','.join(columns),
placeholder=','.join(values))
# Beim Verlassen des Kontextes wird automatisch commit aufgerufen
with connection as cursor:
cursor.execute(sql, data)
def main():
db = db_connect(credentials)
# list_hosts(db)
row = dict(name='notebook99',
domain='linuxhotel.de',
address='192.168.1.299')
db_insert_into(db, 'hosts', row)
# Verbindung sauber trennen
db.close()
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory')
hide_exception(main)

View File

@@ -0,0 +1,52 @@
#! /usr/bin/env python3
import sys
import pymysql
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def list_hosts(connection):
cursor = connection.cursor()
# Simple: SELECT * FROM hosts
sql = """
SELECT name, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
# TODO: cursor.description enthaelt die Feldnamen
# cursor.fetchone()
# cursor.fetchall()
# cursor ist Iterator
for row in cursor:
print("{0:20} {2:15} {1}".format(*row))
# for name, domain, address in cursor:
# pass
def main():
db = db_connect(credentials)
list_hosts(db)
# Verbindung sauber trennen
db.close()
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory')
hide_exception(main)

View File

@@ -0,0 +1,59 @@
#! /usr/bin/env python3
import sys
import pymysql
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def list_hosts(connection):
cursor = connection.cursor()
# Simple: SELECT * FROM hosts
sql = """
SELECT name, length(name) AS namelen, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
#print(cursor.description)
# cursor ist Iterator
# Hausarbeit: Konvertierung von tupel zu dict als Funktion :-)
# for row in named(cursor):
for row in cursor:
#print(list(zip(cursor.description, row)))
#print(list(zip(map(lambda d:d[0], cursor.description), row)))
# Dictionary Comprehension
# mydict = { i: i**10 for i in range(10) }
# row = {k:v for k, v in zip(map(lambda d:d[0], cursor.description), row)}
#print(list(zip(map(lambda d:d[0], cursor.description), row)))
#print(tuple(zip(map(lambda d:d[0], cursor.description), row)))
row = dict(zip(map(lambda d:d[0], cursor.description), row))
print("{name:20} {address:15} {domain}".format(**row))
# for name, domain, address in cursor:
# pass
def main():
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory')
db = db_connect(credentials)
list_hosts(db)
# Verbindung sauber trennen
db.close()
hide_exception(main)

View File

@@ -0,0 +1,53 @@
#! /usr/bin/env python3
import sys
import pymysql
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def list_hosts(connection):
cursor = connection.cursor()
# Simple: SELECT * FROM hosts
sql = """
SELECT name, length(name) AS namelen, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
# TODO: cursor.description enthaelt die Feldnamen
# cursor.fetchone()
# cursor.fetchall()
# cursor ist Iterator
for row in cursor:
print("{name:20} {address:15} {domain}".format(**row))
# for name, domain, address in cursor:
# pass
def main():
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory',
# DictCursor erzeugt als row ein Dict statt Tupel
cursorclass=pymysql.cursors.DictCursor)
db = db_connect(credentials)
list_hosts(db)
# Verbindung sauber trennen
db.close()
hide_exception(main)

View File

@@ -0,0 +1,17 @@
"""
Allgemeine Mathematische Funktionen
"""
__version__ = (1, 0, 2)
def fak(n):
"Berechnung der Fakultaet"
if type(n) is not int:
raise TypeError("Fakultaet ist nur fuer Ganzzahlen definiert")
if n < 0:
raise ValueError("Fakultaet fuer negative Zahlen nicht definiert")
if n == 0:
return 1
return n * fak(n-1)

View File

@@ -0,0 +1,49 @@
from unittest import TestCase, main, skip, skipIf, skipUnless
from mathematik import fak
class FacultyTester(TestCase):
def test_basic(self):
self.assertEqual(fak(0), 1)
self.assertEqual(fak(1), 1)
def test_basic2(self):
self.assertTrue(fak(0) == 1)
self.assertTrue(fak(1) == 1)
def test_basic3(self):
self.assertFalse(fak(0) == 0)
def test_greater(self):
for n in range(2,10):
self.assertGreater(fak(n), fak(n-1))
def test_invalid(self):
# Achtung: Funktion wird ausserhalb von assertRaises aufgerufen
# self.assertRaises(Exception, fak(-1))
# Jetzt ruft assertRaises das Callable=fak mit *args, **kwargs auf
self.assertRaises(Exception, fak, -1)
with self.assertRaises(Exception):
fak(-1)
with self.assertRaises(ValueError):
fak(-1)
# v1 + v2
def test_kaputt(self):
self.skipTest("Ist kaputt")
self.assertTrue(False)
@skip("darum")
def test_kaputt_auch_ist(self):
self.assertTrue(False)
# mathematik.__version__ / mathematik.VERSION
@skipUnless("1.0" > "3.0", "Modul zu alt")
def test_ab_version_3(self):
self.assertFalse(True)
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,35 @@
"""
Name des Moduls (Kopfzeile)
Ausfuehrliche Beschreibung des Moduls
"""
import sys
def argv_value(param: str, default: str = None) -> str:
"""
Ermittelt den Wert eines Parameters auf der Kommandozeile
'param' entspricht dem Parameter, nach dem gesucht wird,
mit fuehrendem dash. etc. foo bar bla fasel :p
'default' plus Beschreibung dazu, bin zu faul
Beispiel:
value = argv_value('-o', 'pprint')
"""
idx = 1 # idx 0 ist der Programmpfad
while idx < len(sys.argv):
if sys.argv[idx] == param:
if idx+1 < len(sys.argv) and not sys.argv[idx+1].startswith('-'):
return sys.argv[idx+1]
idx += 1
return default
# python3 -m argv # Aufruf des Moduls als Hauptprogramm
if __name__ == '__main__':
print("Wert von -o :", argv_value('-o'))
print("Kommandozeile :", sys.argv[1:])

View File

@@ -0,0 +1,8 @@
#! /usr/bin/env python3
import sys
from argv import argv_value
print("Wert von -o :", argv_value('-o'))
print("Kommandozeile :", sys.argv[1:])

View File

@@ -0,0 +1,10 @@
#! /usr/bin/env python3
# Nur Bezeichner pprint aus Modul pprint importieren
from pprint import pprint
data = dict(userlist=['nutzer01', 'nutzer02', 'nutzer03',
'nutzer04', 'nutzer05', 'nutzer06'],
location="Linuxhotel")
pprint(data)

View File

@@ -0,0 +1,11 @@
#! /usr/bin/env python3
# Gesamtes Modul pprint als Bezeichner pprint zur Verfuegung stellen
import pprint
data = dict(userlist=['nutzer01', 'nutzer02', 'nutzer03',
'nutzer04', 'nutzer05', 'nutzer06'],
location="Linuxhotel")
pprint.pprint(data)

Some files were not shown because too many files have changed in this diff Show More