view · edit · history · print

Python 2 sample

import logging
logging.basicConfig(level=logging.INFO, format='==> %(asctime)s,%(msecs).03d - %(levelname)s - %(message)s', datefmt='%Y%m%dT%H%M%S')
# more logging options filename='example.log', filemode='w', 
# The default levels are NOTSET, DEBUG, INFO, WARNING, ERROR and CRITICAL.'START') # will not print anything
logging.warning('Watch out, we started.') # will print a message to the console
logging.debug('This message should not be seen')'test: nonewline')
print "hello",
print "there"'test: concatenation')
one = "hej"
two = "there"
z = "." * 10
print one + " " + two + z'test: print array')
mylist = [len(z),5,0]
for x in mylist:
  print x,
print ""'test: print formatted variables')
print "number of dots: %s are %d." % (z, mylist[0])'test: find caracter position and print')
find1 = "e"
print "finding '%s' in position: %s" % (two[two.count(find1)], two.count(find1))'test: split string print first array item')
sayhello = "hello creul world"
# splitting the var sayhello on spaces will result in a list like:
# ['hello', 'world']
print sayhello.split(" ")[0] # only take the first field'test: if ... else')
if "." in z:
  print "dots are found!"
  # include elsif
  print "no dots?"'test: functions and calling functions')
def callme(name, *morevars):
  print "Call me %s." %(name)
  print "(rest: %s)" % list(morevars)
# functions precede call :(
callme("john", "a", "b")
# HOWEVER... a main() function can precede function definitions 
# it can be called by adding this to the end of the script
#if __name__ == "__main__":
#  main()'test: regex')
sayhello = "hello creul world"
import re
patt = re.compile('hello[\t]*(.*)')
mobj = patt.match(sayhello)
print "match behind 'hello' = " +
obj2 ='Hello[\t]*(.*)', sayhello,re.I)
print "search 'Hello' = " +
print "1 line search behind 'hello(.*world)' = " +'hello(.*world)', sayhello).group()
m ='hxxxxxello(.*world)', sayhello)
if m:
  print "match found: %s" %(
  print "no match"'test: replacement and string edit')
sayhello = "hello creul world"
print "hello creul world".replace("creul", "nice")
print sayhello.lstrip("hello ")
print re.sub('\screul\s', '-', sayhello) + " (flags=re.I only work for 2.7, not 2.6)"
# re.I workarround for 2.6
regex = re.compile('\sCrEuL\s', re.I)
print regex.sub('-', sayhello) + " (with re.I flags)"
print re.sub('(?i)\sCreul\s', '-', sayhello) + " (with inline regex (?i) flags)"
print re.sub('\s[c|C]reul\s', '-', sayhello) + " (real regex!)"'test: external OS commands')
import os
os.system("date | tr ' ' '_'")
f = os.popen("date | tr ' ' '_'")
now =
print "Today is ", now
ret = os.system("badcommand #with strange return codes")
print "return code = %s" %(ret)
from subprocess import call
ret = call("badcommand #with correct return codes", shell=True)
print "return code = %s" %(ret)
import subprocess
p = subprocess.Popen("badcommand #with correct return codes", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in p.stdout.readlines():
    print line
for line in p.stderr.readlines(): #alternatively you can redirect stderr=subprocess.STDOUT
    print line + " -- ohoh, that ain't good"
ret = p.wait()
print "return code = %s" %(ret)
# alternatively we can also use expect to spawn or run a process, example:
# child = pexpect.spawn('ftp')
# PS: import pexpect is NOT standard'test: edit file inplace, line-by-line')
import fileinput
os.system("test -f foo.orig && cp -f foo.orig foo")
  for line in fileinput.input("foo",inplace=1):
    print "%d: %s" %(fileinput.lineno(),line),
    # previous print seems to go into the file?!?
  os.system("test -f foo && cat foo")
  print "Oops, no file. Maybe the filecopy failed and you are not on UNIX?!"'test: edit file inplace, as string chunck')
  with open("foo", "r+") as f:
    new_txt =
    new_txt = new_txt + "xxxx\n"
    print new_txt # just informational print to stdout
    f.truncate(0) # delete/empty file before writing
    # by using r+ and skipping the previous truncate you can choose to append
  print "Oops, no file. Maybe the filecopy failed and you are not on UNIX?!"'test: compress existing file')
# and os-call would be more easy to do here!
  import gzip
  f_in = open('foo', 'rb')
  f_out ='foo.gz', 'wb')
  os.system("ls -l foo*")
  print "Oops, no file. Maybe the filecopy failed and you are not on UNIX?!"'test: input data')
str = raw_input("type something: ")
print "You typed: ", str'test: todo - CLI arguments')
import getopt, sys
  opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError, err:
  print err
print "options and arguments for: ", sys.argv[0]
print opts
print args'test: todo - switch/case statement?')
print " if ... elif ... elif ... else ..."
print "see also:"'test: todo - tkinter')
print "see other testscript t4*.py"'test: todo - debug')
print "see logging, but is there an actual interactive debugger?"
print "yes, run: python -m pdb"
print "other options are: Pydb, ddd, ipython -- even in combination"
print "Winpdb also looks interesting with remote debugging"'test: todo - time conversion')'test: todo - associative arrays or key/value pairs')
print "In Smalltalk, Objective-C, .NET, Python, and REALbasic they are called dictionaries"
print "in Perl and Ruby they are called hashes"
print "in C++, Java, Go, Clojure and Scala they are called maps"
print "in Common Lisp and Windows PowerShell, they are called hash tables"
print "In PHP, all arrays can be associative, except that the keys are limited to integers and strings"
print "In Lua, they are called tables"
print "In Visual FoxPro, they are called Collections"
print "In JavaScript (see also JSON), all objects behave as associative arrays."'test: todo - JSON & XML')'test: todo - gethostbyname / addr')
import socket
print socket.gethostname()
HOST = socket.gethostbyname(socket.gethostname())
print HOST
print socket.gethostbyaddr("")'test: todo - sockets')'test: todo - pip')'test: todo - twisted event framework')'test: todo - html string.Template systems (and CGI)')'test: todo - Pyramid (=Pylons), Bottle, Turbogears, Django')'test: sleep')
import time
time.sleep(0.2) # 0.2 = 200 milli-second'END') # will not print anything

admin · attr · attach · edit · history · print
Page last modified on May 08, 2019, at 12:17 PM