PythonBeispiele
dateandtime.py: Umgang mit Datum und Zeit
import datetime
def main():
now = datetime.datetime.now()
print(now.strftime("Now is: %Y.%m.%d %H:%M:%S"))
firstJan = datetime.datetime(now.date().year, 1, 1, 0, 0, 0, 0)
# diff is a timedelta object:
diff = now - firstJan
print(firstJan.strftime("first day of the year: %Y.%m.%d %H:%M:%S"))
print("the year is {:d} days and {:d} seconds old".format(diff.days, diff.seconds))
main()
linkfinder.py: XML-Auswertung
Findet die Links in einer XHTML-Anwendung
import xml.etree.ElementTree
import sys
class LinkFinder:
"""Gets the links of an XHTML document and print them.
"""
def __init__(self):
"""Constructor.
@param filename: name of the XHTML file to check
"""
self._counter = 0
def checkFile(self, filename):
"""Checks the links of a given XHTML file:
@param filename: name of the XHTML file to check
"""
tree = xml.etree.ElementTree.parse(filename)
root = tree.getroot()
self.findLinks(root)
self.findByXPath(root)
#try:
#except Exception as ex:
#print("+++ " + str(ex))
def findLinks(self, node):
if node.tag == "{http://www.w3.org/1999/xhtml}a":
self.checkLink(node)
elif node.tag == "{http://www.w3.org/1999/xhtml}img":
self.checkImg(node)
else :
for child in node:
self.findLinks(child)
def checkLink(self, node):
self._counter += 1
if "href" in node.attrib:
print("{:d}: {:s}".format(self._counter, node.attrib["href"]))
else:
print("+++ no href in link but: " + " ".join(node.attrib))
def checkImg(self, node):
self._counter += 1
print("{:d}: {:s}".format(self._counter, node.attrib["src"]))
def findByXPath(self, root):
print("Searching via XPath...")
self._counter = 0
for node in root.findall(".//{http://www.w3.org/1999/xhtml}a"):
self.checkLink(node)
for node in root.findall(".//{http://www.w3.org/1999/xhtml}img"):
self.checkImg(node)
def main(argv):
checker = LinkFinder()
name = argv[1] if len(argv) > 1 else "example.xhtml"
checker.checkFile(name)
if __name__ == "__main__":
main(sys.argv)
config_regexpr.py: Anwendung von regulären Ausdrücken
Mit Hilfe von reg. Ausdrücken werden Konfigurationsdateien im *.ini-Format eingelesen.
import re
class Config:
"""Manages a configuration file in the "Windows ini format".
Example:
[connection]
ip=localhost
port=6400
"""
def __init__(self, filename):
"""Constructor.
@param filename: the name of the configuration file (with path)
"""
self._sections = dict()
self.read(filename)
def read(self, filename):
"""Reads the configuration file and stores it in a dictionary of dictionaries
@param filename: the name of the configuration file (with path)
"""
varExpr = re.compile(r"([\w-]+)\s*=\s*(.*)")
sectionExpr = re.compile(r"\[([^\]]+)\]")
lastSection = "!default!"
lastDict = dict()
self._sections[lastSection] = lastDict
with open(filename, "r") as fp:
for line in fp:
matcher = sectionExpr.match(line)
if matcher:
section = matcher.group(1).lower()
lastDict = dict()
self._sections[section] = lastDict
continue
matcher = varExpr.match(line)
if matcher:
lastDict[matcher.group(1).lower()] = matcher.group(2)
def valueOf(self, variable, section = "!Default!"):
"""Gets the value of a configuration variable.
@param variable: the variable name
@param section: the section of the variable
@return: None: not found
otherwise: the value of the variable
"""
rc = None
section = section.lower()
if section in self._sections:
variable = variable.lower()
dictionary = self._sections[section]
if variable in dictionary:
rc = dictionary[variable]
return rc
def test():
fn = "/tmp/test.ini"
with open(fn, "w") as fp:
fp.write("""[Connection]
IP=localhost
Port=6400
""")
config = Config(fn)
ip = config.valueOf("ip", "Connection")
assert ip == "localhost"
port = int(config.valueOf("port", "Connection"))
assert port==6400
assert None == config.valueOf("ip", "x")
assert None == config.valueOf("x", "Connection")
if __name__ == "__main__":
test()
thread.py: Parallele Programmausführung
Ein Subnetz wird parallel mittels des externen Programms ping nach Hosts abgesucht.
import os
import re
import threading
rexpr = re.compile(r"(\d+) received")
locker = threading.Lock()
ready = []
class CheckIp (threading.Thread):
def __init__(self, ip):
threading.Thread.__init__(self)
self._ip = ip
self._pings = -1
def run(self):
out = os.popen("ping -q -c2 "+self._ip,"r")
while True:
line = out.readline()
if line == None:
break
matcher = rexpr.search(line)
if matcher:
self._pings = int(matcher.group(1))
if self._pings > 0:
#global locker
with locker:
print(self._ip)
global ready
break
ready.append(self)
def ips(prefix="192.168"):
"Generating ip addresses with a given prefix"
for node1 in range(256):
for node2 in range(1, 254):
yield "{:s}.{:d}.{:d}".format(prefix, node1, node2)
def main():
threads = []
count = 0
finished = 0
for ip in ips():
count += 1
if count % 100 == 0:
with locker:
global ready
finished += len(ready)
for current in ready:
current.join()
ready = []
if count % 500 == 0:
print "= {:d} threads started, {:d} threads finished".format(count, finished)
checker = CheckIp(ip)
threads.append(checker)
checker.start()
main()
gui.py: GUI mittels QT für Python
Ein GUI-Taschenrechner, der komplexe Formeln beherrscht, wie z.B. 2.777+sin(3.14/3)+log(1.99e+7)
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from math import *
class Window(QWidget):
"""Main window handling
"""
def __init__(self, parent = None):
"""Constructor
@param parent: the window parent or <i>none</i>
"""
QWidget.__init__(self, parent)
self.setWindowTitle(self.tr("Calculator"))
self._labelFormula = QLabel(self.tr("Formula:"))
self._editFormula = QLineEdit()
self._editFormula.setToolTip(self.tr("Any mathematical formula like '2.777+sin(3.14/3)+log(1.99e+7)'"))
self._labelResult = QLabel(self.tr("Result:"))
self._labelResult2 = QLabel("")
self._buttonCalc = QPushButton(self.tr("Calc"))
self._buttonCalc.default = True
self._listHistory = QListWidget()
# Put the widgets in a layout (now they start to appear):
layout = QGridLayout(self)
layout.addWidget(self._labelFormula, 0, 0)
layout.addWidget(self._editFormula, 0, 1)
layout.addWidget(self._buttonCalc, 1, 1)
layout.addWidget(self._labelResult, 2, 0)
layout.addWidget(self._labelResult2, 2, 1)
# addWidget(row, col, rowspan, colspan):
layout.addWidget(self._listHistory, 3, 0, 2, 2)
layout.setRowStretch(4, 1)
self.connect(self._buttonCalc, SIGNAL("clicked()"), self.onClickCalc)
def onClickCalc(self):
"""Event handler for the button click
"""
try:
text = str(self._editFormula.text())
rc = str(eval(text))
self._labelResult2.setText(rc)
self._listHistory.addItem(text + " = " + rc)
except Exception as e:
self._labelResult2.setText("+++ " + repr(e))
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
# Let's resize the window:
window.resize(480, 250)
window.show()
sys.exit(app.exec_())