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.
logging.info('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')

logging.info('test: nonewline')
print "hello",
print "there"

logging.info('test: concatenation')
one = "hej"
two = "there"
z = "." * 10
print one + " " + two + z

logging.info('test: print array')
mylist = [len(z),5,0]
for x in mylist:
  print x,
print ""

logging.info('test: print formatted variables')
print "number of dots: %s are %d." % (z, mylist[0])

logging.info('test: find caracter position and print')
find1 = "e"
print "finding '%s' in position: %s" % (two[two.count(find1)], two.count(find1))

logging.info('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

logging.info('test: if ... else')
if "." in z:
  print "dots are found!"
  # include elsif
else:
  print "no dots?"

logging.info('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()

logging.info('test: regex')
sayhello = "hello creul world"
import re
patt = re.compile('hello[\t]*(.*)')
mobj = patt.match(sayhello)
print "match behind 'hello' = " + mobj.group(1)
obj2 = re.search('Hello[\t]*(.*)', sayhello,re.I)
print "search 'Hello' = " + obj2.group(1)
print "1 line search behind 'hello(.*world)' = " + re.search('hello(.*world)', sayhello).group()
m = re.search('hxxxxxello(.*world)', sayhello)
if m:
  print "match found: %s" %(m.group())
else:
  print "no match"

logging.info('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!)"

logging.info('test: external OS commands')
import os
os.system("date | tr ' ' '_'")
f = os.popen("date | tr ' ' '_'")
now = f.read()
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 192.168.0.24')
# PS: import pexpect is NOT standard

logging.info('test: edit file inplace, line-by-line')
import fileinput
os.system("test -f foo.orig && cp -f foo.orig foo")
try:
  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")
except:
  print "Oops, no file. Maybe the filecopy failed and you are not on UNIX?!"

logging.info('test: edit file inplace, as string chunck')
try:
  with open("foo", "r+") as f:
    new_txt = f.read()
    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
    f.write(new_txt)
    f.close()
except:
  print "Oops, no file. Maybe the filecopy failed and you are not on UNIX?!"

logging.info('test: compress existing file')
# and os-call would be more easy to do here!
try:
  import gzip
  f_in = open('foo', 'rb')
  f_out = gzip.open('foo.gz', 'wb')
  f_out.writelines(f_in)
  f_out.close()
  f_in.close()
  os.system("ls -l foo*")
except:
  print "Oops, no file. Maybe the filecopy failed and you are not on UNIX?!"

logging.info('test: input data')
str = raw_input("type something: ")
print "You typed: ", str

logging.info('test: todo - CLI arguments')
import getopt, sys
try:
  opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError, err:
  print err
  sys.exit(2)
print "options and arguments for: ", sys.argv[0]
print opts
print args

logging.info('test: todo - switch/case statement?')
print " if ... elif ... elif ... else ..."
print "see also: http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python"

logging.info('test: todo - tkinter')
print "see other testscript t4*.py"

logging.info('test: todo - debug')
print "see logging, but is there an actual interactive debugger?"
print "yes, run: python -m pdb t1.py"
print "other options are: Pydb, ddd, ipython -- even in combination"
print "Winpdb also looks interesting with remote debugging"

logging.info('test: todo - time conversion')

logging.info('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."

logging.info('test: todo - JSON & XML')

logging.info('test: todo - gethostbyname / addr')
import socket
print socket.gethostname()
HOST = socket.gethostbyname(socket.gethostname())
print HOST
print socket.gethostbyaddr("127.0.0.1")

logging.info('test: todo - sockets')

logging.info('test: todo - pip')

logging.info('test: todo - twisted event framework')

logging.info('test: todo - html string.Template systems (and CGI)')

logging.info('test: todo - Pyramid (=Pylons), Bottle, Turbogears, Django')


logging.info('test: sleep')
import time
time.sleep(0.2) # 0.2 = 200 milli-second
logging.info('END') # will not print anything

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