Inhaltsverzeichnis
Python
Installation
Python
Applications for Python
https://www.python.org/about/apps/
Python for Non-Programmers
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
https://www.geeksforgeeks.org/python-3-basics/?ref=lbp
Am besten installiert man Python auf Windows mithilfe einer Python-Distribution wie Anaconda oder schlanker mit Miniconda.
Miniconda is a free minimal installer for conda. It is a small, bootstrap version of Anaconda that includes only conda, Python …
https://docs.conda.io/en/latest/miniconda.html
https://stackoverflow.com/questions/45421163/anaconda-vs-miniconda
https://www.educative.io/answers/anaconda-vs-miniconda
https://winstall.app/apps/Anaconda.Miniconda3
Chocolaty führt die Pakete im Angebot Conda.
python --version # Python Version ermitteln
Installiere folgende Tools in der Reihenfolge:
- Install Visual Studio Code on Windows
- Install the Python Extension „IntelliSense (Pylance)“ direkt in VS Code Link
Nach erfolgreicher Installation starte
- Anaconda Prompt (miniconda3)
- Ziehe die „Visual Studio Code“-Verknüpfung ins Fenster und drücke Enter
Befehle für die Anaconda Prompt
echo %PATH% # Zeigt die Umgebungsvariable Pfad an where python # Sucht nach "Python"
Pakete
Mehrere Module zusammen können als Paket gespeichert werden. Ein Paket entspricht einem Verzeichnis mit mehreren Python-Dateien. Ein Paket kann mit Unterverzeichnisse strukturiert werden. Jedes Verzeichnis benötigt eine Datei namens „init.py“
Die Site-Pakete für Alle (global) sind in sys.path aufgelistet. Um Alle installierten Python Pakete aufzulisten:
python -m site
Um die benutzerspezifisch (local) PEP370 installierten Python Pakete aufzulisten:
python -m site --user-site
oder
import sysconfig print(sysconfig.get_path('purelib')) print(sysconfig.get_path("scripts"))
Optimiert in einer Zeile und direkt in der PowerShell ausführbar.
python -c "import sysconfig; print(sysconfig.get_path('purelib'); print(sysconfig.get_path('scripts'))"
Pakete werden mit der Paketverwaltung conda installiert. Conda war ursprünglich ein Teil der Python-Distribution Anaconda. Mittlerweile ist es ein eigenständiges Open-Source-Softwarepaket.
conda-forge ist eine GitHub-Organisation https://conda-forge.org/#about
conda --version # Zeigt die Version an conda clean --all # Entferne nicht verwendete Pakete und Caches conda config --add channels conda-forge # Channel conda-forge hinzufügen conda config --set channel_priority strict # Channel als Default setzen conda install <package-name> # Pakete aus dem Channel installieren conda install -c conda-forge conda # Installiere conda aus dem Channel conda-forge conda update -c conda-forge conda # Update conda aus dem Channel conda-forge conda update conda # Aktualisiere conda conda install -c microsoft playwright # Installiere playwright aus dem Channel Microsoft conda update --all # Aktualisiere alle Pakete conda list # Zeige alle lokal installierten Pakete conda list -f ^pandas$ # Zeige die Pakete, welche dem Regex entsprechen conda list pan # Zeigt alle Pakete, die "pan" im Namen enthalten conda search # Zeige alle verfügbaren Pakete von Anaconda conda search --outdated # lists all available versions conda search openpyxl # Zeige alle Versionen von openpyxl conda remove package # Ein Paket deinstallieren
Channels
| Name | Link |
| Suche am Beispiel von pywin32 | https://anaconda.org/search?q=pywin32 |
| conda-forge (20303) | https://anaconda.org/conda-forge/ |
| Anaconda (2937) | https://anaconda.org/anaconda |
| Microfot (37) | https://anaconda.org/Microsoft/ |
Python environments
Ein Environment bzw. eine Umgebung ist der Ort, an dem ein Python-Programm läuft und besteht aus einem Interpreter und einer beliebigen Anzahl von installierten Paketen.
Creating virtual environments
https://docs.python.org/3.4/library/venv.html
https://peps.python.org/pep-0405/
https://virtualenv.pypa.io/en/latest/#
python -m venv NeueUmgebung
Conda Informationen
conda info --all # Show all information conda info --system # List environment variables. conda info --base # Display base environment path conda info --envs # List all known conda environments. Bei der aktiven Umgebung steht ein * davor. conda info --unsafe-channels # Display list of channels with tokens exposed.
Umgebung erstellen
conda create --name snakes python=3.9 # Erstelle eine Umgebung mit dem Namen "snakes" und installiere das Paket Python 3.9 conda create --name Test01 python # Installiert das aktuelleste Python Paket in der Umgebung "Test01" conda create --name bio biopython # Inst. das Paket [[https://biopython.org/|BioPython]] in der Umgebung "bio" conda create --name Test02 # Erstelle nur die Umgebung "Test02"
Umgebung kopieren
conda create --clone Test02 --name Test03
Aktivere eine andere Umgebung
conda activate snakes conda activate Test03
Aktiviere die Default Python Umgebung (base):
deactivate # oder conda activate
Umgebung löschen
conda remove -n Test01 --all conda remove -n Test02 --all -y # lösche ohne nachzufragen
IPython
Kommandozeileninterpreter IPython
https://de.wikipedia.org/wiki/IPython, https://ipython.org/
conda install IPython conda update IPython
Jupyter Notebooks
JupyterLab is the latest web-based interactive development environment for notebooks, code, and data.
https://jupyter.org/, https://jupyter.org/try-jupyter/lab/
conda install Jupyter conda update Jupyter
Starte ein Jupyter-Notebook-Server
(base)> e: (base)> cd e:\OneDrive\Codes\JupyterLab2 (base)> jupyter notebook
In the first cell of the notebook, you can import pandas and check the version with:
import numpy as np import pandas as pd pd.set_option('html', False) pandas.__version__
Beispiel gemäss https://pandas.pydata.org/getting_started.html
import numpy as np import pandas as pd pd.set_option('html', False)
Jupyter Befehle
print("Hello World!")
help('modules panda')
NumPy
The fundamental package for scientific computing with Python NumPy (Numerical Python) is an open source Python library that’s used in almost every field of science and engineering. https://numpy.org/
conda install numpy conda update numpy import numpy as np
Pandas
Pandas is a data analysis and modeling library. https://pandas.pydata.org/
conda install Pandas conda update Pandas import pandas as pd
pandasql
Damit können pandas DataFrames mit Hilfe von SQL abgefragt werden. https://pypi.org/project/pandasql/
conda install pandasql conda update pandasql
On your Jupyter Notebook and in any cell run. Die Bedeutung des Ausrufezeichens ist mir nicht klar!
!pip install -U pandasql
pywin32
A set of extension modules that provides access to many of the Windows API functions.
https://anaconda.org/conda-forge/pywin32, https://github.com/mhammond/pywin32, https://anaconda.org/search?q=pywin32
conda install -c conda-forge pywin32 # Version 304 conda install -c anaconda pywin32 # Version 305 import pywin32 import win32com.client as win32
xlutils
This package collects utilities that require both xlrd and xlwt, including the ability to copy and modify or filter existing excel files. NB: In general, these use cases are now covered by openpyxl!
https://anaconda.org/conda-forge/xlutils, https://www.python-excel.org/
conda install xlutils conda update xlutils
openpyxl
A Python library to read/write Excel 2010 xlsx/xlsm files
https://openpyxl.readthedocs.io/en/stable/index.html#
conda install openpyxl conda update openpyxl import openpyxl as xl
xlwings
xlwings is a Python library that makes it easy to call Python from Excel and vice versa
https://docs.xlwings.org/en/stable/
conda install -c conda-forge xlwings conda update -c conda-forge xlwings import xlwings as xw
re
Regular expression operations Regex, https://pypi.org/project/regex/
conda install re conda update re import re
PyPI
Der Python Package Index (PyPI) ist ein Software-Verzeichnis der Programmiersprache Python. PyPI steht für Python Package Index und ist ein riesiges Repository, in das jeder Open-Source-Python-Pakete hochladen kann, die Python mit zusätzlicher Funktionalität ausstatten.
https://pypi.org/
conda install PyPI conda update PyPI
Requests
Abrufen von Daten aus Internetquellen
https://anaconda.org/anaconda/requests, https://requests.readthedocs.io/en/latest/
conda install Requests conda update Requests
playwright
https://anaconda.org/microsoft/playwright, https://pypi.org/project/playwright/, https://playwright.dev/python/docs/library
conda install -c Micoroft playwright conda update -c Micoroft playwright playwright install
import asyncio from playwright.async_api import async_playwright async def main(): async with async_playwright() as p: browser = await p.chromium.launch() page = await browser.new_page() await page.goto("http://playwright.dev") print(await page.title()) await browser.close() asyncio.run(main())
plotly
Open Source Graphing Library
https://anaconda.org/anaconda/plotly, https://plotly.com/python/
conda install plotly conda update plotly
Module
Eine thematische Sammlung von Funktionen kann man in Module zusammenfassen. Ein Modul wird als Python Datei „modul.py“ gespeichert.
Suchpfad für eigene Module
Liegt das eigene Modul nicht im gleichen Verzeichnis wie das Python-Script, so muss vor dem Import der Pfad dem Suchpfad hinzugefügt werden:
https://www.geeksforgeeks.org/sys-path-in-python/
import sys sys.path.append('.\Python\modules') # sys.path.append('e:\OneDrive\Codes\Python\modules') import mbe_module as mbe
Start-Code eines Moduls
Wenn ein Modul (Python-Script) direkt ausgeführt werden soll, dann kann man eine Triage einfügen. Damit kann man zum Beispiel Funktionstest einbauen.
if __name__ == '__main__': print("Das Modul funktioniert nur als Import.")
pip
Module werden mit dem Paketverwaltungsprogramm pip installiert.
pip --version pip list # Alle installierten Module auflisten pip freeze # Alle installierten Module auflisten pip install <package> # Die neuste Version des Modules installieren pip install <package>==1.0.0 # Eine bestimmte Modul Version installieren pip list --outdated # Listet die Module mit neu verfügbarer Version auf pip install --upgrade <package> # Modul updaten pip install --upgrade pip # Pip Modul updaten pip uninstall <package> # Modul deinstallieren pip show pandas # It will show the location of where it was installed.
WARNING: Ignoring invalid distribution -heel (c:\tools\miniconda3\lib\site-packages) This happens because when pip updates or deletes a package, it renames the package name by replacing the first letter with a ‘ ~ ‘ or ’tilde,’ which is normal behavior. The problem here is that pip is renaming its own package (pip → ~ip) without restoring it. Gehe zu c:\tools\miniconda3\lib\site-packages und entferne die ~ bei den entsprechenden Verzeichnissen
pyxlsb
https://pypi.org/project/pyxlsb/
pip install --upgrade pyxlsb
pytrends
Unofficial API for Google Trends
https://pypi.org/project/pytrends/
pip install --upgrade pytrends
selenium
Selenium automatisiert/fernsteuert den Browser über Python. →Alternative zu Playwright
https://www.python-lernen.de/selenium-fernsteuern-browser.htm
pip install --upgrade selenium
python-dateutil
https://docs.python.org/3/library/datetime.html, https://dateutil.readthedocs.io/en/stable/, https://pypi.org/project/python-dateutil/
pip install --upgrade python-dateutil import datetime as dt
more-itertools
https://docs.python.org/3/library/itertools.html#module-itertools, https://pypi.org/project/more-itertools/
pip install --upgrade more-itertools import itertools
Namenskonvention
- Funktionen und Variablen werden kleingeschrieben und enthalten zwischen den Wörtern einen Unterstrich
- Interne Funktionen beginnen mit einem Unterstrich _
- Funktionen werden klein geschriben
- Vor einer Funktion zwei Leerzeilen
- Jeder Import auf eine eigene Zeile „Import sys, os“ →nok
- Modul Importe in folgender Reihenfolge, mit einer Leerzeile zwischen den drei Gruppen:
- Standardbibliotheken
- Installierte Import von Dritten
- Eigene Module
- Wildcard imports „from <module> import *“ sollten vermieden werden
- Zwischen Variable, Zuweisungszeichen und Wert, nur einen Leerschlag
- Kein Leerschlag zwischen Zuweisungszeichen für Funktionsparameter Standardwerte
Funktionen
Docstring
Die zweite Leerzeilen ist nötig. Ansonsten wird kein Umbruch in der Vorschau angezeigt. Link
def abc(a: int, c = [1,2]): """Zusammenfassung der Funktion Parameters: a : int, Beschreibung c : list[int], optional, Defaults [1,2], Beschreibung Raises: AssertionError: Beschreibung Returns: int: Beschreibung """ if a > 10: raise AssertionError("a is more than 10") return c
Pandas
Playwright for Python
Playwright enables reliable end-to-end testing for modern web apps. Link
Introduction to Playwright: What is Playwright? Link
Such Resultate „playwright+python“ Link
Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API. Link
Playwright Selectors ab Seite 94 Link
Playwright Tutorial for Beginners Link
Let's Learn: Playwright Link
Playwright vs Selenium: A Comparison Link1 Link2
Automation Testing
Cross-browser (Chromium, WebKit and Firefox), cross-platform (Windows, Linux and macOS, locally or on CI, headless or headed), cross-language (TypeScript, JavaScript, Python, .NET, Java), Test Mobile Web
Powerful Tooling
| Tool | Beschreibung |
|---|---|
| Codegen | Generate tests by recording your actions. Save them into any language. playwright codegen https://portal.int.avideno.com/ |
| Playwright inspector | Inspect page, generate selectors, step through the test execution, see click points, explore execution logs. |
| Trace Viewer | Capture all the information to investigate the test failure. Playwright trace contains test execution screencast, live DOM snapshots, action explorer, test source, and many more. |
Praxisbeispiel
# Open Playwright Inspector await page.pause() # Lade die Website der url und warte bis sie geladen wurde await page.goto(url=url, wait_until="domcontentloaded") # Anmeldung ausfüllen, auf Login klicken und eine Sekunde warten await page.fill('input[type="text"]', user) await page.fill('input[type="password"]', pw) await page.click('button[type="button"]') await page.wait_for_timeout(1000) # Warte auf das Element und klicke anschliessend auf das Icon await page.wait_for_selector('button .icon_plus', timeout=0) await page.click('button .icon_plus') # Wähle den Radio Button, die Datei für den Upload und fülle den Namen ab await page.check('#radio-creation-import') await page.locator('input.import-project-file').set_input_files(r"e:\Datei1.pdf") await page.fill('text="Name:"', "Mustermann") # Der Speichern Button an zweiter Stelle soll gedrückt werden # funktioniert nur für de und en #await page.locator('button:has-text("Projekt speichern"), button:has-text("Save project")').select_text() await page.click('div.dxbs-modal-footer > button >> nth=1') # sprachunabhängig # Warte auf die Rückemldung await page.wait_for_selector("div .bg-success", timeout=0) # Kurz warten und dann abmelden await page.wait_for_timeout(3000) #await page.click('text=Abmelden') # funktioniert nur für de await page.click('span.dx-image.fas.fa-sign-out-alt.dx-menu-item-image') # sprachunabhängig
Links
| Link | Kommentar |
|---|---|
| Auto-waiting | Checks the elements before making actions to ensure these actions behave as expected. |
| Locators | Locators are the central piece of Playwright's auto-waiting and retry-ability. |
| page-locator | page.locator(selector: str, has_text: str, has: Locator) → Locator |
| Selectors | Selectors are strings that are used to create Locators. |
| Working with selectors | Checkly, content around Playwright & Puppeteer |
| Text selector | Text selector locates elements that contain passed text. |
| CSS selector | CSS selector |
| Selecting visible elements | Selecting visible elements |
| N-th element selector | N-th element selector |
| Multi condiitions | Selecting elements matching one of the conditions |
| Chaining selectors | |
| Best practices | Best practices |
| Automate logging in | Interaction with a login form |
| Input | Fill out the form fields |
environment variables
import os # Set environment variables os.environ['Street'] = 'Dorfstrasse' # To see all environment variables on your system print("\nUmgebungsvariabeln:") for k, v in sorted(os.environ.items()): print(f'{k}={v}') # To see a single environmental variable print("\nUsername: ", os.environ.get('USERNAME')) # Check if environmental variable exist env_var = input('Please enter the environment variable you are looking for:\n') # ->Enter 'Lego' or 'TMP' if env_var in os.environ: print(f'\n{env_var} value is {os.environ[env_var]}') else: print(f'\n{env_var} does not exist') os.environ[env_var] = "Technik" print(env_var, " = ", os.environ[env_var])
.env files
https://playwright.dev/docs/test-parameterize#env-files
https://www.nylas.com/blog/making-use-of-environment-variables-in-python/
https://www.twilio.com/blog/environment-variables-python
https://pypi.org/project/python-dotenv/
>>>pip install python-dotenv from dotenv import load_dotenv if load_dotenv(): print(os.environ.get("AVIDENO_int_url")) print(os.environ.get("AVIDENO_int_user")) print(os.environ.get("AVIDENO_int_password"))
- .env
# Development settings, Filename: ".env" AVIDENO_int_url=https://portal.int.avideno.com/ AVIDENO_int_user=vorname.nachname@avideno.com AVIDENO_int_password=xyxyxyxyxxyx
Kurse
| Kommentar | Link |
|---|---|
| Python Totorial by Bernd Klein | https://python-course.eu/ |
| Link | |
| Link |
Referenzen
Glossar
| Abkürzung | Bezeichnung |
|---|---|
| DOM | Document Object Model |
| PEP | Python Enhancement Proposals |
