Benutzer-Werkzeuge

Webseiten-Werkzeuge


Übersetzungen:
de

programming:python:start

Python

Kommentare

#print("Hello, World!")
"""
This is a comment
written in
more than just one line
"""

if / else / ternary

if condition_1:
    Statement 1
    Statement 2
elif condition_2:
    Statement 3
    Statement 4
else:
    Statement 5
    Statement 6

https://thispointer.com/python-ifelifelse-statement/

value_1 if condition else value_2

https://thispointer.com/python-if-else-in-one-line-a-ternary-operator/

Schleifen

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 = 'Sample Text'
# 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,last+1):
    print(i)

https://thispointer.com/python-programming/

Typumwandlung

integer

int(str, base=10)
value = '234'
# Convert string to integer
num = int(value)
value = '01110011'
num = int(value, base=2)
value = '0xFF11'
# Convert hex string to integer
num = int(value, base=16)

https://thispointer.com/python-string-to-int/

float

def is_float(value):
  try:
    float(value)
    return True
  except:
    return False
 
def string_to_number(str):
  if("." in str):
    try:
      res = float(str)
    except:
      res = str  
  elif(str.isdigit()):
    res = int(str)
  else:
    res = str
  return(res)
 
a = "545.2222"
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(".", "", value.count(".") -1)

https://stackoverflow.com/questions/7106417/convert-decimal-mark

Listen

# List of string 
listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from']
 
if 'at' in listOfStrings :
    print("Yes, 'at' found in List : " , listOfStrings)
 
if listOfStrings.count('at') > 0 :
    print("Yes, 'at' found in List : " , listOfStrings)

Quelle: https://thispointer.com/python-how-to-check-if-an-item-exists-in-list-search-by-value-or-condition/

ini

import configparser
 
config = configparser.ConfigParser()
config.read('mysql.conf')
print(config['mysql']['host'].strip('\"')) # löscht umfassende "" bei strings

MySQL

import pymysql
import configparser
 
config = configparser.ConfigParser()
config.read('mysql.conf')
 
db = pymysql.connect(config['mysql']['host'].strip('\"'),
                     config['mysql']['user'].strip('\"'),
                     config['mysql']['password'].strip('\"'),
                     config['mysql']['database'].strip('\"') )
#cursor = db.cursor()
cursor = db.cursor(pymysql.cursors.DictCursor)
sql = "SELECT * FROM users WHERE Nachname = %(lastname)s"
lastname="Wunderlich"
try:
    # Execute the SQL command
    cursor.execute(sql,{"id":1,"lastname":lastname})
    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("Exception: {}".format(type(exception).__name__))
    print("Exception message: {}".format(exception))
 
db.close()

vorherige Script Instanz beenden

import os
import psutil
#import time
 
application="python"
scriptfile=os.path.basename(__file__)
 
print(f"own pid ({scriptfile}):{os.getpid()}")
for p in psutil.process_iter():
#    print(p.pid,p.name(),p.cmdline())
    if p.name().startswith(application):
        print("Python: ",p.pid,p.name(),p.cmdline())
        if p.pid == os.getpid():
            print("own process")
        else:
            print("other process...")
            if scriptfile in p.cmdline():
                print("kill it...")
                p.terminate()
 
#while True:
#    time.sleep(5)
 
print("exit")

http-Abfragen

import requests #scriptname must not be requests.py or http.py!
 
url="https://api.github.com"
 
try:
    response = requests.get(url)
    # If the response was successful, no Exception will be raised
    response.raise_for_status()
except requests.HTTPError as e:
    #print(f'HTTP error occurred: {e}')
    status_code = e.response.status_code
    print("Status:",status_code)
except requests.Timeout as e:
    print('The request timed out')
except requests.ConnectionError as e:
    print(f"connection-error {e}")
except Exception as e:
    print(f'Other error occurred: {e}')  # Python 3.6
else:
    print('Success!')
    #print(response.text)
    print(response.headers['content-type'])
    json_data=response.json()
    print(json_data['issues_url'])
 
#get-param
response = requests.get(
    'https://api.github.com/search/repositories',
    params={'q': 'requests+language:python'},
    headers={'Accept': 'application/vnd.github.v3.text-match+json'},
)
json_response = response.json()
repository = json_response['items'][0]
print(f'Repository name: {repository["name"]}')
 
 
requests.post('https://httpbin.org/post', data={'key':'value'})
requests.put('https://httpbin.org/put', data={'key':'value'})
requests.delete('https://httpbin.org/delete')
requests.head('https://httpbin.org/get')
requests.patch('https://httpbin.org/patch', data={'key':'value'})
requests.options('https://httpbin.org/get')

Asynchrone (parallele) Abfragen:

time

import time
 
start = time.time()
#do something
end = time.time()
print(round((end - start) * 1000,2),"ms")

regex

https://docs.python.org/3/library/re.html

re.sub()
re.match()
# ersetzen mit backref benötigt r-string (r'')
>>> import re
>>> s="2020-10-11"
>>> re.sub('^(\d+)-(\d+)-(\d+)$',r'\3.\2.\1',s)
'11.10.2020'

externe Anwendung

import subprocess
subprocess.call(["ls", "-l"])

OOP

Beispiel-Klasse Fifo

class Fifo:
    def __init__(self,liste=[]):
        self.__liste=list(liste)#wichtig, damit leere liste erzeugt wird!!!
 
    def put_in(self,element):
        self.__liste.append(element)
 
    def take_out(self):
        if len(self.__liste)>0:
            return self.__liste.pop(0)
        else:
            print("Liste leer!")
 
    def interactive(self):
        while True:
            s=input("bitte Element eingeben (beenden mit leer, rausnehmen mit ?):")
            if s=='':
                break
            elif s=='?':
                print(self.take_out())
            else:
                self.put_in(s)
 
    def getElements(self):
        return self.__liste
    def __str__(self): #print(obj)
        return f"Ich bin eine {self.__class__.__name__} {self.__liste}"
 
    def __add__(self,other_fifo):
        if isinstance(other_fifo,Fifo):
            return Fifo(self.getElements() + other_fifo.getElements())
        else:
            print(f"Addition abgelehnt, element ist ein {other_fifo.__class__} ")
 
l=Fifo()
l.put_in("test1")
l.put_in("test2")
#print(l)
l.take_out()
print(l)
#l.interactive()
 
l2=Fifo()
print("l2,sollte leer sein:",l2)
l2.put_in("test3")
l2.put_in("test4")

nano

für Tab2Spaces + 4 Zeicheneinrückung verwende ich einen alias (~/.bashrc)

alias pynano="nano -ET4"
programming/python/start.txt · Zuletzt geändert: 2020/10/17 15:29 von frank