{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Live Hacking" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Strings können viel: `split()`\n", "Beim zeilenweisen Lesen eines Files, die Nutzdaten einer Zeile extrahieren wollend ...\n", "* Frage: wie spalte ich eine Zeile, die offensichtlich mit Tabs separierte Felder hat?\n", "* Antwort: [`split()` ohne Argumente](https://docs.python.org/3/library/stdtypes.html#str.split) ist am gscheitesten, weil es aufeinanderfolgende Whitespaces als eines nimmt." ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['abc', 'def']" ] }, "execution_count": 80, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line = ' \\t abc \\t def '\n", "line.split()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tuple unpacking ist praktisch, wenn man weiss, dass z.B. genau drei Felder rauskommen werden ..." ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "aaa bbb ccc\n" ] } ], "source": [ "line = 'aaa\\tbbb\\tccc'\n", "feld0, feld1, feld2 = line.split()\n", "print(feld0, feld1, feld2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Gibts optionale Felder in der Zeile - aber ganz sicher mindestens drei -, so splittet man drei weg, und bearbeitet den Rest manuell nach ..." ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "feld0: aaa , feld1: bbb , feld2: ccc , rest: ddd eee\n", "do is no wos dabei\n" ] } ], "source": [ "# optional fields\n", "line = 'aaa\\tbbb\\tccc ddd eee'\n", "feld0, feld1, feld2, rest = line.split(maxsplit=3)\n", "print('feld0:', feld0, ', feld1:', feld1, ', feld2:', feld2, ', rest:', rest)\n", "\n", "restfields = rest.split()\n", "if len(restfields):\n", " print('do is no wos dabei')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Geht auch von rechts her ..." ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [], "source": [ "line = '1.2.3.4.10101010'\n", "rest, switchnumber = line.rsplit('.', maxsplit=1)" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.2.3.4 10101010\n" ] } ], "source": [ "print(rest, switchnumber)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Mutability, Immutability: kann man nicht oft genug wiederholen" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3]\n", "[1, 2, 3]\n" ] } ], "source": [ "l1 = [1,2,3]\n", "l2 = l1\n", "print(l1)\n", "print(l2)" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 'vier']" ] }, "execution_count": 86, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l1.append('vier')\n", "l1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Das ist der Punkt**: die Änderung sieht man auch über `l2`" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 'vier']" ] }, "execution_count": 87, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`l1` und `l2` zeigen auf dasselbe Objekt:" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "140070310441600\n", "140070310441600\n" ] } ], "source": [ "print(id(l1))\n", "print(id(l2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dass die beiden auf das gleiche Objekt zeigen, ist nicht so das Problem. Das Problem ist eigentlich, dass das Objekt verändert werden kann.\n", "\n", "* `list` ist *mutable* -> Problem\n", "* `tuple` ist *immutable* -> kein Problem" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 2, 3)" ] }, "execution_count": 89, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t1 = (1,2,3)\n", "t1" ] }, { "cell_type": "code", "execution_count": 90, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 2, 3)" ] }, "execution_count": 90, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t2 = t1\n", "t2" ] }, { "cell_type": "code", "execution_count": 91, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "140070371015728\n", "140070371015728\n" ] } ], "source": [ "print(id(t1))\n", "print(id(t2))" ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "gottseidank sind tuples immutable\n" ] } ], "source": [ "try:\n", " t1.append('vier')\n", "except AttributeError:\n", " print('gottseidank sind tuples immutable')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionaries" ] }, { "cell_type": "code", "execution_count": 93, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 93, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d = {'eins': 1,\n", " 'zwei': 2\n", " }\n", "d['eins']" ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(d))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternativer `dict` Aufruf: Liste von `(key,value)` Paaren" ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [], "source": [ "d = dict([('eins', 1), ('zwei', 2)])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"Hartes\" Indizieren ..." ] }, { "cell_type": "code", "execution_count": 96, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 96, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d['eins']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Fehlender Key -> Exception" ] }, { "cell_type": "code", "execution_count": 97, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "nix key in dict: 'drei'\n" ] } ], "source": [ "try:\n", " d['drei']\n", "except KeyError as e:\n", " print('nix key in dict:', e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"Weiches\" Nettfragen ..." ] }, { "cell_type": "code", "execution_count": 98, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 98, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d.get('eins')" ] }, { "cell_type": "code", "execution_count": 99, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n" ] } ], "source": [ "value = d.get('drei')\n", "print(value)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Shortcuts" ] }, { "cell_type": "code", "execution_count": 100, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "100\n" ] } ], "source": [ "# umstaendlich\n", "value = d.get('hundert')\n", "if value is None:\n", " value = 100\n", "print(value)" ] }, { "cell_type": "code", "execution_count": 101, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "100\n" ] } ], "source": [ "# einfach\n", "value = d.get('hundert', 100)\n", "print(value)" ] }, { "cell_type": "code", "execution_count": 102, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'eins': 1, 'zwei': 2}" ] }, "execution_count": 102, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d" ] }, { "cell_type": "code", "execution_count": 103, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "100\n" ] } ], "source": [ "# umstaendlich\n", "value = d.get('hundert')\n", "if value is None:\n", " d['hundert'] = 100\n", " value = 100\n", "print(value)" ] }, { "cell_type": "code", "execution_count": 104, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'eins': 1, 'zwei': 2, 'hundert': 100}" ] }, "execution_count": 104, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d" ] }, { "cell_type": "code", "execution_count": 105, "metadata": {}, "outputs": [], "source": [ "# (clear this up)\n", "del d['hundert']" ] }, { "cell_type": "code", "execution_count": 106, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "100\n" ] } ], "source": [ "# einfach\n", "value = d.setdefault('hundert', 100)\n", "print(value)" ] }, { "cell_type": "code", "execution_count": 107, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'eins': 1, 'zwei': 2, 'hundert': 100}" ] }, "execution_count": 107, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Objektorientierte Programmierung" ] }, { "cell_type": "code", "execution_count": 108, "metadata": {}, "outputs": [], "source": [ "class MeinVoelligSinnloserTyp:\n", " def __init__(self):\n", " self.eins = 1\n", " self.zwei = 2\n", " def sinnlose_addition(self):\n", " return self.eins + self.zwei" ] }, { "cell_type": "code", "execution_count": 109, "metadata": {}, "outputs": [], "source": [ "sinnlobj = MeinVoelligSinnloserTyp()" ] }, { "cell_type": "code", "execution_count": 110, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 110, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sinnlobj.eins" ] }, { "cell_type": "code", "execution_count": 111, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 111, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sinnlobj.zwei" ] }, { "cell_type": "code", "execution_count": 112, "metadata": {}, "outputs": [], "source": [ "sinnlobj.drei = 3" ] }, { "cell_type": "code", "execution_count": 113, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<__main__.MeinVoelligSinnloserTyp at 0x7f64a8934890>" ] }, "execution_count": 113, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sinnlobj" ] }, { "cell_type": "code", "execution_count": 114, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 114, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sinnlobj.drei" ] }, { "cell_type": "code", "execution_count": 115, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 115, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sinnlobj.sinnlose_addition()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Inheritance" ] }, { "cell_type": "code", "execution_count": 116, "metadata": {}, "outputs": [], "source": [ "class NochWenigerSinnvoll(MeinVoelligSinnloserTyp):\n", " def __init__(self, der_absolute_unsinn):\n", " super().__init__()\n", " self.unsinn = der_absolute_unsinn\n", " def uebertreibs_jetzt_bitte(self):\n", " self.eins += self.unsinn\n", " self.zwei += self.unsinn" ] }, { "cell_type": "code", "execution_count": 117, "metadata": {}, "outputs": [], "source": [ "bs = NochWenigerSinnvoll(666)" ] }, { "cell_type": "code", "execution_count": 118, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<__main__.NochWenigerSinnvoll at 0x7f64a894a790>" ] }, "execution_count": 118, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bs" ] }, { "cell_type": "code", "execution_count": 119, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 119, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bs.sinnlose_addition()" ] }, { "cell_type": "code", "execution_count": 120, "metadata": {}, "outputs": [], "source": [ "bs.uebertreibs_jetzt_bitte()" ] }, { "cell_type": "code", "execution_count": 121, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1335" ] }, "execution_count": 121, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bs.sinnlose_addition()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Date and Time and Time Deltas - `datetime`" ] }, { "cell_type": "code", "execution_count": 122, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "datetime.datetime(2020, 3, 17, 13, 55, 2, 819508)" ] }, "execution_count": 122, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import datetime\n", "\n", "now = datetime.datetime.now()\n", "now" ] }, { "cell_type": "code", "execution_count": 123, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "datetime.timedelta(seconds=358)" ] }, "execution_count": 123, "metadata": {}, "output_type": "execute_result" } ], "source": [ "uptime = datetime.timedelta(seconds=358)\n", "uptime" ] }, { "cell_type": "code", "execution_count": 124, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "datetime.datetime(2020, 3, 17, 13, 49, 4, 819508)" ] }, "execution_count": 124, "metadata": {}, "output_type": "execute_result" } ], "source": [ "boot = now - uptime\n", "boot" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Bissl potschert zum Schreiben is scho ... (andere Formen von `import`)" ] }, { "cell_type": "code", "execution_count": 125, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "datetime.datetime(2020, 3, 2, 13, 55, 2, 834972)" ] }, "execution_count": 125, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from datetime import datetime, timedelta\n", "irgendwann_einmal_gewesen = datetime.now() - timedelta(days=15)\n", "\n", "irgendwann_einmal_gewesen" ] }, { "cell_type": "code", "execution_count": 126, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "datetime.datetime(2020, 3, 17, 13, 55, 2, 840837)" ] }, "execution_count": 126, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from datetime import datetime as datetime_from_batteries\n", "datetime_from_batteries.now()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## String Representations: `__str__()`" ] }, { "cell_type": "code", "execution_count": 127, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'2020-03-17 13:55:02.846889'" ] }, "execution_count": 127, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# recover from the datetime massacre we created above\n", "del datetime\n", "import datetime\n", "now = datetime.datetime.now() # for example\n", "str(now)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Frage**: woher weiss `str()`, `datetime` als String ausschauen will?" ] }, { "cell_type": "code", "execution_count": 128, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'sinnlose str repraesentation von 666'" ] }, "execution_count": 128, "metadata": {}, "output_type": "execute_result" } ], "source": [ "class Sinnlos:\n", " def __init__(self, sinnlos):\n", " self.sinnlos = sinnlos\n", " def __str__(self):\n", " return 'sinnlose str repraesentation von {}'.format(self.sinnlos)\n", " \n", "str(Sinnlos(666))" ] }, { "cell_type": "code", "execution_count": 129, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"sinnlose str repraesentation von [1, 2, 3, 'vier']\"" ] }, "execution_count": 129, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str(Sinnlos([1,2,3,'vier']))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## `subprocess`" ] }, { "cell_type": "code", "execution_count": 130, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "CompletedProcess(args=['ls', '-l'], returncode=0)" ] }, "execution_count": 130, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import subprocess\n", "\n", "subprocess.run(['ls', '-l'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Nicht viel Information: `returncode = 0` -> ls erfolgreich beendet\n", "* **Frage**: Was ist mit dem Output?\n", "* **Antwort**: schau in dem Terminal nach, das du verwendest, um dieses Notebook anzuzeigen. (Die Cells werden vom Browser an den Notebook-Server gesendet, der sie dann ausführt.)\n", "Hmm ...\n", "* **Frage**: und wie krieg ich den von dort weg, in mein Programm rein?\n", "* **Antwort**: so ->" ] }, { "cell_type": "code", "execution_count": 131, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "b'total 52\\ndrwxrwxr-x. 2 jfasch jfasch 4096 Mar 17 13:48 Exercises\\n-rw-r--r--. 1 jfasch jfasch 2607 Mar 17 13:48 index.rst\\n-rw-rw-r--. 1 jfasch jfasch 33768 Mar 17 13:54 LiveHacking.ipynb\\ndrwxrwxr-x. 2 jfasch jfasch 4096 Mar 17 13:48 Misc\\n-rw-r--r--. 1 jfasch jfasch 0 Mar 17 13:48 README.rst.~1~\\ndrwxr-xr-x. 4 jfasch jfasch 4096 Mar 17 13:48 SwitchZeug\\n'\n" ] } ], "source": [ "result = subprocess.run(['ls', '-l'], capture_output=True)\n", "print(result.stdout)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Hmm ... das ist jetzt kein String, sondern Bytes (erkennbar am 'b'). Keiner weiss, in welchem Encoding `ls -l` seinen `stdout` formuliert - also ist das nur logisch so." ] }, { "cell_type": "code", "execution_count": 132, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(result.stdout))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* **Frage**: Wenn ich irgendwas mit dem Output machen will?\n", "* **Antwort**: Dann konvertier es in einen String. Dabei musst du dich aber aufs Encoding festlegen." ] }, { "cell_type": "code", "execution_count": 133, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "stdout_as_utf8 = str(result.stdout, encoding='utf-8')\n", "print(type(stdout_as_utf8))" ] }, { "cell_type": "code", "execution_count": 134, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'total 52\\ndrwxrwxr-x. 2 jfasch jfasch 4096 Mar 17 13:48 Exercises\\n-rw-r--r--. 1 jfasch jfasch 2607 Mar 17 13:48 index.rst\\n-rw-rw-r--. 1 jfasch jfasch 33768 Mar 17 13:54 LiveHacking.ipynb\\ndrwxrwxr-x. 2 jfasch jfasch 4096 Mar 17 13:48 Misc\\n-rw-r--r--. 1 jfasch jfasch 0 Mar 17 13:48 README.rst.~1~\\ndrwxr-xr-x. 4 jfasch jfasch 4096 Mar 17 13:48 SwitchZeug\\n'" ] }, "execution_count": 134, "metadata": {}, "output_type": "execute_result" } ], "source": [ "stdout_as_utf8" ] }, { "cell_type": "code", "execution_count": 135, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['total 52',\n", " 'drwxrwxr-x. 2 jfasch jfasch 4096 Mar 17 13:48 Exercises',\n", " '-rw-r--r--. 1 jfasch jfasch 2607 Mar 17 13:48 index.rst',\n", " '-rw-rw-r--. 1 jfasch jfasch 33768 Mar 17 13:54 LiveHacking.ipynb',\n", " 'drwxrwxr-x. 2 jfasch jfasch 4096 Mar 17 13:48 Misc',\n", " '-rw-r--r--. 1 jfasch jfasch 0 Mar 17 13:48 README.rst.~1~',\n", " 'drwxr-xr-x. 4 jfasch jfasch 4096 Mar 17 13:48 SwitchZeug',\n", " '']" ] }, "execution_count": 135, "metadata": {}, "output_type": "execute_result" } ], "source": [ "stdout_as_utf8.split('\\n')" ] }, { "cell_type": "code", "execution_count": 136, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ ".ipynb_checkpoints\n", "Misc\n", "SwitchZeug\n", "index.rst\n", "LiveHacking.ipynb\n", "README.rst.~1~\n", "Exercises\n", ".gitignore\n" ] } ], "source": [ "# fuer ls gibts was besseres\n", "import os\n", "\n", "for elem in os.listdir('.'):\n", " print(elem)" ] }, { "cell_type": "code", "execution_count": 137, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "dirpath: . , dirnames: ['.ipynb_checkpoints', 'Misc', 'SwitchZeug', 'Exercises'] , filenames: ['index.rst', 'LiveHacking.ipynb', 'README.rst.~1~', '.gitignore'] \n", "\n", "dirpath: ./.ipynb_checkpoints , dirnames: [] , filenames: ['LiveHacking-checkpoint.ipynb', 'ITG-Project-checkpoint.ipynb'] \n", "\n", "dirpath: ./Misc , dirnames: [] , filenames: ['scope.py', 'getter-setter.py', 'eval-argv.py', 'fibo-generator-yield.py', 'listcomprehension-generatorexpression.py', 'operator-overloading.py', 'scope-closure.py'] \n", "\n", "dirpath: ./SwitchZeug , dirnames: ['SwitchZeug', 'data'] , filenames: ['01-der-anfang.py', 'switchdb-create-schema.py', 'switchdb-report-switch.py', 'tests.py', 'michi-switch-upgrade-von-ini.py', 'michi-switch-upgrade-config.txt', '02-michi-parse.py', 'switchdb-insert-switch.py', 'michi-switch-upgrade-von-pyexec.py', 'tests.py.~1~', 'michi-switch-upgrade-config.ini'] \n", "\n", "dirpath: ./SwitchZeug/SwitchZeug , dirnames: [] , filenames: ['interface.py', 'switch.py', 'error.py', 'database.py.~1~', 'michi.py', 'database.py', '__init__.py'] \n", "\n", "dirpath: ./SwitchZeug/data , dirnames: [] , filenames: ['ifAdminStatus.txt', 'ifDescr.txt', 'ifLastChange.txt', 'snmpEngineTime.txt', 'ifOperStatus.txt'] \n", "\n", "dirpath: ./Exercises , dirnames: [] , filenames: ['20.py', 'prime.py', 'uniq.py', 'digit.py'] \n", "\n" ] } ], "source": [ "# noch besser: rekursives Iterieren!!\n", "for dirpath, dirnames, filenames in os.walk('.'):\n", " print('dirpath:', dirpath, ', dirnames:', dirnames, ', filenames:', filenames, '\\n')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## `enumerate()`, `zip()`\n", "Feine kleine Helferlein ... (hochtrabend nennt sich das \"Funktionales Programmieren\")\n", "* [`enumerate()`](https://docs.python.org/3/library/functions.html#enumerate)\n", "* [`zip()`](https://docs.python.org/3/library/functions.html#zip)\n", "* [Mehr davon](https://docs.python.org/3/library/functools.html#module-functools)" ] }, { "cell_type": "code", "execution_count": 138, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 200\n", "2 300\n", "3 400\n" ] } ], "source": [ "l = [200, 300, 400]\n", "for num, elem in enumerate(l, start=1):\n", " print(num, elem)" ] }, { "cell_type": "code", "execution_count": 139, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 eins\n", "2 zwei\n", "3 drei\n" ] } ], "source": [ "l1 = [1,2,3]\n", "l2 = ['eins', 'zwei', 'drei']\n", "for links, rechts in zip(l1, l2):\n", " print(links, rechts)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## List Comprehension" ] }, { "cell_type": "code", "execution_count": 140, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 4, 9, 16]\n" ] } ], "source": [ "# umstaendlich\n", "\n", "l = [1,2,3,4]\n", "l_quadrat = []\n", "for n in l:\n", " l_quadrat.append(n**2)\n", "print(l_quadrat)" ] }, { "cell_type": "code", "execution_count": 141, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 4, 9, 16]\n" ] } ], "source": [ "# einfach\n", "\n", "l_quadrat = [n**2 for n in l]\n", "print(l_quadrat)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## `exec()`, `eval()`\n", "\n", "* **Frage**: (Michi) mein Programm hat eine komplizierte Konfiguration (Anm.: assoziiert Firmware-Versionen mit Files, und macht Updates basierend darauf), die im Programm aufgebaut wird. Wie kann ich die Konfiguration aus dem Programm rausnehmen und die Python-Variablen von einem Konfigurationsfile lesen?\n", "* **Antwort**: [`eval()`](https://docs.python.org/3/library/functions.html#eval) und [`exec()`](https://docs.python.org/3/library/functions.html#exec)\n", "* Siehe [Beispiel mit `exec()`](SwitchZeug/michi-switch-upgrade-von-pyexec.py)\n", "* Siehe [Beispiel mit `configparser`: Windows .ini](SwitchZeug/michi-switch-upgrade-von-ini.py)" ] }, { "cell_type": "code", "execution_count": 142, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 142, "metadata": {}, "output_type": "execute_result" } ], "source": [ "expression = '1 == 2'\n", "eval(expression)" ] }, { "cell_type": "code", "execution_count": 143, "metadata": {}, "outputs": [], "source": [ "liste_als_string = '[1,2,3]'" ] }, { "cell_type": "code", "execution_count": 144, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3]" ] }, "execution_count": 144, "metadata": {}, "output_type": "execute_result" } ], "source": [ "liste = eval(liste_als_string)\n", "liste" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Umgebender Context" ] }, { "cell_type": "code", "execution_count": 145, "metadata": {}, "outputs": [], "source": [ "herbert = 666" ] }, { "cell_type": "code", "execution_count": 146, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "666" ] }, "execution_count": 146, "metadata": {}, "output_type": "execute_result" } ], "source": [ "eval('herbert') # Variable 'herbert' liegt heraussen" ] }, { "cell_type": "code", "execution_count": 147, "metadata": {}, "outputs": [], "source": [ "exec('joerg = 42') # Variable 'joerg' wird heraussen definiert" ] }, { "cell_type": "code", "execution_count": 148, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "42" ] }, "execution_count": 148, "metadata": {}, "output_type": "execute_result" } ], "source": [ "joerg" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Eigener Context" ] }, { "cell_type": "code", "execution_count": 149, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1998" ] }, "execution_count": 149, "metadata": {}, "output_type": "execute_result" } ], "source": [ "eval('joerg*3', {'joerg': 666})" ] }, { "cell_type": "code", "execution_count": 150, "metadata": {}, "outputs": [], "source": [ "del joerg # cleanup what I did above" ] }, { "cell_type": "code", "execution_count": 151, "metadata": {}, "outputs": [], "source": [ "context = {}\n", "exec('joerg = 42', context)" ] }, { "cell_type": "code", "execution_count": 152, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "42" ] }, "execution_count": 152, "metadata": {}, "output_type": "execute_result" } ], "source": [ "context['joerg']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## `json`\n", "Das ist das Leichteste was es gibt ..." ] }, { "cell_type": "code", "execution_count": 153, "metadata": {}, "outputs": [], "source": [ "mein_dict = {\n", " 'joerg': 666,\n", " 'gerhard': {\n", " 'age': 32,\n", " 'size': 175,\n", " }\n", "}" ] }, { "cell_type": "code", "execution_count": 154, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'{\"joerg\": 666, \"gerhard\": {\"age\": 32, \"size\": 175}}'" ] }, "execution_count": 154, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import json\n", "\n", "dict_as_json_string = json.dumps(mein_dict)\n", "dict_as_json_string" ] }, { "cell_type": "code", "execution_count": 155, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'joerg': 666, 'gerhard': {'age': 32, 'size': 175}}" ] }, "execution_count": 155, "metadata": {}, "output_type": "execute_result" } ], "source": [ "gelesenes_dict_von_json = json.loads(dict_as_json_string)\n", "gelesenes_dict_von_json" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" } }, "nbformat": 4, "nbformat_minor": 2 }