Examples added.

master
51x 2017-06-11 21:42:13 +02:00
parent f696061fa8
commit 28a8e55abb
30 changed files with 591 additions and 0 deletions

View File

@ -0,0 +1,51 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
var1 = "something"
print id(var1) # memory location
print hex(id(var1))
print var1.__repr__
var2 = r'raw, no new \n live'
print var2
var3 = """
multi
line
etc"""
print var3
var3 = unicode(var3) # unicode is used for internationalization, also dont forget line after #! !
print var1[1]
#var1[1]="f" # this won't work because python cant change only part of the memory of the string, just the whole
buf = "A" * 66
buf= "qwertyuiopaa"
print buf[5:10:2]
#vars = var1.split['a']
print var1.find('me')
print var1.split('me') # splits into list
print var1.split('me')[1] # split, then print list [1], starts from 0!
print var1.replace('some', 'any') # replaces, but it returns new object, not modifying original var1: immutable strings!
dis = "dis"
print "fug %s" % dis
l = "lol"
print "fug %s %s" % (dis, l)
print "fug %(dis)s %(l)s" % {"dis":"DIS","l":"lel"} # "s" is still required after the %() !
mylist = [1,2,3,4]
print len(mylist)
mylist2 = [1,2,3,[4,5]]
print len(mylist2)
print len(mylist2[3])
print mylist[1]
mylist.insert(2,"a") # etc
print mylist[2]

14
02_tuples_vars.py 100755
View File

@ -0,0 +1,14 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
tuple_variable = tuple(["1","2","3"])
print tuple_variable
one, two, three = tuple_variable
print one
print two
print three

17
03_sets.py 100755
View File

@ -0,0 +1,17 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
setA = set([1,2,3,3,2])
setB = set([3,4,5])
setA|setB # Union
setA&setB # Intersection
setA-setB # In set A, but not set B
setB-setA # In set B, but not set A
var = setA&setB
print var

28
04_dict.py 100755
View File

@ -0,0 +1,28 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
myBio = {'name' : "unknown", 'age' : 666, 'hobby' : 'hacking'}
print myBio
myBio.has_key('hobby')
myBio.has_key('notinside')
myBio.values()
print myBio.get('age')
del myBio['age'] # Delete age
print myBio
dict_tuple = myBio.items() # into tuples
print dict_tuple
'name' in myBio
print myBio.has_key('hobby')
print dir(myBio)
help(myBio.update)
help(myBio.has_key)

25
05_if_for_while.py 100755
View File

@ -0,0 +1,25 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
age = 4
if age == 4 :
print "go!"
else :
print ":>"
men = ['1', '2', '3']
for vvv in men:
print vvv
while True :
rawi = raw_input("something?")
print rawi
#while age > 2 :
# age = age + 1
# print "infinite" # thats how to broken pipe ( :
#print raw_input("something?")

8
06_range.py 100755
View File

@ -0,0 +1,8 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
print range(10)
print range(10)[4]
print range(0,10)
print range(0,10,2) # C like "for": lower,upper,rate/step

View File

@ -0,0 +1,33 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
def funkcion():
print "done"
funkcion()
def funkcion2(vvv):
print vvv
funkcion2("vav")
def funkcion3(vvv):
return vvv
print funkcion3("vuv")
out = funkcion3("viv")
print out
import sys # take argument from command line, handle if its not given
def fromsys(this):
print this
thisinto = ""
try:
thisinto = sys.argv[1]
except:
pass
fromsys(thisinto)

29
08_class_object.py 100755
View File

@ -0,0 +1,29 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Calculator:
def __init__(self, ina, inb):
self.a = ina
self.b = inb
def add(self):
return self.a + self.b
def mul(self):
return self.a*self.b
newCalculation = Calculator(22,44)
print 'a+b: %d'%newCalculation.add()
print 'a*b: %d'%newCalculation.mul()
class Scientific(Calculator) :
def power(self):
return pow(self.a, self.b)
newPower = Scientific(6,7)
print 'a+b: %d'%newPower.add()
print 'a*b: %d'%newPower.mul()

8
09_modules.py 100755
View File

@ -0,0 +1,8 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# modules are just files, import testmod --> testmod.py
# note that it cannot start with a number...
# that's it
# example with previous class: import filewithclass // var1 = filewithclass.Calculator(10,20) // print

8
10_exception.py 100755
View File

@ -0,0 +1,8 @@
#try:
#except:
#else:
#finally:
#except Exception as anything:

View File

@ -0,0 +1,11 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3
conn = sqlite3.connect('/System/Library/Frameworks/CoreLocation.framework/Support/timezone.db')
cur = conn.cursor()
for zone in cur.execute("select * from Names") :
print zone

View File

@ -0,0 +1,28 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Note, buffering in open() and byte_count in read() can be set
fdesc = open("/tmp/any.txt", "w")
print fdesc
for count in range(0,99):
fdesc.write(str(count) + "\n")
fdesc.close
fdesc = open("/tmp/any.txt", "a")
for count in range(0,999):
fdesc.write(str(count) + "\n")
fdesc.close
fdesc = open("/tmp/any.txt", "r")
for line in fdesc.readlines() :
print line.strip()
fdesc.close
import os
os.rename("/tmp/any.txt", "/tmp/nyuu.txt")
#os.remove("/tmp/any.txt")
# os.rmdir("/tmp/emptydir") # ... etc

View File

@ -0,0 +1,27 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
os.getcwd()
os.mkdir("NewDir")
os.rmdir("NewDir")
os.listdir(".") # List
os.listdir("/")
for item in os.listdir(".") :
if os.path.isfile(item) :
print item + " is a file."
elif os.path.isdir(item) :
print item + " is a dir."
else :
print "couldn't identify."
import glob
for item in glob.glob(os.path.join(".","*.py")) :
print item

View File

@ -0,0 +1,25 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
def child_proc():
print "I am the child with PID: %d" % os.getpid()
print "Child exits."
def parent_proc():
print "I am the parent with PID %d" % os.getpid()
childpid = os.fork() # Replica of the parent, runs after
if childpid == 0: # Runs if child is created and returned 0
print "We have entered a child process."
child_proc()
else:
print "We have entered the parent process."
print "Our child's PID is: %d" % childpid
# while True:
# pass
parent_proc()

View File

@ -0,0 +1,6 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
os.execvp("ping", ["ping", "127.0.0.1", "-c", "4"])

27
16_threads.py 100755
View File

@ -0,0 +1,27 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# "Global Interpreter Lock" - Only one thread :(
# Don't expect more.
import thread
import time
def worker_thread(id) :
print "Thread ID start: %d" % id
count = 1
while True :
print "Thread ID: %d with value %d" % (id, count)
time.sleep(2)
count += 1
for i in range(5) :
thread.start_new_thread(worker_thread, (i,))
print "Main thread goes with an infinite loop."
while True :
pass

View File

@ -0,0 +1,4 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-

View File

@ -0,0 +1,4 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-

14
19_signals_ipc.py 100755
View File

@ -0,0 +1,14 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
import signal
def ctrlc_handler(signum, frm) :
print "Can't ctrlc this."
print "Signal handler..."
signal.signal(signal.SIGINT, ctrlc_handler)
print "Done."
while True:
pass

19
20_subprocess.py 100755
View File

@ -0,0 +1,19 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
import subprocess
subprocess.call(['ps', 'aux']) # Just exec.
lines = subprocess.check_output(['ls']) # Get output into vari
print type(lines)
print lines
# Popen for handle stds
handle = subprocess.Popen("ls", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) # True here can be a sec issue.
handle.stdout.read()

20
21_socket.py 100755
View File

@ -0,0 +1,20 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP - STREAM
tcpSocket.bind(("127.0.0.1", 8001)) # Should be passed as tuple
tcpSocket.listen(2) # 2 is the number of concurr to handle
(client, ( ip, port)) = tcpSocket.accept() # accept by default is blocking call
# client.send("Message to client.")
data = client.recv(2048)
print ip
print port
print data

View File

@ -0,0 +1,25 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP - STREAM
tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpSocket.bind(("127.0.0.1", 8001)) # Should be passed as tuple
tcpSocket.listen(2) # 2 is the number of concurr to handle
(client, ( ip, port)) = tcpSocket.accept() # accept by default is blocking call
data = "empty"
while len(data) :
data = client.recv(2048)
print "Client sent: ",data
client.send(data)
client.close()
tcpSocket.close()

View File

@ -0,0 +1,20 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
import SocketServer
class EchoHandler(SocketServer.BaseRequestHandler) :
def handle(self) :
print "Connection from: ", self.client_address
data = 'dummy'
while len(data) :
data = self.request.recv(1024)
self.request.send(data)
print "Client left."
serverAddr = ("127.0.0.1", 4000)
server = SocketServer.TCPServer(serverAddr, EchoHandler)
server.serve_forever()

12
24_werkzeug.py 100755
View File

@ -0,0 +1,12 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
from werkzeug.wrappers import Request, Response
@Request.application
def application(request):
return Response('ok')
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple('localhost', 4000, application)

12
25_flask.py 100755
View File

@ -0,0 +1,12 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'ok'
if __name__ == '__main__':
app.run('127.0.0.1',4001)

View File

@ -0,0 +1,5 @@
# How to run it fast
# python -m SimpleHTTPServer 4444
# ...or start transiting to python 3!
# python3 -m http.server 4444
# pushd /serve/anotherdir ; python3 -m http.server 4444

View File

@ -0,0 +1,19 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
import SocketServer
import SimpleHTTPServer
class HttpRequestHandler (SimpleHTTPServer.SimpleHTTPRequestHandler) :
def do_GET(self) :
if self.path == "/admin" :
self.wfile.write('This page is only for admins lol')
self.wfile.write(self.headers)
else :
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
httpServer = SocketServer.TCPServer(("", 7777), HttpRequestHandler)
print "It should listen on 7777."
httpServer.serve_forever()

View File

@ -0,0 +1,31 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Ethernet / IP / TCP / Application
#
# Ethernet header: 14 bytes
#
# 0 5 6 11 12 14
# | EthDHost | EthSHost | EthType |
# | Ethernet Packet Data |
# 0 3 4 7 8 15 16 31
# | Version | IDL | Type of Service | Total Length |
# | Identification | Flags | Fragment Offser |
# | TTL | Protocol | Header Checksum |
# | Source Address |
# | Destination Address |
# | Options | Padding |
# Note here when interpreting: Network Byte Order is indicated by first byte (eg. Big-Endian)
import struct # For packing/unpacking binary data
print struct.pack("B", 1) # Packet as byte "B", little endian ordering here
print struct.pack("H", 1) # Etc...
print struct.pack(">H", 1) # Big endian ordering here because of ">"
print struct.pack("!L", 1) # Unsigned long, 4 bytes, network byte format "!"
struct.unpack("!L", "\x00\x00\x00\x01") # With the, computer unpacks "1"

View File

@ -0,0 +1,51 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# How to unpack raw packets
# Ethernet / IP / TCP / Application
#
# Ethernet header: 14 bytes
#
# 0 5 6 11 12 14
# | EthDHost | EthSHost | EthType |
# | Ethernet Packet Data |
# 0 3 4 7 8 15 16 31
# | Version | IDL | Type of Service | Total Length |
# | Identification | Flags | Fragment Offser |
# | TTL | Protocol | Header Checksum |
# | Source Address |
# | Destination Address |
# | Options | Padding |
# Note here when interpreting: Network Byte Order is indicated by first byte (eg. Big-Endian)
import socket
import struct
import binascii
# PF_PACKET for layer2 modifications
# For addresses: /usr/include/linux/if_ether.h
rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800))
pkt = rawSocket.recvfrom(2048)
ethernetHeader = pkt[0][0:14]
eth_hdr = struct.unpack("!6s6s2s", ethernetHeader)
binascii.hexlify(eth_hdr[0]) # Take values and print out
binascii.hexlify(eth_hdr[1])
binascii.hexlify(eth_hdr[2])
ipHeader = pkt[0][14:34] # IP Header, 20 bytes
ip_hdr = struct.unpack("12s4s4s", ipHeader)
print "Source IP addr: " + socket.inet_ntoa(ip_hdr[1])
print "Destin IP addr: " + socket.inet_ntoa(ip_hdr[2])
# tcp header part
tcpHeader = pkt[0][34:54]
tcp_hdr = struct.unpack("!HH16s", tcpHeader)

10
README.txt 100644
View File

@ -0,0 +1,10 @@
Python2 notes
=============
These are intended to be reminders on how to code in Python 2 and for the SPSE. Whenever a refresh is needed the examples here are ready!
IDE used is "vim".
Looking for topics on linux: ls -l | grep tuple
All examples should work without error.