programming:python:start
Unterschiede
Hier werden die Unterschiede zwischen zwei Versionen angezeigt.
Beide Seiten der vorigen RevisionVorhergehende ÜberarbeitungNächste Überarbeitung | Vorhergehende Überarbeitung | ||
programming:python:start [2021/02/19 19:12] – [ini] frank | programming:python:start [2023/06/08 17:06] (aktuell) – Externe Bearbeitung 127.0.0.1 | ||
---|---|---|---|
Zeile 1: | Zeile 1: | ||
+ | ====== Python ====== | ||
+ | Web-Automation mit [[Selenium]] | ||
+ | |||
+ | GUI mit [[Tkinter]] | ||
+ | |||
+ | http mit [[requests]] | ||
+ | ===== Kommentare ===== | ||
+ | <code python> | ||
+ | # | ||
+ | """ | ||
+ | This is a comment | ||
+ | written in | ||
+ | more than just one line | ||
+ | """ | ||
+ | </ | ||
+ | |||
+ | ===== if / else / ternary ===== | ||
+ | |||
+ | <code python> | ||
+ | if condition_1: | ||
+ | Statement 1 | ||
+ | Statement 2 | ||
+ | elif condition_2: | ||
+ | Statement 3 | ||
+ | Statement 4 | ||
+ | else: | ||
+ | Statement 5 | ||
+ | Statement 6 | ||
+ | </ | ||
+ | |||
+ | https:// | ||
+ | |||
+ | value_1 if condition else value_2 | ||
+ | |||
+ | https:// | ||
+ | |||
+ | Switch/ | ||
+ | https:// | ||
+ | |||
+ | Multiline if: | ||
+ | https:// | ||
+ | ===== Schleifen ===== | ||
+ | |||
+ | <code python> | ||
+ | x = 1 | ||
+ | # Infinite While Loop | ||
+ | while True: | ||
+ | print(x) | ||
+ | # If x is 6, then break the loop | ||
+ | if x == 6: | ||
+ | break | ||
+ | x += 1 | ||
+ | |||
+ | sample_str = ' | ||
+ | # Iterate over all the characters in string | ||
+ | for elem in sample_str: | ||
+ | # If char is not lower case then skip printing | ||
+ | if elem.islower() == False: | ||
+ | continue | ||
+ | print(elem) | ||
+ | | ||
+ | for i in range(first, | ||
+ | print(i) | ||
+ | </ | ||
+ | |||
+ | https:// | ||
+ | ===== Typumwandlung ===== | ||
+ | |||
+ | ==== integer ==== | ||
+ | |||
+ | int(str, base=10) | ||
+ | | ||
+ | <code python> | ||
+ | value = ' | ||
+ | # Convert string to integer | ||
+ | num = int(value) | ||
+ | value = ' | ||
+ | num = int(value, base=2) | ||
+ | value = ' | ||
+ | # Convert hex string to integer | ||
+ | num = int(value, base=16) | ||
+ | </ | ||
+ | |||
+ | https:// | ||
+ | ==== float ==== | ||
+ | |||
+ | <code python> | ||
+ | def is_float(value): | ||
+ | try: | ||
+ | float(value) | ||
+ | return True | ||
+ | except: | ||
+ | return False | ||
+ | |||
+ | def string_to_number(str): | ||
+ | if(" | ||
+ | try: | ||
+ | res = float(str) | ||
+ | except: | ||
+ | res = str | ||
+ | elif(str.isdigit()): | ||
+ | res = int(str) | ||
+ | else: | ||
+ | res = str | ||
+ | return(res) | ||
+ | |||
+ | a = " | ||
+ | float(a) | ||
+ | 545.22220000000004 | ||
+ | |||
+ | # , in . (mit . als tausendtrenner) | ||
+ | # 1) Replace all commas for points: | ||
+ | value.replace(",", | ||
+ | # 2)Remove all but the last point: | ||
+ | value.replace(" | ||
+ | </ | ||
+ | |||
+ | https:// | ||
+ | |||
+ | ==== Formatstrings ==== | ||
+ | |||
+ | https:// | ||
+ | |||
+ | f"var: {var}" | ||
+ | |||
+ | string-of-char: | ||
+ | |||
+ | " | ||
+ | ===== Listen ===== | ||
+ | |||
+ | <code python> | ||
+ | # List of string | ||
+ | listOfStrings = [' | ||
+ | |||
+ | if ' | ||
+ | print(" | ||
+ | | ||
+ | if listOfStrings.count(' | ||
+ | print(" | ||
+ | </ | ||
+ | |||
+ | Quelle: https:// | ||
+ | |||
+ | ==== Liste von Objekten ==== | ||
+ | <code python> | ||
+ | content = [] | ||
+ | for i in find_all(' | ||
+ | info = { | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | } | ||
+ | content.append(info) | ||
+ | </ | ||
+ | |||
+ | ==== dict ==== | ||
+ | |||
+ | https:// | ||
+ | ===== ini ===== | ||
+ | |||
+ | <code python> | ||
+ | import configparser | ||
+ | |||
+ | config = configparser.ConfigParser() | ||
+ | config.read(' | ||
+ | print(config[' | ||
+ | </ | ||
+ | |||
+ | ===== json ===== | ||
+ | |||
+ | https:// | ||
+ | |||
+ | ===== grep ===== | ||
+ | |||
+ | https:// | ||
+ | |||
+ | ===== exceptions ===== | ||
+ | |||
+ | <code python> | ||
+ | def divide(a, | ||
+ | result=None | ||
+ | try: | ||
+ | result=a/b | ||
+ | except ZeroDivisionError as e: | ||
+ | print(" | ||
+ | except Exception as e: | ||
+ | print(type(e).__name__, | ||
+ | else: | ||
+ | print(" | ||
+ | finally: | ||
+ | print(" | ||
+ | return result | ||
+ | </ | ||
+ | |||
+ | <code python> | ||
+ | try: | ||
+ | ... | ||
+ | except Exception as e: | ||
+ | | ||
+ | </ | ||
+ | ===== MySQL ===== | ||
+ | <code python> | ||
+ | import pymysql | ||
+ | import configparser | ||
+ | |||
+ | config = configparser.ConfigParser() | ||
+ | config.read(' | ||
+ | |||
+ | db = pymysql.connect(config[' | ||
+ | | ||
+ | | ||
+ | | ||
+ | #cursor = db.cursor() | ||
+ | cursor = db.cursor(pymysql.cursors.DictCursor) | ||
+ | sql = " | ||
+ | lastname=" | ||
+ | try: | ||
+ | # Execute the SQL command | ||
+ | cursor.execute(sql, | ||
+ | print(cursor._last_executed) | ||
+ | # Fetch all the rows in a list of lists or as list of dict (if using the DictCursor). | ||
+ | results = cursor.fetchall() | ||
+ | for row in results: | ||
+ | print(row) | ||
+ | except Exception as e: | ||
+ | print(" | ||
+ | print(" | ||
+ | |||
+ | db.close() | ||
+ | </ | ||
+ | |||
+ | ===== vorherige Script Instanz beenden ===== | ||
+ | |||
+ | <code python> | ||
+ | import os | ||
+ | import psutil | ||
+ | #import time | ||
+ | |||
+ | application=" | ||
+ | scriptfile=os.path.basename(__file__) | ||
+ | |||
+ | print(f" | ||
+ | for p in psutil.process_iter(): | ||
+ | # print(p.pid, | ||
+ | if p.name().startswith(application): | ||
+ | print(" | ||
+ | if p.pid == os.getpid(): | ||
+ | print(" | ||
+ | else: | ||
+ | print(" | ||
+ | if scriptfile in p.cmdline(): | ||
+ | print(" | ||
+ | p.terminate() | ||
+ | |||
+ | #while True: | ||
+ | # time.sleep(5) | ||
+ | |||
+ | print(" | ||
+ | </ | ||
+ | |||
+ | ===== time ===== | ||
+ | |||
+ | <code python> | ||
+ | import time | ||
+ | |||
+ | start = time.time() | ||
+ | #do something | ||
+ | end = time.time() | ||
+ | print(round((end - start) * 1000, | ||
+ | </ | ||
+ | |||
+ | ===== Datetime ===== | ||
+ | |||
+ | formatstring parsen (3.6) und zeitzone umrechnen: | ||
+ | |||
+ | <code python> | ||
+ | from datetime import datetime, | ||
+ | |||
+ | def parseisodt(d): | ||
+ | dtfmt=' | ||
+ | if ":" | ||
+ | d = d[: | ||
+ | dt=datetime.strptime(d, | ||
+ | return dt | ||
+ | |||
+ | d=parseisodt(' | ||
+ | d=d.astimezone(tz=timezone.utc) | ||
+ | print(d) | ||
+ | </ | ||
+ | |||
+ | ab 3.7 gibt es dann [[https:// | ||
+ | ===== regex ===== | ||
+ | |||
+ | https:// | ||
+ | |||
+ | re.sub() | ||
+ | re.match() | ||
+ | |||
+ | # ersetzen mit backref benötigt r-string (r'' | ||
+ | >>> | ||
+ | >>> | ||
+ | >>> | ||
+ | ' | ||
+ | |||
+ | <code python> | ||
+ | REGEXP_TEST = re.compile(r''' | ||
+ | (? | ||
+ | ''', | ||
+ | |||
+ | def test(txt): | ||
+ | match = REGEXP_TEST.search(txt) | ||
+ | if match: | ||
+ | print(match.group(" | ||
+ | return match.groupdict() | ||
+ | else: | ||
+ | return false | ||
+ | </ | ||
+ | ===== externe Anwendung ===== | ||
+ | |||
+ | <code python> | ||
+ | import subprocess | ||
+ | subprocess.call([" | ||
+ | </ | ||
+ | |||
+ | ===== OOP ===== | ||
+ | |||
+ | Beispiel-Klasse Fifo | ||
+ | |||
+ | <code python> | ||
+ | class Fifo: | ||
+ | def __init__(self, | ||
+ | self.__liste=list(liste)# | ||
+ | | ||
+ | def put_in(self, | ||
+ | self.__liste.append(element) | ||
+ | |||
+ | def take_out(self): | ||
+ | if len(self.__liste)> | ||
+ | return self.__liste.pop(0) | ||
+ | else: | ||
+ | print(" | ||
+ | |||
+ | def interactive(self): | ||
+ | while True: | ||
+ | s=input(" | ||
+ | if s=='': | ||
+ | break | ||
+ | elif s=='?': | ||
+ | print(self.take_out()) | ||
+ | else: | ||
+ | self.put_in(s) | ||
+ | |||
+ | def getElements(self): | ||
+ | return self.__liste | ||
+ | def __str__(self): | ||
+ | return f"Ich bin eine {self.__class__.__name__} {self.__liste}" | ||
+ | | ||
+ | def __add__(self, | ||
+ | if isinstance(other_fifo, | ||
+ | return Fifo(self.getElements() + other_fifo.getElements()) | ||
+ | else: | ||
+ | print(f" | ||
+ | |||
+ | l=Fifo() | ||
+ | l.put_in(" | ||
+ | l.put_in(" | ||
+ | #print(l) | ||
+ | l.take_out() | ||
+ | print(l) | ||
+ | # | ||
+ | |||
+ | l2=Fifo() | ||
+ | print(" | ||
+ | l2.put_in(" | ||
+ | l2.put_in(" | ||
+ | </ | ||
+ | |||
+ | ===== Modularisierung ===== | ||
+ | Import: https:// | ||
+ | |||
+ | to import a class apibase from file apibase.py | ||
+ | |||
+ | from apibase import apibase | ||
+ | |||
+ | to import all from myhelper.py: | ||
+ | |||
+ | from myhelper import * | ||
+ | ===== dict anzeigen ===== | ||
+ | <code python> | ||
+ | import json | ||
+ | def formatdict(d): | ||
+ | # | ||
+ | formatted_str = json.dumps(d, | ||
+ | return formatted_str | ||
+ | </ | ||
+ | |||
+ | ===== Pfad des Scriptes ===== | ||
+ | <code python> | ||
+ | import os.path | ||
+ | p=os.path.dirname(os.path.abspath(__file__)) | ||
+ | </ | ||
+ | ===== nano ===== | ||
+ | |||
+ | für Tab2Spaces + 4 Zeicheneinrückung verwende ich einen alias (~/.bashrc) | ||
+ | |||
+ | alias pynano=" | ||
+ | |||
+ | ===== python2 venv ===== | ||
+ | |||
+ | https:// | ||
+ | |||
+ | < | ||
+ | wget https:// | ||
+ | tar -xzf Python-2.7.18.tgz | ||
+ | mkdir ~/ | ||
+ | ./configure --prefix=$HOME/ | ||
+ | make | ||
+ | make install | ||
+ | cd ~/ | ||
+ | bin/python -m ensurepip --upgrade #install 2.7 pip | ||
+ | #install python3 virtualenv | ||
+ | pip install virtualenv | ||
+ | python3 -m virtualenv ~/env27 -p $HOME/ | ||
+ | source ~/ | ||
+ | python -V | ||
+ | </ |
programming/python/start.txt · Zuletzt geändert: 2023/06/08 17:06 von 127.0.0.1