From c0ae9cc93df0029e3175e66ba83d2dffaa3b02c6 Mon Sep 17 00:00:00 2001 From: jonnybravo Date: Tue, 11 Apr 2023 17:21:48 +0200 Subject: [PATCH] commit message from python script --- Dienstag/User_modify.py | 0 Dienstag/func.py | 0 Dienstag/func_summe.py | 0 Dienstag/nutzer.py | 0 Dienstag/zahlen.py | 0 .../__pycache__/decorators.cpython-39.pyc | Bin Donnerstag/__pycache__/vectors.cpython-39.pyc | Bin Donnerstag/check_zip.py | 0 Donnerstag/curry.py | 0 Donnerstag/decorators.py | 0 Donnerstag/fakultät.py | 0 Donnerstag/fibonacci.py | 0 Donnerstag/taxi.py | 0 Donnerstag/temp_var.py | 0 Donnerstag/v_calc.py | 0 Donnerstag/vectors.py | 0 Freitag/__pycache__/decorators.cpython-39.pyc | Bin Freitag/__pycache__/mathematik.cpython-39.pyc | Bin Freitag/__pycache__/utilities.cpython-39.pyc | Bin Freitag/check_env.py | 0 Freitag/db_con.py | 0 Freitag/db_select.py | 0 Freitag/decorators.py | 0 Freitag/ext_ip.py | 0 Freitag/fakultät.py | 0 Freitag/fibonacci.py | 0 Freitag/insert_all.py | 0 Freitag/mathematik.py | 0 Freitag/test_fak.py | 0 Freitag/utilities.py | 0 Lehrer/pythonkurs/Dienstag/function1 | 8 ++ Lehrer/pythonkurs/Dienstag/function2 | 8 ++ Lehrer/pythonkurs/Dienstag/function3 | 11 ++ Lehrer/pythonkurs/Dienstag/function3.1 | 16 +++ Lehrer/pythonkurs/Dienstag/function4 | 21 +++ Lehrer/pythonkurs/Dienstag/function5 | 13 ++ Lehrer/pythonkurs/Dienstag/function6 | 21 +++ Lehrer/pythonkurs/Dienstag/function7 | 19 +++ Lehrer/pythonkurs/Dienstag/function8 | 20 +++ Lehrer/pythonkurs/Dienstag/function9 | 22 +++ Lehrer/pythonkurs/Dienstag/functiona | 33 +++++ Lehrer/pythonkurs/Dienstag/functionb | 17 +++ Lehrer/pythonkurs/Dienstag/functionc | 16 +++ Lehrer/pythonkurs/Dienstag/sorting1 | 13 ++ Lehrer/pythonkurs/Dienstag/userlist1 | 61 +++++++++ Lehrer/pythonkurs/Dienstag/userlist2 | 78 +++++++++++ Lehrer/pythonkurs/Dienstag/userlist3 | 82 ++++++++++++ Lehrer/pythonkurs/Dienstag/userlist4 | 85 ++++++++++++ Lehrer/pythonkurs/Dienstag/zahlen1 | 9 ++ Lehrer/pythonkurs/Dienstag/zahlen2 | 10 ++ Lehrer/pythonkurs/Dienstag/zahlen3 | 8 ++ Lehrer/pythonkurs/Dienstag/zahlen4 | 8 ++ Lehrer/pythonkurs/Dienstag/zahlen5 | 8 ++ Lehrer/pythonkurs/Dienstag/zahlen6 | 11 ++ Lehrer/pythonkurs/Dienstag/zahlen7 | 11 ++ Lehrer/pythonkurs/Dienstag/zahlen8 | 21 +++ Lehrer/pythonkurs/Dienstag/zahlen9 | 33 +++++ Lehrer/pythonkurs/Dienstag/zahlena | 36 +++++ Lehrer/pythonkurs/Dienstag/zahlenb | 45 +++++++ Lehrer/pythonkurs/Dienstag/zahlenc | 21 +++ .../pythonkurs/Donnerstag/.decorators.py.swp | Bin 0 -> 12288 bytes Lehrer/pythonkurs/Donnerstag/argv.py | 31 +++++ Lehrer/pythonkurs/Donnerstag/calc1 | 10 ++ Lehrer/pythonkurs/Donnerstag/calc2 | 10 ++ Lehrer/pythonkurs/Donnerstag/calc3 | 16 +++ Lehrer/pythonkurs/Donnerstag/calc4 | 15 +++ Lehrer/pythonkurs/Donnerstag/calc5 | 14 ++ Lehrer/pythonkurs/Donnerstag/calc6 | 21 +++ Lehrer/pythonkurs/Donnerstag/curry | 32 +++++ Lehrer/pythonkurs/Donnerstag/decorators.py | 30 +++++ Lehrer/pythonkurs/Donnerstag/fakultaet | 24 ++++ Lehrer/pythonkurs/Donnerstag/fibonacci1 | 15 +++ Lehrer/pythonkurs/Donnerstag/fibonacci1.count | 24 ++++ Lehrer/pythonkurs/Donnerstag/fibonacci2 | 21 +++ Lehrer/pythonkurs/Donnerstag/fibonacci3 | 31 +++++ Lehrer/pythonkurs/Donnerstag/fibonacci4 | 32 +++++ Lehrer/pythonkurs/Donnerstag/fibonacci5 | 28 ++++ Lehrer/pythonkurs/Donnerstag/goodies | 28 ++++ Lehrer/pythonkurs/Donnerstag/taxi | 14 ++ Lehrer/pythonkurs/Donnerstag/vectors.py | 100 ++++++++++++++ Lehrer/pythonkurs/Donnerstag/zip | 15 +++ Lehrer/pythonkurs/Donnerstag/zuweisung | 66 +++++++++ Lehrer/pythonkurs/Freitag/connect_db | 31 +++++ Lehrer/pythonkurs/Freitag/datetime_test | 13 ++ Lehrer/pythonkurs/Freitag/decorators.py | 46 +++++++ Lehrer/pythonkurs/Freitag/external_ip | 51 +++++++ Lehrer/pythonkurs/Freitag/fak | 14 ++ Lehrer/pythonkurs/Freitag/insert_host | 101 ++++++++++++++ Lehrer/pythonkurs/Freitag/insert_host2 | 106 +++++++++++++++ Lehrer/pythonkurs/Freitag/insert_host3 | 106 +++++++++++++++ Lehrer/pythonkurs/Freitag/insert_host4 | 126 ++++++++++++++++++ Lehrer/pythonkurs/Freitag/list_hosts | 52 ++++++++ Lehrer/pythonkurs/Freitag/list_hosts2 | 59 ++++++++ Lehrer/pythonkurs/Freitag/list_hosts3 | 53 ++++++++ Lehrer/pythonkurs/Freitag/mathematik.py | 17 +++ Lehrer/pythonkurs/Freitag/test_fak.py | 49 +++++++ Lehrer/pythonkurs/Mittwoch/argv.py | 35 +++++ Lehrer/pythonkurs/Mittwoch/cmdline | 8 ++ Lehrer/pythonkurs/Mittwoch/import1 | 10 ++ Lehrer/pythonkurs/Mittwoch/import2 | 11 ++ Lehrer/pythonkurs/Mittwoch/import3 | 18 +++ Lehrer/pythonkurs/Mittwoch/modulpath | 18 +++ Lehrer/pythonkurs/Mittwoch/modultest | 8 ++ Lehrer/pythonkurs/Mittwoch/print_ip | 66 +++++++++ Lehrer/pythonkurs/Mittwoch/userlist5 | 90 +++++++++++++ Lehrer/pythonkurs/Mittwoch/userlist6 | 86 ++++++++++++ Lehrer/pythonkurs/Mittwoch/userlist7 | 104 +++++++++++++++ Lehrer/pythonkurs/Mittwoch/userlist8 | 115 ++++++++++++++++ Lehrer/pythonkurs/Mittwoch/userlist9 | 118 ++++++++++++++++ Lehrer/pythonkurs/Mittwoch/utilities.py | 29 ++++ Lehrer/pythonkurs/Mittwoch/writefile | 17 +++ Lehrer/pythonkurs/Mittwoch/zahlena | 37 +++++ Lehrer/pythonkurs/Montag/contains1 | 18 +++ Lehrer/pythonkurs/Montag/contains2 | 24 ++++ Lehrer/pythonkurs/Montag/dict1 | 14 ++ Lehrer/pythonkurs/Montag/dict2 | 20 +++ Lehrer/pythonkurs/Montag/dict3 | 21 +++ Lehrer/pythonkurs/Montag/dict4 | 24 ++++ Lehrer/pythonkurs/Montag/dict5 | 28 ++++ Lehrer/pythonkurs/Montag/dict6 | 22 +++ Lehrer/pythonkurs/Montag/hello_world | 4 + Lehrer/pythonkurs/Montag/hello_world2 | 3 + Lehrer/pythonkurs/Montag/hello_world3 | 6 + Lehrer/pythonkurs/Montag/hello_world4 | 8 ++ Lehrer/pythonkurs/Montag/if | 29 ++++ Lehrer/pythonkurs/Montag/list1 | 17 +++ Lehrer/pythonkurs/Montag/list2 | 16 +++ Lehrer/pythonkurs/Montag/list3 | 8 ++ Lehrer/pythonkurs/Montag/list4 | 20 +++ Lehrer/pythonkurs/Montag/list5 | 9 ++ Lehrer/pythonkurs/Montag/list6 | 15 +++ Lehrer/pythonkurs/Montag/list7 | 16 +++ Lehrer/pythonkurs/Montag/list8 | 6 + Lehrer/pythonkurs/Montag/list9 | 9 ++ Lehrer/pythonkurs/Montag/lista | 12 ++ Lehrer/pythonkurs/Montag/print1 | 16 +++ Lehrer/pythonkurs/Montag/print1_version2.x | 19 +++ Lehrer/pythonkurs/Montag/print2 | 19 +++ Lehrer/pythonkurs/Montag/schachbrett1 | 16 +++ Lehrer/pythonkurs/Montag/schachbrett2 | 14 ++ Lehrer/pythonkurs/Montag/schachbrett3 | 16 +++ Lehrer/pythonkurs/Montag/schachbrett4 | 16 +++ Lehrer/pythonkurs/Montag/strings1 | 9 ++ Lehrer/pythonkurs/Montag/strings2 | 13 ++ Lehrer/pythonkurs/Montag/strings3 | 9 ++ Lehrer/pythonkurs/Montag/strings4 | 7 + Lehrer/pythonkurs/Montag/strings5 | 27 ++++ Lehrer/pythonkurs/Montag/strings6 | 13 ++ Lehrer/pythonkurs/Montag/strings7 | 16 +++ Lehrer/pythonkurs/Montag/testdict | 4 + Lehrer/pythonkurs/Montag/zahlen1 | 23 ++++ Mittwoch/User_modify.py | 66 ++++----- Mittwoch/__pycache__/argv.cpython-39.pyc | Bin Mittwoch/__pycache__/argv2.cpython-310.pyc | Bin 0 -> 482 bytes .../__pycache__/utilities.cpython-310.pyc | Bin 0 -> 890 bytes Mittwoch/__pycache__/utilities.cpython-39.pyc | Bin Mittwoch/argv2.py | 0 Mittwoch/command.py | 0 Mittwoch/find_ip.py | 0 Mittwoch/import.py | 0 Mittwoch/module_path.py | 0 Mittwoch/moduletest.py | 2 +- Mittwoch/utilities.py | 0 Mittwoch/write_file.py | 0 Module/argv.py | 0 Module/utilities.py | 0 Montag/Listen.py | 0 Montag/String_umwandelt_wortliste.py | 0 Montag/Stringtheorie.py | 0 Montag/dict.py | 0 Montag/hello-world.py | 0 Montag/if.py | 0 Montag/schachbrett.py | 0 Readme.md | 0 meine_test/Textdatei.txt | 4 + meine_test/read_file.py | 26 ++++ meine_test/server.db | Bin 0 -> 8192 bytes meine_test/shelve_test.py | 21 +++ meine_test/sqlite_test.py | 86 ++++++++++++ meine_test/sqllite_what.py | 18 +++ meine_test/testfile | Bin 0 -> 16384 bytes meine_test/write_Datei.py | 11 ++ pythonkurs.tar.gz | Bin test_db | Bin 0 -> 12288 bytes 184 files changed, 3725 insertions(+), 31 deletions(-) mode change 100644 => 100755 Dienstag/User_modify.py mode change 100644 => 100755 Dienstag/func.py mode change 100644 => 100755 Dienstag/func_summe.py mode change 100644 => 100755 Dienstag/nutzer.py mode change 100644 => 100755 Dienstag/zahlen.py mode change 100644 => 100755 Donnerstag/__pycache__/decorators.cpython-39.pyc mode change 100644 => 100755 Donnerstag/__pycache__/vectors.cpython-39.pyc mode change 100644 => 100755 Donnerstag/check_zip.py mode change 100644 => 100755 Donnerstag/curry.py mode change 100644 => 100755 Donnerstag/decorators.py mode change 100644 => 100755 Donnerstag/fakultät.py mode change 100644 => 100755 Donnerstag/fibonacci.py mode change 100644 => 100755 Donnerstag/taxi.py mode change 100644 => 100755 Donnerstag/temp_var.py mode change 100644 => 100755 Donnerstag/v_calc.py mode change 100644 => 100755 Donnerstag/vectors.py mode change 100644 => 100755 Freitag/__pycache__/decorators.cpython-39.pyc mode change 100644 => 100755 Freitag/__pycache__/mathematik.cpython-39.pyc mode change 100644 => 100755 Freitag/__pycache__/utilities.cpython-39.pyc mode change 100644 => 100755 Freitag/check_env.py mode change 100644 => 100755 Freitag/db_con.py mode change 100644 => 100755 Freitag/db_select.py mode change 100644 => 100755 Freitag/decorators.py mode change 100644 => 100755 Freitag/ext_ip.py mode change 100644 => 100755 Freitag/fakultät.py mode change 100644 => 100755 Freitag/fibonacci.py mode change 100644 => 100755 Freitag/insert_all.py mode change 100644 => 100755 Freitag/mathematik.py mode change 100644 => 100755 Freitag/test_fak.py mode change 100644 => 100755 Freitag/utilities.py create mode 100755 Lehrer/pythonkurs/Dienstag/function1 create mode 100755 Lehrer/pythonkurs/Dienstag/function2 create mode 100755 Lehrer/pythonkurs/Dienstag/function3 create mode 100755 Lehrer/pythonkurs/Dienstag/function3.1 create mode 100755 Lehrer/pythonkurs/Dienstag/function4 create mode 100755 Lehrer/pythonkurs/Dienstag/function5 create mode 100755 Lehrer/pythonkurs/Dienstag/function6 create mode 100755 Lehrer/pythonkurs/Dienstag/function7 create mode 100755 Lehrer/pythonkurs/Dienstag/function8 create mode 100755 Lehrer/pythonkurs/Dienstag/function9 create mode 100755 Lehrer/pythonkurs/Dienstag/functiona create mode 100755 Lehrer/pythonkurs/Dienstag/functionb create mode 100755 Lehrer/pythonkurs/Dienstag/functionc create mode 100755 Lehrer/pythonkurs/Dienstag/sorting1 create mode 100755 Lehrer/pythonkurs/Dienstag/userlist1 create mode 100755 Lehrer/pythonkurs/Dienstag/userlist2 create mode 100755 Lehrer/pythonkurs/Dienstag/userlist3 create mode 100755 Lehrer/pythonkurs/Dienstag/userlist4 create mode 100755 Lehrer/pythonkurs/Dienstag/zahlen1 create mode 100755 Lehrer/pythonkurs/Dienstag/zahlen2 create mode 100755 Lehrer/pythonkurs/Dienstag/zahlen3 create mode 100755 Lehrer/pythonkurs/Dienstag/zahlen4 create mode 100755 Lehrer/pythonkurs/Dienstag/zahlen5 create mode 100755 Lehrer/pythonkurs/Dienstag/zahlen6 create mode 100755 Lehrer/pythonkurs/Dienstag/zahlen7 create mode 100755 Lehrer/pythonkurs/Dienstag/zahlen8 create mode 100755 Lehrer/pythonkurs/Dienstag/zahlen9 create mode 100755 Lehrer/pythonkurs/Dienstag/zahlena create mode 100755 Lehrer/pythonkurs/Dienstag/zahlenb create mode 100755 Lehrer/pythonkurs/Dienstag/zahlenc create mode 100755 Lehrer/pythonkurs/Donnerstag/.decorators.py.swp create mode 100755 Lehrer/pythonkurs/Donnerstag/argv.py create mode 100755 Lehrer/pythonkurs/Donnerstag/calc1 create mode 100755 Lehrer/pythonkurs/Donnerstag/calc2 create mode 100755 Lehrer/pythonkurs/Donnerstag/calc3 create mode 100755 Lehrer/pythonkurs/Donnerstag/calc4 create mode 100755 Lehrer/pythonkurs/Donnerstag/calc5 create mode 100755 Lehrer/pythonkurs/Donnerstag/calc6 create mode 100755 Lehrer/pythonkurs/Donnerstag/curry create mode 100755 Lehrer/pythonkurs/Donnerstag/decorators.py create mode 100755 Lehrer/pythonkurs/Donnerstag/fakultaet create mode 100755 Lehrer/pythonkurs/Donnerstag/fibonacci1 create mode 100755 Lehrer/pythonkurs/Donnerstag/fibonacci1.count create mode 100755 Lehrer/pythonkurs/Donnerstag/fibonacci2 create mode 100755 Lehrer/pythonkurs/Donnerstag/fibonacci3 create mode 100755 Lehrer/pythonkurs/Donnerstag/fibonacci4 create mode 100755 Lehrer/pythonkurs/Donnerstag/fibonacci5 create mode 100755 Lehrer/pythonkurs/Donnerstag/goodies create mode 100755 Lehrer/pythonkurs/Donnerstag/taxi create mode 100755 Lehrer/pythonkurs/Donnerstag/vectors.py create mode 100755 Lehrer/pythonkurs/Donnerstag/zip create mode 100755 Lehrer/pythonkurs/Donnerstag/zuweisung create mode 100755 Lehrer/pythonkurs/Freitag/connect_db create mode 100755 Lehrer/pythonkurs/Freitag/datetime_test create mode 100755 Lehrer/pythonkurs/Freitag/decorators.py create mode 100755 Lehrer/pythonkurs/Freitag/external_ip create mode 100755 Lehrer/pythonkurs/Freitag/fak create mode 100755 Lehrer/pythonkurs/Freitag/insert_host create mode 100755 Lehrer/pythonkurs/Freitag/insert_host2 create mode 100755 Lehrer/pythonkurs/Freitag/insert_host3 create mode 100755 Lehrer/pythonkurs/Freitag/insert_host4 create mode 100755 Lehrer/pythonkurs/Freitag/list_hosts create mode 100755 Lehrer/pythonkurs/Freitag/list_hosts2 create mode 100755 Lehrer/pythonkurs/Freitag/list_hosts3 create mode 100755 Lehrer/pythonkurs/Freitag/mathematik.py create mode 100755 Lehrer/pythonkurs/Freitag/test_fak.py create mode 100755 Lehrer/pythonkurs/Mittwoch/argv.py create mode 100755 Lehrer/pythonkurs/Mittwoch/cmdline create mode 100755 Lehrer/pythonkurs/Mittwoch/import1 create mode 100755 Lehrer/pythonkurs/Mittwoch/import2 create mode 100755 Lehrer/pythonkurs/Mittwoch/import3 create mode 100755 Lehrer/pythonkurs/Mittwoch/modulpath create mode 100755 Lehrer/pythonkurs/Mittwoch/modultest create mode 100755 Lehrer/pythonkurs/Mittwoch/print_ip create mode 100755 Lehrer/pythonkurs/Mittwoch/userlist5 create mode 100755 Lehrer/pythonkurs/Mittwoch/userlist6 create mode 100755 Lehrer/pythonkurs/Mittwoch/userlist7 create mode 100755 Lehrer/pythonkurs/Mittwoch/userlist8 create mode 100755 Lehrer/pythonkurs/Mittwoch/userlist9 create mode 100755 Lehrer/pythonkurs/Mittwoch/utilities.py create mode 100755 Lehrer/pythonkurs/Mittwoch/writefile create mode 100755 Lehrer/pythonkurs/Mittwoch/zahlena create mode 100755 Lehrer/pythonkurs/Montag/contains1 create mode 100755 Lehrer/pythonkurs/Montag/contains2 create mode 100755 Lehrer/pythonkurs/Montag/dict1 create mode 100755 Lehrer/pythonkurs/Montag/dict2 create mode 100755 Lehrer/pythonkurs/Montag/dict3 create mode 100755 Lehrer/pythonkurs/Montag/dict4 create mode 100755 Lehrer/pythonkurs/Montag/dict5 create mode 100755 Lehrer/pythonkurs/Montag/dict6 create mode 100755 Lehrer/pythonkurs/Montag/hello_world create mode 100755 Lehrer/pythonkurs/Montag/hello_world2 create mode 100755 Lehrer/pythonkurs/Montag/hello_world3 create mode 100755 Lehrer/pythonkurs/Montag/hello_world4 create mode 100755 Lehrer/pythonkurs/Montag/if create mode 100755 Lehrer/pythonkurs/Montag/list1 create mode 100755 Lehrer/pythonkurs/Montag/list2 create mode 100755 Lehrer/pythonkurs/Montag/list3 create mode 100755 Lehrer/pythonkurs/Montag/list4 create mode 100755 Lehrer/pythonkurs/Montag/list5 create mode 100755 Lehrer/pythonkurs/Montag/list6 create mode 100755 Lehrer/pythonkurs/Montag/list7 create mode 100755 Lehrer/pythonkurs/Montag/list8 create mode 100755 Lehrer/pythonkurs/Montag/list9 create mode 100755 Lehrer/pythonkurs/Montag/lista create mode 100755 Lehrer/pythonkurs/Montag/print1 create mode 100755 Lehrer/pythonkurs/Montag/print1_version2.x create mode 100755 Lehrer/pythonkurs/Montag/print2 create mode 100755 Lehrer/pythonkurs/Montag/schachbrett1 create mode 100755 Lehrer/pythonkurs/Montag/schachbrett2 create mode 100755 Lehrer/pythonkurs/Montag/schachbrett3 create mode 100755 Lehrer/pythonkurs/Montag/schachbrett4 create mode 100755 Lehrer/pythonkurs/Montag/strings1 create mode 100755 Lehrer/pythonkurs/Montag/strings2 create mode 100755 Lehrer/pythonkurs/Montag/strings3 create mode 100755 Lehrer/pythonkurs/Montag/strings4 create mode 100755 Lehrer/pythonkurs/Montag/strings5 create mode 100755 Lehrer/pythonkurs/Montag/strings6 create mode 100755 Lehrer/pythonkurs/Montag/strings7 create mode 100755 Lehrer/pythonkurs/Montag/testdict create mode 100755 Lehrer/pythonkurs/Montag/zahlen1 mode change 100644 => 100755 Mittwoch/User_modify.py mode change 100644 => 100755 Mittwoch/__pycache__/argv.cpython-39.pyc create mode 100755 Mittwoch/__pycache__/argv2.cpython-310.pyc create mode 100755 Mittwoch/__pycache__/utilities.cpython-310.pyc mode change 100644 => 100755 Mittwoch/__pycache__/utilities.cpython-39.pyc mode change 100644 => 100755 Mittwoch/argv2.py mode change 100644 => 100755 Mittwoch/command.py mode change 100644 => 100755 Mittwoch/find_ip.py mode change 100644 => 100755 Mittwoch/import.py mode change 100644 => 100755 Mittwoch/module_path.py mode change 100644 => 100755 Mittwoch/moduletest.py mode change 100644 => 100755 Mittwoch/utilities.py mode change 100644 => 100755 Mittwoch/write_file.py mode change 100644 => 100755 Module/argv.py mode change 100644 => 100755 Module/utilities.py mode change 100644 => 100755 Montag/Listen.py mode change 100644 => 100755 Montag/String_umwandelt_wortliste.py mode change 100644 => 100755 Montag/Stringtheorie.py mode change 100644 => 100755 Montag/dict.py mode change 100644 => 100755 Montag/hello-world.py mode change 100644 => 100755 Montag/if.py mode change 100644 => 100755 Montag/schachbrett.py mode change 100644 => 100755 Readme.md create mode 100755 meine_test/Textdatei.txt create mode 100755 meine_test/read_file.py create mode 100755 meine_test/server.db create mode 100755 meine_test/shelve_test.py create mode 100755 meine_test/sqlite_test.py create mode 100755 meine_test/sqllite_what.py create mode 100755 meine_test/testfile create mode 100755 meine_test/write_Datei.py mode change 100644 => 100755 pythonkurs.tar.gz create mode 100755 test_db diff --git a/Dienstag/User_modify.py b/Dienstag/User_modify.py old mode 100644 new mode 100755 diff --git a/Dienstag/func.py b/Dienstag/func.py old mode 100644 new mode 100755 diff --git a/Dienstag/func_summe.py b/Dienstag/func_summe.py old mode 100644 new mode 100755 diff --git a/Dienstag/nutzer.py b/Dienstag/nutzer.py old mode 100644 new mode 100755 diff --git a/Dienstag/zahlen.py b/Dienstag/zahlen.py old mode 100644 new mode 100755 diff --git a/Donnerstag/__pycache__/decorators.cpython-39.pyc b/Donnerstag/__pycache__/decorators.cpython-39.pyc old mode 100644 new mode 100755 diff --git a/Donnerstag/__pycache__/vectors.cpython-39.pyc b/Donnerstag/__pycache__/vectors.cpython-39.pyc old mode 100644 new mode 100755 diff --git a/Donnerstag/check_zip.py b/Donnerstag/check_zip.py old mode 100644 new mode 100755 diff --git a/Donnerstag/curry.py b/Donnerstag/curry.py old mode 100644 new mode 100755 diff --git a/Donnerstag/decorators.py b/Donnerstag/decorators.py old mode 100644 new mode 100755 diff --git a/Donnerstag/fakultät.py b/Donnerstag/fakultät.py old mode 100644 new mode 100755 diff --git a/Donnerstag/fibonacci.py b/Donnerstag/fibonacci.py old mode 100644 new mode 100755 diff --git a/Donnerstag/taxi.py b/Donnerstag/taxi.py old mode 100644 new mode 100755 diff --git a/Donnerstag/temp_var.py b/Donnerstag/temp_var.py old mode 100644 new mode 100755 diff --git a/Donnerstag/v_calc.py b/Donnerstag/v_calc.py old mode 100644 new mode 100755 diff --git a/Donnerstag/vectors.py b/Donnerstag/vectors.py old mode 100644 new mode 100755 diff --git a/Freitag/__pycache__/decorators.cpython-39.pyc b/Freitag/__pycache__/decorators.cpython-39.pyc old mode 100644 new mode 100755 diff --git a/Freitag/__pycache__/mathematik.cpython-39.pyc b/Freitag/__pycache__/mathematik.cpython-39.pyc old mode 100644 new mode 100755 diff --git a/Freitag/__pycache__/utilities.cpython-39.pyc b/Freitag/__pycache__/utilities.cpython-39.pyc old mode 100644 new mode 100755 diff --git a/Freitag/check_env.py b/Freitag/check_env.py old mode 100644 new mode 100755 diff --git a/Freitag/db_con.py b/Freitag/db_con.py old mode 100644 new mode 100755 diff --git a/Freitag/db_select.py b/Freitag/db_select.py old mode 100644 new mode 100755 diff --git a/Freitag/decorators.py b/Freitag/decorators.py old mode 100644 new mode 100755 diff --git a/Freitag/ext_ip.py b/Freitag/ext_ip.py old mode 100644 new mode 100755 diff --git a/Freitag/fakultät.py b/Freitag/fakultät.py old mode 100644 new mode 100755 diff --git a/Freitag/fibonacci.py b/Freitag/fibonacci.py old mode 100644 new mode 100755 diff --git a/Freitag/insert_all.py b/Freitag/insert_all.py old mode 100644 new mode 100755 diff --git a/Freitag/mathematik.py b/Freitag/mathematik.py old mode 100644 new mode 100755 diff --git a/Freitag/test_fak.py b/Freitag/test_fak.py old mode 100644 new mode 100755 diff --git a/Freitag/utilities.py b/Freitag/utilities.py old mode 100644 new mode 100755 diff --git a/Lehrer/pythonkurs/Dienstag/function1 b/Lehrer/pythonkurs/Dienstag/function1 new file mode 100755 index 0000000..06f47bc --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/function1 @@ -0,0 +1,8 @@ +#! /usr/bin/env python3 + +def myprint(): + print("Ausgabe aus einer Funktion") + print("-" * 30) + + +myprint() diff --git a/Lehrer/pythonkurs/Dienstag/function2 b/Lehrer/pythonkurs/Dienstag/function2 new file mode 100755 index 0000000..111ea73 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/function2 @@ -0,0 +1,8 @@ +#! /usr/bin/env python3 + +def myprint(text, amount): + print(text) + print("-" * amount) + + +myprint("Ausgabe aus Funktion", 25) diff --git a/Lehrer/pythonkurs/Dienstag/function3 b/Lehrer/pythonkurs/Dienstag/function3 new file mode 100755 index 0000000..0153759 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/function3 @@ -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) diff --git a/Lehrer/pythonkurs/Dienstag/function3.1 b/Lehrer/pythonkurs/Dienstag/function3.1 new file mode 100755 index 0000000..05828ab --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/function3.1 @@ -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) diff --git a/Lehrer/pythonkurs/Dienstag/function4 b/Lehrer/pythonkurs/Dienstag/function4 new file mode 100755 index 0000000..0a3d151 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/function4 @@ -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") diff --git a/Lehrer/pythonkurs/Dienstag/function5 b/Lehrer/pythonkurs/Dienstag/function5 new file mode 100755 index 0000000..b5a5f12 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/function5 @@ -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)) diff --git a/Lehrer/pythonkurs/Dienstag/function6 b/Lehrer/pythonkurs/Dienstag/function6 new file mode 100755 index 0000000..86d4f62 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/function6 @@ -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) diff --git a/Lehrer/pythonkurs/Dienstag/function7 b/Lehrer/pythonkurs/Dienstag/function7 new file mode 100755 index 0000000..e8efebd --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/function7 @@ -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) diff --git a/Lehrer/pythonkurs/Dienstag/function8 b/Lehrer/pythonkurs/Dienstag/function8 new file mode 100755 index 0000000..6161b34 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/function8 @@ -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))) diff --git a/Lehrer/pythonkurs/Dienstag/function9 b/Lehrer/pythonkurs/Dienstag/function9 new file mode 100755 index 0000000..b8a4443 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/function9 @@ -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)) diff --git a/Lehrer/pythonkurs/Dienstag/functiona b/Lehrer/pythonkurs/Dienstag/functiona new file mode 100755 index 0000000..e43d190 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/functiona @@ -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")) diff --git a/Lehrer/pythonkurs/Dienstag/functionb b/Lehrer/pythonkurs/Dienstag/functionb new file mode 100755 index 0000000..68104dd --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/functionb @@ -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)) diff --git a/Lehrer/pythonkurs/Dienstag/functionc b/Lehrer/pythonkurs/Dienstag/functionc new file mode 100755 index 0000000..257ece1 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/functionc @@ -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)) diff --git a/Lehrer/pythonkurs/Dienstag/sorting1 b/Lehrer/pythonkurs/Dienstag/sorting1 new file mode 100755 index 0000000..3e93426 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/sorting1 @@ -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) diff --git a/Lehrer/pythonkurs/Dienstag/userlist1 b/Lehrer/pythonkurs/Dienstag/userlist1 new file mode 100755 index 0000000..3c20042 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/userlist1 @@ -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() diff --git a/Lehrer/pythonkurs/Dienstag/userlist2 b/Lehrer/pythonkurs/Dienstag/userlist2 new file mode 100755 index 0000000..15f23c0 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/userlist2 @@ -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() diff --git a/Lehrer/pythonkurs/Dienstag/userlist3 b/Lehrer/pythonkurs/Dienstag/userlist3 new file mode 100755 index 0000000..c2fb946 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/userlist3 @@ -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() diff --git a/Lehrer/pythonkurs/Dienstag/userlist4 b/Lehrer/pythonkurs/Dienstag/userlist4 new file mode 100755 index 0000000..1fbdff7 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/userlist4 @@ -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() diff --git a/Lehrer/pythonkurs/Dienstag/zahlen1 b/Lehrer/pythonkurs/Dienstag/zahlen1 new file mode 100755 index 0000000..19b55cf --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/zahlen1 @@ -0,0 +1,9 @@ +#! /usr/bin/env python3 + +zahlen = [] +value = 1 +for c in "abcdefghijk": + zahlen.append(value) + value += 1 + +print(zahlen) diff --git a/Lehrer/pythonkurs/Dienstag/zahlen2 b/Lehrer/pythonkurs/Dienstag/zahlen2 new file mode 100755 index 0000000..86ce305 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/zahlen2 @@ -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) diff --git a/Lehrer/pythonkurs/Dienstag/zahlen3 b/Lehrer/pythonkurs/Dienstag/zahlen3 new file mode 100755 index 0000000..08d1912 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/zahlen3 @@ -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) diff --git a/Lehrer/pythonkurs/Dienstag/zahlen4 b/Lehrer/pythonkurs/Dienstag/zahlen4 new file mode 100755 index 0000000..960e35e --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/zahlen4 @@ -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) diff --git a/Lehrer/pythonkurs/Dienstag/zahlen5 b/Lehrer/pythonkurs/Dienstag/zahlen5 new file mode 100755 index 0000000..05f2818 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/zahlen5 @@ -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) diff --git a/Lehrer/pythonkurs/Dienstag/zahlen6 b/Lehrer/pythonkurs/Dienstag/zahlen6 new file mode 100755 index 0000000..952de84 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/zahlen6 @@ -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) diff --git a/Lehrer/pythonkurs/Dienstag/zahlen7 b/Lehrer/pythonkurs/Dienstag/zahlen7 new file mode 100755 index 0000000..87cbd12 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/zahlen7 @@ -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]) diff --git a/Lehrer/pythonkurs/Dienstag/zahlen8 b/Lehrer/pythonkurs/Dienstag/zahlen8 new file mode 100755 index 0000000..4648f1b --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/zahlen8 @@ -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) diff --git a/Lehrer/pythonkurs/Dienstag/zahlen9 b/Lehrer/pythonkurs/Dienstag/zahlen9 new file mode 100755 index 0000000..4a0bc64 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/zahlen9 @@ -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))) diff --git a/Lehrer/pythonkurs/Dienstag/zahlena b/Lehrer/pythonkurs/Dienstag/zahlena new file mode 100755 index 0000000..566444b --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/zahlena @@ -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)))) diff --git a/Lehrer/pythonkurs/Dienstag/zahlenb b/Lehrer/pythonkurs/Dienstag/zahlenb new file mode 100755 index 0000000..6fbbb2b --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/zahlenb @@ -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)) diff --git a/Lehrer/pythonkurs/Dienstag/zahlenc b/Lehrer/pythonkurs/Dienstag/zahlenc new file mode 100755 index 0000000..469a663 --- /dev/null +++ b/Lehrer/pythonkurs/Dienstag/zahlenc @@ -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)))) diff --git a/Lehrer/pythonkurs/Donnerstag/.decorators.py.swp b/Lehrer/pythonkurs/Donnerstag/.decorators.py.swp new file mode 100755 index 0000000000000000000000000000000000000000..c975bbf9f81724918bed3f9f34a7ce09ddeedad0 GIT binary patch literal 12288 zcmeI2KW`H;6u?~sod_Tp*wAYtK^jV$76ug2p;A>*Az(l-fS_{jUhdpG*^$rJl2*{I zW#JnzAa*_gJ0Ad6X80aFU+<#Oe+-=>Jxf3N&d>IH{&|Wnz0QlZ$8f*BD5zZ#V(;^A z@MdjV)UOMnbGMCl;hqnj*0gchGbZ`p%=guX^D9Pcw3(C9e29Uu(ixkz2gB2{aEuMG zfwLK?iMxvn9luATJ_FaTK0n)byqXQL0XDz}*Z><~18jf|uz`s(;09A-mnuG2R(+%F zrw;YyD|c*w4X^<=zy{a=8(;%$fDNz#HoykhzyunQp%A|=(zpH^6;I#)tKa{BE(`IS z_(}XAz7ijan23lOVw$)>e7_{bC*lLKPwWwf=o1f#2Sk&&McgE6#ChTy<@`eI6FWpv z!vs3ylGy+oU;}J`4X^<=zy{a=8(;%R4M5ojGRuU2#a~`8lD)9!VeriKpFq{9L3C0hUldI%e6&rrK4h% z(hjYbX;smBr~>z@n(}&Nr~%7qG1IBdu0L1el+l^RK3de{svS*P?>|e&TSn~X?WV(z{Jf#BDE&lF 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:]) diff --git a/Lehrer/pythonkurs/Donnerstag/calc1 b/Lehrer/pythonkurs/Donnerstag/calc1 new file mode 100755 index 0000000..32dde58 --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/calc1 @@ -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))) diff --git a/Lehrer/pythonkurs/Donnerstag/calc2 b/Lehrer/pythonkurs/Donnerstag/calc2 new file mode 100755 index 0000000..e735941 --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/calc2 @@ -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) diff --git a/Lehrer/pythonkurs/Donnerstag/calc3 b/Lehrer/pythonkurs/Donnerstag/calc3 new file mode 100755 index 0000000..ba033d9 --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/calc3 @@ -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") diff --git a/Lehrer/pythonkurs/Donnerstag/calc4 b/Lehrer/pythonkurs/Donnerstag/calc4 new file mode 100755 index 0000000..d4b07e0 --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/calc4 @@ -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)) diff --git a/Lehrer/pythonkurs/Donnerstag/calc5 b/Lehrer/pythonkurs/Donnerstag/calc5 new file mode 100755 index 0000000..eb9a04d --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/calc5 @@ -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()) diff --git a/Lehrer/pythonkurs/Donnerstag/calc6 b/Lehrer/pythonkurs/Donnerstag/calc6 new file mode 100755 index 0000000..01bb4da --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/calc6 @@ -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" diff --git a/Lehrer/pythonkurs/Donnerstag/curry b/Lehrer/pythonkurs/Donnerstag/curry new file mode 100755 index 0000000..c72853a --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/curry @@ -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)) diff --git a/Lehrer/pythonkurs/Donnerstag/decorators.py b/Lehrer/pythonkurs/Donnerstag/decorators.py new file mode 100755 index 0000000..c34e581 --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/decorators.py @@ -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 diff --git a/Lehrer/pythonkurs/Donnerstag/fakultaet b/Lehrer/pythonkurs/Donnerstag/fakultaet new file mode 100755 index 0000000..c345047 --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/fakultaet @@ -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() +@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) diff --git a/Lehrer/pythonkurs/Donnerstag/fibonacci1 b/Lehrer/pythonkurs/Donnerstag/fibonacci1 new file mode 100755 index 0000000..cce669e --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/fibonacci1 @@ -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)) diff --git a/Lehrer/pythonkurs/Donnerstag/fibonacci1.count b/Lehrer/pythonkurs/Donnerstag/fibonacci1.count new file mode 100755 index 0000000..cedb554 --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/fibonacci1.count @@ -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)) diff --git a/Lehrer/pythonkurs/Donnerstag/fibonacci2 b/Lehrer/pythonkurs/Donnerstag/fibonacci2 new file mode 100755 index 0000000..d57249f --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/fibonacci2 @@ -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)) diff --git a/Lehrer/pythonkurs/Donnerstag/fibonacci3 b/Lehrer/pythonkurs/Donnerstag/fibonacci3 new file mode 100755 index 0000000..ad7ad26 --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/fibonacci3 @@ -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)]) diff --git a/Lehrer/pythonkurs/Donnerstag/fibonacci4 b/Lehrer/pythonkurs/Donnerstag/fibonacci4 new file mode 100755 index 0000000..90e6b5d --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/fibonacci4 @@ -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)]) diff --git a/Lehrer/pythonkurs/Donnerstag/fibonacci5 b/Lehrer/pythonkurs/Donnerstag/fibonacci5 new file mode 100755 index 0000000..1168e33 --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/fibonacci5 @@ -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)]) diff --git a/Lehrer/pythonkurs/Donnerstag/goodies b/Lehrer/pythonkurs/Donnerstag/goodies new file mode 100755 index 0000000..5f45d29 --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/goodies @@ -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)) diff --git a/Lehrer/pythonkurs/Donnerstag/taxi b/Lehrer/pythonkurs/Donnerstag/taxi new file mode 100755 index 0000000..0efd766 --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/taxi @@ -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" diff --git a/Lehrer/pythonkurs/Donnerstag/vectors.py b/Lehrer/pythonkurs/Donnerstag/vectors.py new file mode 100755 index 0000000..0c8a35f --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/vectors.py @@ -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) + diff --git a/Lehrer/pythonkurs/Donnerstag/zip b/Lehrer/pythonkurs/Donnerstag/zip new file mode 100755 index 0000000..cfd2ecb --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/zip @@ -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) diff --git a/Lehrer/pythonkurs/Donnerstag/zuweisung b/Lehrer/pythonkurs/Donnerstag/zuweisung new file mode 100755 index 0000000..65fe9e3 --- /dev/null +++ b/Lehrer/pythonkurs/Donnerstag/zuweisung @@ -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) diff --git a/Lehrer/pythonkurs/Freitag/connect_db b/Lehrer/pythonkurs/Freitag/connect_db new file mode 100755 index 0000000..84257dc --- /dev/null +++ b/Lehrer/pythonkurs/Freitag/connect_db @@ -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) diff --git a/Lehrer/pythonkurs/Freitag/datetime_test b/Lehrer/pythonkurs/Freitag/datetime_test new file mode 100755 index 0000000..4a29ecc --- /dev/null +++ b/Lehrer/pythonkurs/Freitag/datetime_test @@ -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()) diff --git a/Lehrer/pythonkurs/Freitag/decorators.py b/Lehrer/pythonkurs/Freitag/decorators.py new file mode 100755 index 0000000..63a88c2 --- /dev/null +++ b/Lehrer/pythonkurs/Freitag/decorators.py @@ -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 = + 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 diff --git a/Lehrer/pythonkurs/Freitag/external_ip b/Lehrer/pythonkurs/Freitag/external_ip new file mode 100755 index 0000000..62005b9 --- /dev/null +++ b/Lehrer/pythonkurs/Freitag/external_ip @@ -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) diff --git a/Lehrer/pythonkurs/Freitag/fak b/Lehrer/pythonkurs/Freitag/fak new file mode 100755 index 0000000..3ddc308 --- /dev/null +++ b/Lehrer/pythonkurs/Freitag/fak @@ -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)) diff --git a/Lehrer/pythonkurs/Freitag/insert_host b/Lehrer/pythonkurs/Freitag/insert_host new file mode 100755 index 0000000..abf7a6c --- /dev/null +++ b/Lehrer/pythonkurs/Freitag/insert_host @@ -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) diff --git a/Lehrer/pythonkurs/Freitag/insert_host2 b/Lehrer/pythonkurs/Freitag/insert_host2 new file mode 100755 index 0000000..f4610bd --- /dev/null +++ b/Lehrer/pythonkurs/Freitag/insert_host2 @@ -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) diff --git a/Lehrer/pythonkurs/Freitag/insert_host3 b/Lehrer/pythonkurs/Freitag/insert_host3 new file mode 100755 index 0000000..b19e47b --- /dev/null +++ b/Lehrer/pythonkurs/Freitag/insert_host3 @@ -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) diff --git a/Lehrer/pythonkurs/Freitag/insert_host4 b/Lehrer/pythonkurs/Freitag/insert_host4 new file mode 100755 index 0000000..b077d51 --- /dev/null +++ b/Lehrer/pythonkurs/Freitag/insert_host4 @@ -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) diff --git a/Lehrer/pythonkurs/Freitag/list_hosts b/Lehrer/pythonkurs/Freitag/list_hosts new file mode 100755 index 0000000..5b0ad17 --- /dev/null +++ b/Lehrer/pythonkurs/Freitag/list_hosts @@ -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) diff --git a/Lehrer/pythonkurs/Freitag/list_hosts2 b/Lehrer/pythonkurs/Freitag/list_hosts2 new file mode 100755 index 0000000..bcacd7b --- /dev/null +++ b/Lehrer/pythonkurs/Freitag/list_hosts2 @@ -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) diff --git a/Lehrer/pythonkurs/Freitag/list_hosts3 b/Lehrer/pythonkurs/Freitag/list_hosts3 new file mode 100755 index 0000000..3742461 --- /dev/null +++ b/Lehrer/pythonkurs/Freitag/list_hosts3 @@ -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) diff --git a/Lehrer/pythonkurs/Freitag/mathematik.py b/Lehrer/pythonkurs/Freitag/mathematik.py new file mode 100755 index 0000000..b56afdd --- /dev/null +++ b/Lehrer/pythonkurs/Freitag/mathematik.py @@ -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) diff --git a/Lehrer/pythonkurs/Freitag/test_fak.py b/Lehrer/pythonkurs/Freitag/test_fak.py new file mode 100755 index 0000000..9aae19b --- /dev/null +++ b/Lehrer/pythonkurs/Freitag/test_fak.py @@ -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() diff --git a/Lehrer/pythonkurs/Mittwoch/argv.py b/Lehrer/pythonkurs/Mittwoch/argv.py new file mode 100755 index 0000000..2e1f04a --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/argv.py @@ -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:]) diff --git a/Lehrer/pythonkurs/Mittwoch/cmdline b/Lehrer/pythonkurs/Mittwoch/cmdline new file mode 100755 index 0000000..1b500a7 --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/cmdline @@ -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:]) diff --git a/Lehrer/pythonkurs/Mittwoch/import1 b/Lehrer/pythonkurs/Mittwoch/import1 new file mode 100755 index 0000000..636f0bf --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/import1 @@ -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) diff --git a/Lehrer/pythonkurs/Mittwoch/import2 b/Lehrer/pythonkurs/Mittwoch/import2 new file mode 100755 index 0000000..febe1fa --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/import2 @@ -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) diff --git a/Lehrer/pythonkurs/Mittwoch/import3 b/Lehrer/pythonkurs/Mittwoch/import3 new file mode 100755 index 0000000..dc76fcd --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/import3 @@ -0,0 +1,18 @@ +#! /usr/bin/env python3 + +# Nur Bezeichner pprint aus Modul pprint importieren +from pprint import pprint as prettyprint +import pprint + +import sys as pysys + + +def pprint(*args): + print("Not yet implemented") + + +data = dict(userlist=['nutzer01', 'nutzer02', 'nutzer03', + 'nutzer04', 'nutzer05', 'nutzer06'], + location="Linuxhotel") + +prettyprint(data) diff --git a/Lehrer/pythonkurs/Mittwoch/modulpath b/Lehrer/pythonkurs/Mittwoch/modulpath new file mode 100755 index 0000000..8d42e81 --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/modulpath @@ -0,0 +1,18 @@ +#! /usr/bin/env python3 + +import sys + +# Umgebungsvariable PYTHONPATH wird verwendet, falls vorhanden +# PYTHONPATH=p1:p2:p2 ./modulpath +# oder +# PYTHONPATH=p1:p2:p2 +# export PYTHONPATH +# ./modulpath + +# Eigenes Modulverzeichnis hinzufuegen +sys.path.insert(0, '/opt/project/python3') + +print("Verzeichnisse mit Modulen:") + +for path in sys.path: + print(" ", path) diff --git a/Lehrer/pythonkurs/Mittwoch/modultest b/Lehrer/pythonkurs/Mittwoch/modultest new file mode 100755 index 0000000..9190158 --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/modultest @@ -0,0 +1,8 @@ +#! /usr/bin/env python3 + +import argv +from argv import argv_value + +print("Wert von -o :", argv_value('-o')) +# Unorthodoxer Zugriff auf Modul sys mittels Modul argv +print("Kommandozeile :", argv.sys.argv[1:]) diff --git a/Lehrer/pythonkurs/Mittwoch/print_ip b/Lehrer/pythonkurs/Mittwoch/print_ip new file mode 100755 index 0000000..3d852e1 --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/print_ip @@ -0,0 +1,66 @@ +#! /usr/bin/env python3 + +import os +import sys +import re + +from utilities import hide_exception + + +def read_from_command(command: str) -> list: + # command = "tar cf /tmp/backup.tar ." + # ret = os.system(command) + # ret = [8 Bit Exit code] + [8 Bit Flags] + # exit_code = ret >> 8 + + try: + with os.popen(command, 'r') as pipe: + return [l.rstrip() for l in pipe.readlines()] + except OSError: + print("Kann Programm nicht auslesen", file=sys.stderr) + # zur Sicherheit auch hier eine Liste zurueckgeben + return [] + + +def extract_ip(lines: list) -> list: + # [0-9] 1 Zeichen aus der Gruppe 0 bis 9 (\d) + # regex{1,3} regex matcht 1 bis 3 mal + # \. 1 echter Punkt + # . 1 beliebiges Zeichen + # regex? regex match 0 oder 1 mal + # regex+ regex match 1 mal oder beliebig oft + # regex* regex match 0 mal oder beliebig oft + # regex{3} regex match exakt 3 mal + # (regex) Gruppierung des Teil-Ausdrucks + # z.B. fuer Quantifizierung ?, +, *, {} + # PLUS als Nebeneffekt werden Variablen erzeugt + # ^ Anfang der Zeile + # $ Ende der Zeile + # .* Beliebig viele beliebige Zeichen (so viel wie geht) + # .*? Beliebig viele beliebige Zeichen, non-greedy + # [:space:] 1 Zeichen aus der Gruppe Spaces + # \s 1 Whitespace (Space, Tab) + regex = r'.*inet\s(([0-9]{1,3}\.){3}[0-9]{1,3})' + addresses = [] + + for line in lines: + match = re.match(regex, line) + if match: + #print(line) + #print("Gesamte IP:", match.group(1)) + #print("3. Oktett :", match.group(2)) + #print("-" * 20) + addresses.append(match.group(1)) + # Mehrfachzuweisung aller gefundener Gruppen + # ip, dummy = match.groups() + + return addresses + + +def main(): + lines = read_from_command("ip address show") + local_ips = extract_ip(lines) + print("Aktuelle Adressen:", local_ips) + + +hide_exception(main) diff --git a/Lehrer/pythonkurs/Mittwoch/userlist5 b/Lehrer/pythonkurs/Mittwoch/userlist5 new file mode 100755 index 0000000..ae5144c --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/userlist5 @@ -0,0 +1,90 @@ +#! /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): + userlen = 0 + # Extra-Schleife zum Berechnen der maximalen Breite des Usernames + for user in userlist: + if len(user['username']) > userlen: + userlen = len(user['username']) + + for user in sorted(userlist, key=lambda e: e['uid']): + print("{uid:5} {username:{width}} {realname}".format(width=userlen, **user)) + + +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() diff --git a/Lehrer/pythonkurs/Mittwoch/userlist6 b/Lehrer/pythonkurs/Mittwoch/userlist6 new file mode 100755 index 0000000..3e18ee6 --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/userlist6 @@ -0,0 +1,86 @@ +#! /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): + userlen = max(map(lambda u: len(u['username']), userlist)) + + for user in sorted(userlist, key=lambda e: e['uid']): + print("{uid:5} {username:{width}} {realname}".format(width=userlen, **user)) + + +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() diff --git a/Lehrer/pythonkurs/Mittwoch/userlist7 b/Lehrer/pythonkurs/Mittwoch/userlist7 new file mode 100755 index 0000000..e97ca1b --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/userlist7 @@ -0,0 +1,104 @@ +#! /usr/bin/env python3 + +from pprint import pprint + +# from argv import argv_value +import argv + + +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_to_file(userlist): + userlen = max(map(lambda u: len(u['username']), userlist)) + with open('/tmp/userlist.txt', 'w') as outfile: + for user in userlist: + print("{uid:5} {username:{width}} {realname}".format( + width=userlen, **user), + file=outfile) + + +def print_userlist_sorted_by_uid(userlist): + userlen = max(map(lambda u: len(u['username']), userlist)) + + for user in sorted(userlist, key=lambda e: e['uid']): + print("{uid:5} {username:{width}} {realname}".format(width=userlen, **user)) + + +def main(): + # Dictionary mit Ausgabe-Funktionen als Referenz + output_functions = { + 'pprint': pprint, + 'logger': print_to_file, + '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'] + outfunc = output_functions[argv.argv_value('-o', 'uid')] + + lines = read_file("/etc/passwd") + userlist = build_userlist(lines) + # print(userlist) # Kontrollausgabe + outfunc(userlist) + + +main() diff --git a/Lehrer/pythonkurs/Mittwoch/userlist8 b/Lehrer/pythonkurs/Mittwoch/userlist8 new file mode 100755 index 0000000..6bd22b1 --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/userlist8 @@ -0,0 +1,115 @@ +#! /usr/bin/env python3 + +import sys +from pprint import pprint + +# from argv import argv_value +import argv + + +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_to_file(userlist): + userlen = max(map(lambda u: len(u['username']), userlist)) + try: + with open('/etc/userlist.txt', 'w') as outfile: + for user in userlist: + print("{uid:5} {username:{width}} {realname}".format( + width=userlen, **user), + file=outfile) + # Alle ImportError schlicht ignorieren, nicht einmal eine Meldung ausgeben + except ImportError: + pass + except OSError as e: + print("Kann Datei nicht schreiben,", e, file=sys.stderr) + else: + print("Wird ausgefuehrt, wenn keine Exception ausgeloest wurde.") + finally: + print("Wird immer durchlaufen, unabhaengig von ausgeloesten Exceptions") + + +def print_userlist_sorted_by_uid(userlist): + userlen = max(map(lambda u: len(u['username']), userlist)) + + for user in sorted(userlist, key=lambda e: e['uid']): + print("{uid:5} {username:{width}} {realname}".format(width=userlen, **user)) + + +def main(): + # Dictionary mit Ausgabe-Funktionen als Referenz + output_functions = { + 'pprint': pprint, + 'logger': print_to_file, + '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'] + outfunc = output_functions[argv.argv_value('-o', 'uid')] + + lines = read_file("/etc/passwd") + userlist = build_userlist(lines) + # print(userlist) # Kontrollausgabe + outfunc(userlist) + + +main() diff --git a/Lehrer/pythonkurs/Mittwoch/userlist9 b/Lehrer/pythonkurs/Mittwoch/userlist9 new file mode 100755 index 0000000..449de27 --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/userlist9 @@ -0,0 +1,118 @@ +#! /usr/bin/env python3 + +import sys +from pprint import pprint + +# from argv import argv_value +import argv +from utilities import hide_exception + + +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_to_file(userlist): + userlen = max(map(lambda u: len(u['username']), userlist)) + try: + with open('/etc/userlist.txt', 'w') as outfile: + for user in userlist: + print("{uid:5} {username:{width}} {realname}".format( + width=userlen, **user), + file=outfile) + # Alle ImportError schlicht ignorieren, nicht einmal eine Meldung ausgeben + except ImportError: + pass +# Dieser Teil ist auskommentiert, damit hide_exception ueberhaupt +# eine Exception zum Verarbeiten abbekommt +# except OSError as e: +# print("Kann Datei nicht schreiben,", e, file=sys.stderr) + else: + print("Wird ausgefuehrt, wenn keine Exception ausgeloest wurde.") + finally: + print("Wird immer durchlaufen, unabhaengig von ausgeloesten Exceptions") + + +def print_userlist_sorted_by_uid(userlist): + userlen = max(map(lambda u: len(u['username']), userlist)) + + for user in sorted(userlist, key=lambda e: e['uid']): + print("{uid:5} {username:{width}} {realname}".format(width=userlen, **user)) + + +def main(): + # Dictionary mit Ausgabe-Funktionen als Referenz + output_functions = { + 'pprint': pprint, + 'logger': print_to_file, + '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'] + outfunc = output_functions[argv.argv_value('-o', 'uid')] + + lines = read_file("/etc/passwd") + userlist = build_userlist(lines) + # print(userlist) # Kontrollausgabe + outfunc(userlist) + + +hide_exception(main) diff --git a/Lehrer/pythonkurs/Mittwoch/utilities.py b/Lehrer/pythonkurs/Mittwoch/utilities.py new file mode 100755 index 0000000..4398f4c --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/utilities.py @@ -0,0 +1,29 @@ +""" +Miscellaneous utilities +""" + +import sys +from traceback import format_tb +# oder print_tb(traceback, file=) + + +def hide_exception(func): + try: + return func() + except Exception as e: + name = type(e).__name__ + text = str(e) + traceback = ''.join(format_tb(e.__traceback__)) + if '-V' in sys.argv or '--with-exception' in sys.argv: + # Fuer Faule, einfach existierende Exception weiterleiten + # raise + print("Traceback:\n", traceback, sep='', file=sys.stderr) + print("{name}: {text}".format(name=name, text=text), file=sys.stderr) + else: + print("Interner Fehler,", e) + # TODO: Exception-Informationen in Logdatei schreiben + + +if __name__ == '__main__': + print("from utilities import hide_exception") + print("hide_exception(main)") diff --git a/Lehrer/pythonkurs/Mittwoch/writefile b/Lehrer/pythonkurs/Mittwoch/writefile new file mode 100755 index 0000000..ce9d125 --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/writefile @@ -0,0 +1,17 @@ +#! /usr/bin/env python3 + +def write_into_file(path, lines): + # Mode r=read, w=write, a=append + with open(path, 'w') as outfile: + # Python2.x: outfile.write(string + '\n') + # v2 und v3: outfile.writelines(map(lambda s: s+'\n', lines)) + # outfile.writelines(f'{l}\n' for l in lines) + # outfile.writelines(l+'\n' for l in lines) + for line in lines: + print(line, file=outfile) + + +lines = [] +lines.append("Das ist eine Zeile einfacher Text") +lines.append("Zur Sicherheit noch eine weitere Zeile") +write_into_file("/tmp/test.txt", lines) diff --git a/Lehrer/pythonkurs/Mittwoch/zahlena b/Lehrer/pythonkurs/Mittwoch/zahlena new file mode 100755 index 0000000..efdd883 --- /dev/null +++ b/Lehrer/pythonkurs/Mittwoch/zahlena @@ -0,0 +1,37 @@ +#! /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)))) +# TODO: Nur 2 Nachkommastellen! diff --git a/Lehrer/pythonkurs/Montag/contains1 b/Lehrer/pythonkurs/Montag/contains1 new file mode 100755 index 0000000..baf5a07 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/contains1 @@ -0,0 +1,18 @@ +#! /usr/bin/env python3 + +string = "Removes a key-value pair" + +print("Kommt Wort 'value' im String vor?", 'value' in string) +print("Kommt Wort 'value' im String vor?", "value" in string) + +mlist = ['Quatsch', 'Liste'] + +print("Kommt Wert 'Quatsch' in der Liste vor?", 'Quatsch' in mlist) +print("Kommt Wert 'Quatsch' in der Liste vor?", "Quatsch" in mlist) + +mydict = {'hostname': 'notebook14', 'address': '192.168.1.214', 'maker': 'Lenovo', 'type': 'T530', 'ramsize': 16, 'ssd': True} + +print("Kommt Key 'hostname' im Dictionary vor?", 'hostname' in mydict) +print("Kommt Key 'hostname' im Dictionary vor?", "hostname" in mydict) + + diff --git a/Lehrer/pythonkurs/Montag/contains2 b/Lehrer/pythonkurs/Montag/contains2 new file mode 100755 index 0000000..e443278 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/contains2 @@ -0,0 +1,24 @@ +#! /usr/bin/env python3 + +string = "Removes a key-value pair" + +print("Kommt Wort 'value' im String vor?", 'value' in string) +print("Kommt Wort 'value' im String vor?", "value" in string) + +mlist = ['Quatsch', 'Liste'] + +print("Kommt Wert 'Quatsch' in der Liste vor?", 'Quatsch' in mlist) +print("Kommt Wert 'Quatsch' in der Liste vor?", "Quatsch" in mlist) + +mydict = {'hostname': 'notebook14', + 'address': '192.168.1.214', + 'maker': 'Lenovo', + 'type': 'T530', + 'ramsize': 16, + 'ssd': True, + } + +print("Kommt Key 'hostname' im Dictionary vor?", 'hostname' in mydict) +print("Kommt Key 'hostname' im Dictionary vor?", "hostname" in mydict) + + diff --git a/Lehrer/pythonkurs/Montag/dict1 b/Lehrer/pythonkurs/Montag/dict1 new file mode 100755 index 0000000..d87cec1 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/dict1 @@ -0,0 +1,14 @@ +#! /usr/bin/env python3 + +mydict = {} +print("Leeres Dictionary:", mydict, "mit Laenge:", len(mydict)) + +# Legt ggf. das Key-Value-Paar neu an +mydict['hostname'] = "notebook14" +mydict['address'] = '192.168.1.214' +mydict['maker'] = 'Lenovo' +mydict['type'] = 'T530' +mydict['ramsize'] = 16 +mydict['ssd'] = True + +print("Nicht-Leeres Dictionary:", mydict, "mit Laenge:", len(mydict)) diff --git a/Lehrer/pythonkurs/Montag/dict2 b/Lehrer/pythonkurs/Montag/dict2 new file mode 100755 index 0000000..221039b --- /dev/null +++ b/Lehrer/pythonkurs/Montag/dict2 @@ -0,0 +1,20 @@ +#! /usr/bin/env python3 + +mydict = {} +print("Leeres Dictionary:", mydict, "mit Laenge:", len(mydict)) + +# Legt ggf. das Key-Value-Paar neu an +mydict['hostname'] = "notebook14" +mydict['address'] = '192.168.1.214' +mydict['maker'] = 'Lenovo' +mydict['type'] = 'T530' +mydict['ramsize'] = 16 +mydict['ssd'] = True + +for key in mydict.keys(): + print(key, '=', mydict[key]) + +print("-"*50) + +for value in mydict.values(): + print(value) diff --git a/Lehrer/pythonkurs/Montag/dict3 b/Lehrer/pythonkurs/Montag/dict3 new file mode 100755 index 0000000..4ea4f8e --- /dev/null +++ b/Lehrer/pythonkurs/Montag/dict3 @@ -0,0 +1,21 @@ +#! /usr/bin/env python3 + +mydict = {} + +# Legt ggf. das Key-Value-Paar neu an +mydict['hostname'] = "notebook14" +mydict['address'] = '192.168.1.214' +mydict['maker'] = 'Lenovo' +mydict['type'] = 'T530' +mydict['ramsize'] = 16 +mydict['ssd'] = True + +# Iteration ueber Dictionary selbst iteriert ueber die Keys +for key in mydict: + print(key, '=', mydict[key]) + +print("-"*50) + +# Gleichzeitige Iteration ueber Key und Value +for key, value in mydict.items(): + print(key, '=', value) diff --git a/Lehrer/pythonkurs/Montag/dict4 b/Lehrer/pythonkurs/Montag/dict4 new file mode 100755 index 0000000..c3a0f48 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/dict4 @@ -0,0 +1,24 @@ +#! /usr/bin/env python3 + +mydict = {} + +key_dict = {'eins': 1} +key_list = [1, 2, 3] + +# Achtung: Nicht-hashbare Typen +#mydict[key_dict] = 'foo' +#mydict[key_list] = 'bar' + +mydict[True] = 'True' +mydict[False] = 'False' +mydict[None] = 'None' + +print(mydict) + +# Achtung: Ueberschreibt die Werte von mydict[True] und mydict[False] +mydict[0] = '0' +mydict[1] = '1' +print(mydict) + +print(0 == False) +print(1 == True) diff --git a/Lehrer/pythonkurs/Montag/dict5 b/Lehrer/pythonkurs/Montag/dict5 new file mode 100755 index 0000000..eb06267 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/dict5 @@ -0,0 +1,28 @@ +#! /usr/bin/env python3 + +mydict = {} + +# Legt ggf. das Key-Value-Paar neu an +mydict['hostname'] = "notebook14" +mydict['address'] = '192.168.1.214' +mydict['maker'] = 'Lenovo' +mydict['type'] = 'T530' +mydict['ramsize'] = 16 +mydict['ssd'] = True + +# Iteration ueber Dictionary selbst iteriert ueber die Keys +for key in mydict: + print(key, '=', mydict[key]) + +print("-"*50) + +# Gleichzeitige Iteration ueber Key und Value +for key, value in mydict.items(): + print(key, '=', value) + +print("-"*50) + +# Achtung: Python liefert KeyError, falls der Key unbekannt +# print(mydict['year']) +print(mydict.get('year')) +print(mydict.get('year', 2010)) diff --git a/Lehrer/pythonkurs/Montag/dict6 b/Lehrer/pythonkurs/Montag/dict6 new file mode 100755 index 0000000..4cad6fe --- /dev/null +++ b/Lehrer/pythonkurs/Montag/dict6 @@ -0,0 +1,22 @@ +#! /usr/bin/env python3 + +mydict = {} + +# Legt ggf. das Key-Value-Paar neu an +mydict['hostname'] = "notebook14" +mydict['address'] = '192.168.1.214' +mydict['maker'] = 'Lenovo' +mydict['type'] = 'T530' +mydict['ramsize'] = 16 +mydict['ssd'] = True + +print(mydict) + +value = mydict.pop('address') + +print(mydict) + +key, value = mydict.popitem() +print("Geloeschter Key:", key) + +print(mydict) diff --git a/Lehrer/pythonkurs/Montag/hello_world b/Lehrer/pythonkurs/Montag/hello_world new file mode 100755 index 0000000..7aad54d --- /dev/null +++ b/Lehrer/pythonkurs/Montag/hello_world @@ -0,0 +1,4 @@ +#! /usr/bin/env python3 +#! /usr/bin/python3 + +print("Hello World!") diff --git a/Lehrer/pythonkurs/Montag/hello_world2 b/Lehrer/pythonkurs/Montag/hello_world2 new file mode 100755 index 0000000..af60451 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/hello_world2 @@ -0,0 +1,3 @@ +#! /usr/bin/env python3 + +print("Hello", "World!") diff --git a/Lehrer/pythonkurs/Montag/hello_world3 b/Lehrer/pythonkurs/Montag/hello_world3 new file mode 100755 index 0000000..760f240 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/hello_world3 @@ -0,0 +1,6 @@ +#! /usr/bin/env python3 + +text = "Hallo" + ' ' + "World" + '!' +print(text) + +print("Länge der Zeichenkette:", len(text)) diff --git a/Lehrer/pythonkurs/Montag/hello_world4 b/Lehrer/pythonkurs/Montag/hello_world4 new file mode 100755 index 0000000..a5385cd --- /dev/null +++ b/Lehrer/pythonkurs/Montag/hello_world4 @@ -0,0 +1,8 @@ +#! /usr/bin/env python3 + +# + entspricht String-Concatenation +text = "Hallo" + ' ' + "World" + '!' +print(text) + +# * entspricht String-Repeat +print('=' * len(text)) diff --git a/Lehrer/pythonkurs/Montag/if b/Lehrer/pythonkurs/Montag/if new file mode 100755 index 0000000..956d165 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/if @@ -0,0 +1,29 @@ +#! /usr/bin/env python3 + +mydict = {'hostname': 'notebook14', + 'address': '192.168.1.214', + 'maker': 'Lenovo', + 'type': 'T530', + 'ramsize': 16, + 'ssd': True, + } + +if 'maker' in mydict: + print("Key maker wird verwendet") + +if 'maker' in mydict and 'type' in mydict: + if mydict['maker'] == 'Lenovo' and mydict['type'].startswith('T'): + print("Thinkpad gefunden") + +if 'maker' in mydict and 'type' in mydict and \ + mydict['maker'] == 'Lenovo' and \ + mydict['type'].startswith('T'): + print("Thinkpad gefunden") + +if 'maker' in mydict and mydict['maker'] == 'Lenovo' and \ + 'type' in mydict and mydict['type'].startswith('T'): + print("Thinkpad gefunden") + +if ('maker' in mydict and mydict['maker'] == 'Lenovo' and + 'type' in mydict and mydict['type'].startswith('T')): + print("Thinkpad gefunden") diff --git a/Lehrer/pythonkurs/Montag/list1 b/Lehrer/pythonkurs/Montag/list1 new file mode 100755 index 0000000..6d98d6b --- /dev/null +++ b/Lehrer/pythonkurs/Montag/list1 @@ -0,0 +1,17 @@ +#! /usr/bin/env python3 + +mylist = [] +print("Leere Liste:", mylist) +print("Laenge der Liste:", len(mylist)) + +numbers = [1, 1, 2, 3, 5, 8, 11] +print(numbers) +print("Laenge der Liste:", len(numbers)) + +print("1. Element:", numbers[0]) +print("Letztes Element:", numbers[len(numbers)-1]) +print("Letztes Element:", numbers[-1]) + +# Explizite Aenderung des Wertes +numbers[-1] = 55 +print("Neues letztes Element:", numbers[-1]) diff --git a/Lehrer/pythonkurs/Montag/list2 b/Lehrer/pythonkurs/Montag/list2 new file mode 100755 index 0000000..17dc4f6 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/list2 @@ -0,0 +1,16 @@ +#! /usr/bin/env python3 + +numbers = [1, 1, 2, 3, 5, 8, 13] +print(numbers) +print("Laenge der Liste:", len(numbers)) + +# Zugriff nur innerhalb der vorhandenen Indizes erlaubt +# numbers[len(numbers)] = 21 + +numbers.append(21) +print(numbers) +print("Laenge der Liste:", len(numbers)) + +numbers.insert(0, 0) # 1. Parameter ist Index, 2. Parameter der Wert +print(numbers) +print("Laenge der Liste:", len(numbers)) diff --git a/Lehrer/pythonkurs/Montag/list3 b/Lehrer/pythonkurs/Montag/list3 new file mode 100755 index 0000000..ab3a853 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/list3 @@ -0,0 +1,8 @@ +#! /usr/bin/env python3 + +numbers = [1, 1, 2, 3, 5, 8, 13] +numbers.append(21) +numbers.insert(0, 0) # 1. Parameter ist Index, 2. Parameter der Wert + +for value in numbers: + print(value) diff --git a/Lehrer/pythonkurs/Montag/list4 b/Lehrer/pythonkurs/Montag/list4 new file mode 100755 index 0000000..e93d01e --- /dev/null +++ b/Lehrer/pythonkurs/Montag/list4 @@ -0,0 +1,20 @@ +#! /usr/bin/env python3 + +numbers = [1, 1, 2, 3, 5, 8, 13] +numbers.append(21) +numbers.insert(0, 0) # 1. Parameter ist Index, 2. Parameter der Wert + +# Slice =~ Start-Index und Stop-Index +number_slice1 = numbers[0:3] +number_slice2 = numbers[3:6] +number_slice3 = numbers[-4:-1] + +print(number_slice1) +print(number_slice2) +print(number_slice3) + +# Sonderfall: Start-Index = 0 +print(numbers[:-3]) + +# Sonderfall: Stop-Index = Laenge +print(numbers[3:]) diff --git a/Lehrer/pythonkurs/Montag/list5 b/Lehrer/pythonkurs/Montag/list5 new file mode 100755 index 0000000..9fcc545 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/list5 @@ -0,0 +1,9 @@ +#! /usr/bin/env python3 + +numbers = [1, 1, 2, 3, 5, 8, 13] +numbers.append(21) +numbers.insert(0, 0) # 1. Parameter ist Index, 2. Parameter der Wert + +print(numbers[:-4]) +for value in numbers[:-4]: + print(value) diff --git a/Lehrer/pythonkurs/Montag/list6 b/Lehrer/pythonkurs/Montag/list6 new file mode 100755 index 0000000..644a527 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/list6 @@ -0,0 +1,15 @@ +#! /usr/bin/env python3 + +numbers = [1, 1, 2, 3, 5, 8, 13] +numbers.append(21) +numbers.insert(0, 0) # 1. Parameter ist Index, 2. Parameter der Wert + +# Achtung: Nur die Referenz wird kopiert +kopie = numbers + +kopie[0] = -1 +kopie[1] = -2 +kopie[2] = -3 + +print(numbers) +print(kopie) diff --git a/Lehrer/pythonkurs/Montag/list7 b/Lehrer/pythonkurs/Montag/list7 new file mode 100755 index 0000000..9674c68 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/list7 @@ -0,0 +1,16 @@ +#! /usr/bin/env python3 + +numbers = [1, 1, 2, 3, 5, 8, 13] +numbers.append(21) +numbers.insert(0, 0) # 1. Parameter ist Index, 2. Parameter der Wert + +# Hier echte Kopie erzeugen +kopie = numbers[:] +#kopie = numbers.copy() + +kopie[0] = -1 +kopie[1] = -2 +kopie[2] = -3 + +print(numbers) +print(kopie) diff --git a/Lehrer/pythonkurs/Montag/list8 b/Lehrer/pythonkurs/Montag/list8 new file mode 100755 index 0000000..6f749a9 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/list8 @@ -0,0 +1,6 @@ +#! /usr/bin/env python3 + +wortliste = ['Das', 'ist', 'ein', 'Satz', 'mit', 'X', 'gewesen'] + +for wort in wortliste[:-1]: + print(wort) diff --git a/Lehrer/pythonkurs/Montag/list9 b/Lehrer/pythonkurs/Montag/list9 new file mode 100755 index 0000000..a63b3b3 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/list9 @@ -0,0 +1,9 @@ +#! /usr/bin/env python3 + +mlist = ['Quatsch', 'Liste'] + +# Nur Objekte sind als Element einer Liste zugelassen +mylist = ['Das', 10, 3.14, True, False, None, ['subliste'], [], mlist] + +for value in mylist: + print(value) diff --git a/Lehrer/pythonkurs/Montag/lista b/Lehrer/pythonkurs/Montag/lista new file mode 100755 index 0000000..4d97f5c --- /dev/null +++ b/Lehrer/pythonkurs/Montag/lista @@ -0,0 +1,12 @@ +#! /usr/bin/env python3 + +mlist = ['Quatsch', 'Liste'] +print(mlist) + +mlist.remove('Quatsch') +print(mlist) + +# Ohne Parameter wird das letzte Element entfernt +# Mit Parameter das des angegebenen Indizes +elem = mlist.pop() +print(mlist) diff --git a/Lehrer/pythonkurs/Montag/print1 b/Lehrer/pythonkurs/Montag/print1 new file mode 100755 index 0000000..12a1711 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/print1 @@ -0,0 +1,16 @@ +#! /usr/bin/env python3 + +string = "Linuxhotel, Essen" +integer = 13 +double = 3.1415 + +print(string, integer, double) + +# can only concatenate str (not "int") to str +# Daher muss die Zahl zuerst in einen String konvertiert werden +text = string + ' ' + str(integer) +text = text + ' ' + str(double) + +# Falls die nächste Zeile eingerueckt wird, kann Python die Datei +# nicht mehr compilieren, und erzeugt einen Syntax-Fehler +print(text) diff --git a/Lehrer/pythonkurs/Montag/print1_version2.x b/Lehrer/pythonkurs/Montag/print1_version2.x new file mode 100755 index 0000000..22d9251 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/print1_version2.x @@ -0,0 +1,19 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Compiler-Anweisung zum Character-Set muss in 1. oder 2. Zeile stehen +# Im Fall von UTF-8 nur fuer Python 2.x erforderlich + +string = "Linuxhotel, Essen" +integer = 13 +double = 3.1415 + +print(string, integer, double) + +# can only concatenate str (not "int") to str +# Daher muss die Zahl zuerst in einen String konvertiert werden +text = string + ' ' + str(integer) +text = text + ' ' + str(double) + +# Falls die nächste Zeile eingerueckt wird, kann Python die Datei +# nicht mehr compilieren, und erzeugt einen Syntax-Fehler +print(text) diff --git a/Lehrer/pythonkurs/Montag/print2 b/Lehrer/pythonkurs/Montag/print2 new file mode 100755 index 0000000..8e3e0a8 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/print2 @@ -0,0 +1,19 @@ +#! /usr/bin/env python3 + +string = "Linuxhotel, Essen" +integer = 13 +double = 3.1415 +null = None # expliziter Nicht-Wert, aka NULL, 0x00, NIL +empty_string = '' + +print(string, integer, double) + +# can only concatenate str (not "int") to str +# Daher muss die Zahl zuerst in einen String konvertiert werden +text = string + ' ' + str(integer) +text += ' ' + str(double) + +# Falls die nächste Zeile eingerueckt wird, kann Python die Datei +# nicht mehr compilieren, und erzeugt einen Syntax-Fehler +print(text) +print(null) diff --git a/Lehrer/pythonkurs/Montag/schachbrett1 b/Lehrer/pythonkurs/Montag/schachbrett1 new file mode 100755 index 0000000..5d6bec6 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/schachbrett1 @@ -0,0 +1,16 @@ +#! /usr/bin/env python3 + +spalten = [ None for col in "12345678" ] +# Achtung: Hier wird immer die Referenz auf das Objekt spalten verwendet +# zeilen = [spalten for row in "ABCDEFGH"] +# Daher besser eine echte Kopie erstellen +zeilen = [spalten.copy() for row in "ABCDEFGH"] + +print(zeilen) +# Achtung: Falls oben die Referenz verwendet wird, erhaelt man 32 Tuerme +zeilen[0][0] = 'Turm' +zeilen[0][-1] = 'Turm' +zeilen[-1][0] = 'turm' +zeilen[-1][-1] = 'turm' +print(zeilen) + diff --git a/Lehrer/pythonkurs/Montag/schachbrett2 b/Lehrer/pythonkurs/Montag/schachbrett2 new file mode 100755 index 0000000..0a432aa --- /dev/null +++ b/Lehrer/pythonkurs/Montag/schachbrett2 @@ -0,0 +1,14 @@ +#! /usr/bin/env python3 + +spalten = [ None for col in "12345678" ] +zeilen = [spalten.copy() for row in "ABCDEFGH"] + +zeilen[0][0] = 'Turm' +zeilen[0][-1] = 'Turm' +zeilen[-1][0] = 'turm' +zeilen[-1][-1] = 'turm' + + +print("Adressen der Spalten-Listen:") +for spalte in zeilen: + print(id(spalte)) diff --git a/Lehrer/pythonkurs/Montag/schachbrett3 b/Lehrer/pythonkurs/Montag/schachbrett3 new file mode 100755 index 0000000..bd7706b --- /dev/null +++ b/Lehrer/pythonkurs/Montag/schachbrett3 @@ -0,0 +1,16 @@ +#! /usr/bin/env python3 + +spalten = [ None for col in "12345678" ] +zeilen = [spalten.copy() for row in "ABCDEFGH"] + +zeilen[0][0] = 'Turm' +zeilen[0][-1] = 'Turm' +zeilen[-1][0] = 'turm' +zeilen[-1][-1] = 'turm' + + +for zeile in zeilen: + for zelle in zeile: + print(zelle, end=' ') + else: + print() diff --git a/Lehrer/pythonkurs/Montag/schachbrett4 b/Lehrer/pythonkurs/Montag/schachbrett4 new file mode 100755 index 0000000..2da2838 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/schachbrett4 @@ -0,0 +1,16 @@ +#! /usr/bin/env python3 + +# Alternativ als geschachtelte List Comprehension +zeilen = [[ None for col in "12345678" ] for row in "ABCDEFGH"] + +zeilen[0][0] = 'Turm' +zeilen[0][-1] = 'Turm' +zeilen[-1][0] = 'turm' +zeilen[-1][-1] = 'turm' + + +for zeile in zeilen: + for zelle in zeile: + print(zelle, end=' ') + else: + print() diff --git a/Lehrer/pythonkurs/Montag/strings1 b/Lehrer/pythonkurs/Montag/strings1 new file mode 100755 index 0000000..b8a19a1 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/strings1 @@ -0,0 +1,9 @@ +#! /usr/bin/env python3 + +string = "Das ist kein Satz" + +print(string[:3]) +print(string[-4:]) + +# Strings sind unveraenderlich +# string[0] = 'd' diff --git a/Lehrer/pythonkurs/Montag/strings2 b/Lehrer/pythonkurs/Montag/strings2 new file mode 100755 index 0000000..f517f5c --- /dev/null +++ b/Lehrer/pythonkurs/Montag/strings2 @@ -0,0 +1,13 @@ +#! /usr/bin/env python3 + +string = "Das ist kein Satz" +wortliste = string.split(' ') + +print(wortliste) +print(wortliste[:2]) + +wortliste[2] = 'ein' +print(wortliste) + +string = ' '.join(wortliste) +print(string) diff --git a/Lehrer/pythonkurs/Montag/strings3 b/Lehrer/pythonkurs/Montag/strings3 new file mode 100755 index 0000000..a512c75 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/strings3 @@ -0,0 +1,9 @@ +#! /usr/bin/env python3 + +string = "Das ist kein Satz" +wortliste = string.split(' ') + +print(wortliste) +print(wortliste[-1:]) +print(wortliste[-1:][0]) +print(wortliste[-1]) diff --git a/Lehrer/pythonkurs/Montag/strings4 b/Lehrer/pythonkurs/Montag/strings4 new file mode 100755 index 0000000..127c97c --- /dev/null +++ b/Lehrer/pythonkurs/Montag/strings4 @@ -0,0 +1,7 @@ +#! /usr/bin/env python3 + +string = "Stringtheorie" + +print(string) +for c in string: + print(c) diff --git a/Lehrer/pythonkurs/Montag/strings5 b/Lehrer/pythonkurs/Montag/strings5 new file mode 100755 index 0000000..08109fe --- /dev/null +++ b/Lehrer/pythonkurs/Montag/strings5 @@ -0,0 +1,27 @@ +#! /usr/bin/env python3 + +string = "Stringtheorie" + +asciiwerte = [] +for c in string: + asciiwerte.append(ord(c)) + +# Diese Schleife als List Comprehension +# asciiwerte = [ord(c) for c in string] + +print(asciiwerte) + +# 65 = A, 97 = a +# ord('a') - ord('A') +asciiwerte[0] = asciiwerte[0] + (97-65) + +# List Comprehension = On-the-Fly-Berechnung ganzer Listen +# Kopie von asciiwerte, alternativ zu asciiwerte[:] oder asciiwerte.copy() +ascii_list = [value for value in asciiwerte] + +# Neue Liste von Zeichen +char_list = [chr(value) for value in asciiwerte] +print(char_list) + +ziel_string = ''.join(char_list) +print(ziel_string) diff --git a/Lehrer/pythonkurs/Montag/strings6 b/Lehrer/pythonkurs/Montag/strings6 new file mode 100755 index 0000000..eac7019 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/strings6 @@ -0,0 +1,13 @@ +#! /usr/bin/env python3 + +string = "Stringtheorie" + +print(string) +print(string.lower()) +print(string.upper()) + +print(string[0].lower()+string[1:]) +string = string[0].lower()+string[1:] + +string = 'Übung' +print(string[0].lower()+string[1:]) diff --git a/Lehrer/pythonkurs/Montag/strings7 b/Lehrer/pythonkurs/Montag/strings7 new file mode 100755 index 0000000..ee4f28f --- /dev/null +++ b/Lehrer/pythonkurs/Montag/strings7 @@ -0,0 +1,16 @@ +#! /usr/bin/env python3 + +string = "Stringtheorie" + +# .count() existiert auch bei Listen +print("Haeufigkeit von e:", string.count('e')) +print("Haeufigkeit von a:", string.count('a')) + +print("Index von e:", string.find('e')) +# Achtung: liefert -1 bei Nicht-Finden, muss abgeprueft werden +print("Index von a:", string.find('a')) + +# .index() existiert auch bei Listen +print("Index von e:", string.index('e')) +# Achtung: Loest eine Exception aus, muss ggf. abgefangen werden +print("Index von a:", string.index('a')) diff --git a/Lehrer/pythonkurs/Montag/testdict b/Lehrer/pythonkurs/Montag/testdict new file mode 100755 index 0000000..5ef6aa7 --- /dev/null +++ b/Lehrer/pythonkurs/Montag/testdict @@ -0,0 +1,4 @@ +#! /usr/bin/env python3 +testdict = {'hostname': 'notebook14', 'address': '192.168.1.214', 'maker': 'Lenovo', 'type': 'T530', 'ramsize': 16, 'ssd': True} + +print(testdict['hostname']) diff --git a/Lehrer/pythonkurs/Montag/zahlen1 b/Lehrer/pythonkurs/Montag/zahlen1 new file mode 100755 index 0000000..eb10c3f --- /dev/null +++ b/Lehrer/pythonkurs/Montag/zahlen1 @@ -0,0 +1,23 @@ +#! /usr/bin/env python3 + +integer = 13 +zahl1 = "12" + +print(integer, zahl1) + +# Explizite Typ-Umwandlung in Integer +ergebnis = integer + int(zahl1) +print(ergebnis) + +# Achtung: Python3 erzeugt float als Ergebnis, Python2 ein Integer +print(ergebnis, "/ 5 =", ergebnis / 5) +# Explizite Integer-Division +print(ergebnis, "/ 5 =", ergebnis // 5) + +print(ergebnis, "/ 4 =", ergebnis // 4) +# Modulo = ganzzahliger Rest der Division +print(ergebnis, "% 4 =", ergebnis % 4) + +# Power-Funktion, Exponent-Funktion +print("2 hoch 10 =", 2 ** 10) +print("10 hoch 3 =", 10 ** 3) diff --git a/Mittwoch/User_modify.py b/Mittwoch/User_modify.py old mode 100644 new mode 100755 index 0db2c30..470dda6 --- a/Mittwoch/User_modify.py +++ b/Mittwoch/User_modify.py @@ -2,40 +2,42 @@ from pprint import pprint import sys import utilities -from argv import argv_value +from argv2 import argv_value def read_file(path: str) -> "List of lines": #f = open(path, 'r') - with open(path, 'r') as f: - # f.read(buflen) - binary read - # f.readline() - 1 Textzeile lesen -> str - # f.readlines - alle Textzeilen lesen ->str - # f ist gleichzeitig Iterator - # 1 möglichkeit - #lines = list(map(lambda s : s.rstrip(), f)) - # 2 möflichkeit + with open(path, 'r') as f: + # f.read(buflen) - binary read + # f.readline() - 1 Textzeile lesen -> str + # f.readlines - alle Textzeilen lesen ->str + # f ist gleichzeitig Iterator + # 1 möglichkeit + #lines = list(map(lambda s : s.rstrip(), f)) + # 2 möflichkeit lines = list(map(str.rstrip, f)) # 3 möglichkeit #lines = [] - #for line in f.readlines(): + # for line in f.readlines(): # lines.append(line.rstrip()) - #f.close() + # f.close() return lines + def parse_passwd_lines(line: str) -> "Dict of passwd details": parts = line.split(':') userdict = { - "username" : parts[0], - "uid" : int(parts[2]), - "gid" : int(parts[3]), - "realname" : parts[4].split(',')[0], - "gecos" : parts[4], - "home" : parts[5], + "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: @@ -44,24 +46,26 @@ def build_userlist(lines) -> "List of user dicts": def print_userlist_sorted_by_username(userlist): - #ruft für jedes Element key(elem) also e im Lambda-Ausdruck ist ein Element der Liste user dict + # ruft für jedes Element key(elem) also e im Lambda-Ausdruck ist ein Element der Liste user dict for user in sorted(userlist, key=lambda e: e['username'].lower()): #print("{username:{width}} {realname}".format(width=32 **user)) print("{:5} {:32} {}".format( user['uid'], user['username'], - user['realname'], - user['home'], + user['realname'], + user['home'], user['shell'] )) + + def print_to_file(userlist): userlen = max(map(lambda u: len(u['username']), userlist)) try: with open('/etc/userlist.txt', 'w') as outfile: for user in userlist: print("{uid:5} {username:{width}} {realname}".format( - width=userlen, **user), - file=outfile) + width=userlen, **user), + file=outfile) except ImportError: pass # Wird vom Mdule utilities gesteuert @@ -72,17 +76,19 @@ def print_to_file(userlist): finally: print("Wird immer durchlaufen, unabhaengig von ausgeloesten Exceptions") - - #with open('/tmp/userlist.txt', 'w') as outfile: + # with open('/tmp/userlist.txt', 'w') as outfile: # for user in userlist: # print("{uid:5} {username:{width}} {realname}".format( - # width=userlen, **user), + # width=userlen, **user), # file=outfile) + def print_userlist_sorted_by_uid(userlist): userlen = max(map(lambda u: len(u['username']), userlist)) for user in sorted(userlist, key=lambda e: e['uid']): - print("{uid:5} {username:{width}} {realname}".format(width=userlen, **user)) + print("{uid:5} {username:{width}} {realname}".format( + width=userlen, **user)) + def main(): output_functions = { @@ -90,14 +96,14 @@ def main(): 'logger': print_to_file, 'username': print_userlist_sorted_by_username, 'uid': print_userlist_sorted_by_uid, - + } - #outfunc = output_functions['username'] - outfunc = output_functions[argv_value('-o', default='uid')] + outfunc = output_functions['username'] + #outfunc = output_functions[argv_value('-o', default='uid')] lines = read_file("/etc/passwd") userlist = build_userlist(lines) outfunc(userlist) -utilities.hide_exception(main) \ No newline at end of file +utilities.hide_exception(main) diff --git a/Mittwoch/__pycache__/argv.cpython-39.pyc b/Mittwoch/__pycache__/argv.cpython-39.pyc old mode 100644 new mode 100755 diff --git a/Mittwoch/__pycache__/argv2.cpython-310.pyc b/Mittwoch/__pycache__/argv2.cpython-310.pyc new file mode 100755 index 0000000000000000000000000000000000000000..fe7cc52b1cfe016bb66129ce8f86c3b866cc404f GIT binary patch literal 482 zcmY*VJx{|h5Ix%|ltL>eP`9ukrBaE6gczt05@MvP)B({2h1fJ{len^-mOz;3{{Tk* zl2@kw1;l_|7}}HG`R< zCEu7421_QqAb@1c?QJ?;7d=29T}|fj37E^`u6M;xV1nXk&!P&y_)x9yNHY=XDC3&$ zD#kZE6H!#{GnwRkzS%i5{M5{2Y>6i<@vf@}IT9JKR^IC*<%dZ++Kk+mpyY+F`zoxx zlZI=_b>}S~IOXSY%QkmTQ(hRMq*Iv|+=i5TO-kKCqb(UKA+`ToyGp6KR$hjur6q|z zKC!hz3u$cq>N{+`G>mH<*IYtlnOfkQI05bd#Wrs=ejxq8F@Ilo2P)^?p^|cXsFM@b z-PdZ!M}~Lzr)Hq!i(WbyXJdKX-4(`6R66M1G{ehcYTE%Ytv>|f1 z1`!TnBUpzG+`bGy<3D=CC*vNQCqhzMJw4JY?~H}H>amW<3#Coxu5z`0*MH^@$8p0p zC}k?8RJWa~zVE@8YTVbFpQhxbBg0lEAK DyFlz$ literal 0 HcmV?d00001 diff --git a/Mittwoch/__pycache__/utilities.cpython-39.pyc b/Mittwoch/__pycache__/utilities.cpython-39.pyc old mode 100644 new mode 100755 diff --git a/Mittwoch/argv2.py b/Mittwoch/argv2.py old mode 100644 new mode 100755 diff --git a/Mittwoch/command.py b/Mittwoch/command.py old mode 100644 new mode 100755 diff --git a/Mittwoch/find_ip.py b/Mittwoch/find_ip.py old mode 100644 new mode 100755 diff --git a/Mittwoch/import.py b/Mittwoch/import.py old mode 100644 new mode 100755 diff --git a/Mittwoch/module_path.py b/Mittwoch/module_path.py old mode 100644 new mode 100755 diff --git a/Mittwoch/moduletest.py b/Mittwoch/moduletest.py old mode 100644 new mode 100755 index 4c166ed..848fd24 --- a/Mittwoch/moduletest.py +++ b/Mittwoch/moduletest.py @@ -1,6 +1,6 @@ #! /usr/bin/env python3 #import argv -from argv import argv_value +from argv2 import argv_value print("Wert von -o :", argv_value('-o')) diff --git a/Mittwoch/utilities.py b/Mittwoch/utilities.py old mode 100644 new mode 100755 diff --git a/Mittwoch/write_file.py b/Mittwoch/write_file.py old mode 100644 new mode 100755 diff --git a/Module/argv.py b/Module/argv.py old mode 100644 new mode 100755 diff --git a/Module/utilities.py b/Module/utilities.py old mode 100644 new mode 100755 diff --git a/Montag/Listen.py b/Montag/Listen.py old mode 100644 new mode 100755 diff --git a/Montag/String_umwandelt_wortliste.py b/Montag/String_umwandelt_wortliste.py old mode 100644 new mode 100755 diff --git a/Montag/Stringtheorie.py b/Montag/Stringtheorie.py old mode 100644 new mode 100755 diff --git a/Montag/dict.py b/Montag/dict.py old mode 100644 new mode 100755 diff --git a/Montag/hello-world.py b/Montag/hello-world.py old mode 100644 new mode 100755 diff --git a/Montag/if.py b/Montag/if.py old mode 100644 new mode 100755 diff --git a/Montag/schachbrett.py b/Montag/schachbrett.py old mode 100644 new mode 100755 diff --git a/Readme.md b/Readme.md old mode 100644 new mode 100755 diff --git a/meine_test/Textdatei.txt b/meine_test/Textdatei.txt new file mode 100755 index 0000000..a5b56e3 --- /dev/null +++ b/meine_test/Textdatei.txt @@ -0,0 +1,4 @@ +2022-12-08 17:02:20 input die erste +2022-12-08 17:02:23 input die zweite +2022-12-08 17:02:31 input die erste +2022-12-08 17:02:34 input die zweite diff --git a/meine_test/read_file.py b/meine_test/read_file.py new file mode 100755 index 0000000..6c27413 --- /dev/null +++ b/meine_test/read_file.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 + +def parse_passwd_lines(line: str) -> "Dict of passwd details": + parts = line.split(':') + userdict = { + "gruppenname" : parts[0], + "password" : parts[1], + "gid" : parts[2], + "member" : parts[3] + } + return userdict + +with open("/etc/group", "r") as groups_data: + lines = list(map(str.rstrip, groups_data)) + +result = [] +for line in lines: + result.append(parse_passwd_lines(line)) + +print(result) + + +for user in result: + if user["member"] != "": + #print("{username:{width}} {realname}".format(width=32 **user)) + print(user["gruppenname"] + "---->" + user["member"] ) \ No newline at end of file diff --git a/meine_test/server.db b/meine_test/server.db new file mode 100755 index 0000000000000000000000000000000000000000..680cee2271554503e53b745c186fa51b708d739c GIT binary patch literal 8192 zcmeI$y$ZrG6b0a$SQSKxi%7TYri)8oz#p=8u@-Ty5<#d6ZE*J$d^|@-N1woG6&J-> zIEN%R33vLoWI74g*6?bVZ4%1?HAx5>FcVSPP3h($vE;V9Hx+;O+Y zUy_?_Z?bK&F&yi8{IRchf17*iMCz(8>g+ZM1Rwwb2tWV=5P$##AOHafKmY=NBvA2W T%bMI)O3x~bS{JhO{u;OemWM8h literal 0 HcmV?d00001 diff --git a/meine_test/shelve_test.py b/meine_test/shelve_test.py new file mode 100755 index 0000000..135f89f --- /dev/null +++ b/meine_test/shelve_test.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 + +import shelve +# schreibe shelve Wird dauerhaft gespeichert +spieler_endrunde = ["Hans", "Daniel"] +with shelve.open("testfile") as inhalt: + inhalt["imFinale"] = spieler_endrunde +# inhalt["Vorrunde"] = [spieler_endrunde, "Klaus", "Martin"] +# +#with shelve.open("testfile") as inhalt: +# print(inhalt["imFinale"]) +# erweitere Shelve mit neuer Liste +with shelve.open("testfile") as inhalt: + new_value = inhalt["imFinale"] + new_value.append("derNeue3") + #inhalt["imFinale"] = new_value + print(list(inhalt.keys())) + + +#with*1 open('Textdatei.txt', 'w') as inhalt*2: +#*3inhalt.write('Hallo Schrödinger!') \ No newline at end of file diff --git a/meine_test/sqlite_test.py b/meine_test/sqlite_test.py new file mode 100755 index 0000000..a24ec56 --- /dev/null +++ b/meine_test/sqlite_test.py @@ -0,0 +1,86 @@ +import sqlite3 + +class wireguard_db: + def __init__(self, name = str ,table = str ) -> None: + self.db_name = name + self.table_name = table + + def create(self): + with sqlite3.connect(self.db_name) as con: + #con = sqlite3.connect(":memory:") + cursor = con.cursor() + cursor.execute( + """ + CREATE TABLE IF NOT EXISTS {table_name} ( + id integer primary key autoincrement, + servername TEXT, + public_key TEXT, + adapter TEXT + ) + """.format(table_name=self.table_name)) + con.commit() + + def insert(self, wireguard_server = str, wireguard_public_server_key = str, wireguard_server_adapter = str): + try: + with sqlite3.connect(self.db_name) as con: + #con = sqlite3.connect(":memory:") + cursor = con.cursor() + cursor.execute( + """ + INSERT INTO {table_name} ( + servername, + public_key, + adapter + ) VALUES ( + '{wireguard_server}', + '{wireguard_public_server_key}', + '{wireguard_server_adapter}' + ) + """.format( + table_name = self.table_name, + wireguard_server=wireguard_server, + wireguard_public_server_key=wireguard_public_server_key, + wireguard_server_adapter= wireguard_server_adapter + ) + ) + con.commit() + return True + except: + raise TypeError("schreiben in DB nicht möglich !! ") + finally: + pass + + def select(self, wireguard_server = str): + try: + with sqlite3.connect(self.db_name) as con: + cursor = con.cursor() + cursor.execute( + """ + SELECT * from {table_name} + where servername = '{wireguard_server}' + """.format(table_name=self.table_name, wireguard_server=wireguard_server) + ) + select_output = cursor.fetchall() + if select_output == []: + return False + else: + return select_output + except: + pass + pass + + + +if __name__ == "__main__": + create_server_db = wireguard_db(name="test_db", table="serverlist") + #create_server_db.create() + name_wireguardserver = "mandan_01" + select_server = create_server_db.select(wireguard_server=name_wireguardserver) + if select_server is False: + print("Server existiert nicht in der Datenbank") + create_server_db.insert(wireguard_server=name_wireguardserver, wireguard_public_server_key="lalakdjcdj", wireguard_server_adapter="wrg-srv" ) + else: + server_ids = [test[0] for test in select_server] + server_publickey = [test[2] for test in select_server] + print("""Der Server steht bereits in der DB mit den ID : {server_ids} \nPublic Keys der Server : {server_publickey} + """.format(server_ids=server_ids, server_publickey=server_publickey).rstrip().strip()) \ No newline at end of file diff --git a/meine_test/sqllite_what.py b/meine_test/sqllite_what.py new file mode 100755 index 0000000..0ef928d --- /dev/null +++ b/meine_test/sqllite_what.py @@ -0,0 +1,18 @@ +import sqlite3 + +def create_db(name = str): + with sqlite3.connect(name) as con: + cursor = con.cursor() + cursor.execute( + """ + CREATE TABLE IF NOT EXISTS server ( + id INT, + servername TEXT, + public_key TEXT, + adapter TEXT + ) + """) + con.commit() + + +create_db("test") \ No newline at end of file diff --git a/meine_test/testfile b/meine_test/testfile new file mode 100755 index 0000000000000000000000000000000000000000..f4f2d3c3927cc36957c680019f087c654b42db3e GIT binary patch literal 16384 zcmeI2F-yZh6vuY#%th=^iAM4cQ0xgk&^M7tIzr;O?1uDgpL z!A%_8#9jOjg5LH1u}MuuC#C%t?%uuTy?b{*-aSe$50{4{#*kq&niNX*LtZPnsyf4X zlP%jA=`Mxw{hS_TpfAnqL1^o>=mzWuVV`Z$$Dt47`5yE<^gQ$;^fcx#L9anyfc^;k zUFdgs4wZrgNPq-LfCNZ@1W14cNPq-LfCRdOKn~la)F8-#925cO0rP-)z;nPlz&gM> zz&gM>z&gM>z&g-jb->i8+8Bkr!Tor6O}>Ufc)vb|i}%|B?XcBGf5r3AURn3Z_AWo# zGv4!i&4V1sA$l^H56p*d&WGih=Y8jR!@0tHT|;1@|=YQ|p%Nh)N&|O}l#d zSHV$`_svZ!ZYNFqwkuXuIqz8Bnd8cDR3WRnwhU6AMG)znIE0YDiv|}g>DYM1k|aV$tjm6X?sa4UB%he@8Wk6 z{0M#oFVwc!LbA*Mp-FSOe=iTe?MiO0E@Ud$V^2jqWk+P4P)bf1BZO4+Vd!I8R9~!2 z2l_i37gdEEcw|kdO4T<~{n95C1Rwwb2tWV=5P$##AOHafK!9A9%C)^cdY|%#P$Yv; zZ%sRi7z{=1Ee?(I>-MSJX71_PMVl>TcVZrirvBybOM_Z9$Dyz0WKE$)LWMF(li5}2 z?@F`#Y-g3_l=PX5Q}HAe>nj;?HD+BgW_+0TWb7#si8yWMt}tmKYn8d}J2yYvA3lWA z>tv584s)OPQ{7mW%xz&e+nZbV2C+Zw5BuGIwr}lYJw!nO0uX=z1Rwwb2tWV=5P$## z{=LAKWs)tY9`V@cai?_{@{o7^!1IG=^|YU;5i6U-(Sh+~2j6NfB{ofyH0Fur`IY>6 z$IwsMuFwA=2p+?3;PqtClfO+krQ!%JjAZ+NYJU^`K|ufl5P$##AOHafKmY;|fB*y_ P@J|G))Ntth-3RLjwyMM9 literal 0 HcmV?d00001