diff --git a/01_vars_strings_split_list.py b/01_vars_strings_split_list.py new file mode 100755 index 0000000..9f10c02 --- /dev/null +++ b/01_vars_strings_split_list.py @@ -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] diff --git a/02_tuples_vars.py b/02_tuples_vars.py new file mode 100755 index 0000000..9c857ac --- /dev/null +++ b/02_tuples_vars.py @@ -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 diff --git a/03_sets.py b/03_sets.py new file mode 100755 index 0000000..385529c --- /dev/null +++ b/03_sets.py @@ -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 diff --git a/04_dict.py b/04_dict.py new file mode 100755 index 0000000..d77f583 --- /dev/null +++ b/04_dict.py @@ -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) diff --git a/05_if_for_while.py b/05_if_for_while.py new file mode 100755 index 0000000..19a81aa --- /dev/null +++ b/05_if_for_while.py @@ -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?") diff --git a/06_range.py b/06_range.py new file mode 100755 index 0000000..e2af31f --- /dev/null +++ b/06_range.py @@ -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 diff --git a/07_functions_sysargv_exception.py b/07_functions_sysargv_exception.py new file mode 100755 index 0000000..cfd905d --- /dev/null +++ b/07_functions_sysargv_exception.py @@ -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) diff --git a/08_class_object.py b/08_class_object.py new file mode 100755 index 0000000..b6208b9 --- /dev/null +++ b/08_class_object.py @@ -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() diff --git a/09_modules.py b/09_modules.py new file mode 100755 index 0000000..69b476c --- /dev/null +++ b/09_modules.py @@ -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 diff --git a/10_exception.py b/10_exception.py new file mode 100755 index 0000000..f3c45cd --- /dev/null +++ b/10_exception.py @@ -0,0 +1,8 @@ + +#try: +#except: +#else: +#finally: + +#except Exception as anything: + diff --git a/11_python_on_iphone_sqlite.py b/11_python_on_iphone_sqlite.py new file mode 100755 index 0000000..a28a82e --- /dev/null +++ b/11_python_on_iphone_sqlite.py @@ -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 diff --git a/12_file_open_read_write_close.py b/12_file_open_read_write_close.py new file mode 100755 index 0000000..9645ad4 --- /dev/null +++ b/12_file_open_read_write_close.py @@ -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 diff --git a/13_system_dir_listing_glob_etc.py b/13_system_dir_listing_glob_etc.py new file mode 100755 index 0000000..ce24339 --- /dev/null +++ b/13_system_dir_listing_glob_etc.py @@ -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 diff --git a/14_system_processes_fork.py b/14_system_processes_fork.py new file mode 100755 index 0000000..f27f830 --- /dev/null +++ b/14_system_processes_fork.py @@ -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() diff --git a/15_system_processes_os_execvp.py b/15_system_processes_os_execvp.py new file mode 100755 index 0000000..676981d --- /dev/null +++ b/15_system_processes_os_execvp.py @@ -0,0 +1,6 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +import os + +os.execvp("ping", ["ping", "127.0.0.1", "-c", "4"]) diff --git a/16_threads.py b/16_threads.py new file mode 100755 index 0000000..7d977b4 --- /dev/null +++ b/16_threads.py @@ -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 diff --git a/17_threading_queue.py b/17_threading_queue.py new file mode 100755 index 0000000..8c10786 --- /dev/null +++ b/17_threading_queue.py @@ -0,0 +1,4 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + + diff --git a/18_multiprocessing.py b/18_multiprocessing.py new file mode 100755 index 0000000..8c10786 --- /dev/null +++ b/18_multiprocessing.py @@ -0,0 +1,4 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + + diff --git a/19_signals_ipc.py b/19_signals_ipc.py new file mode 100755 index 0000000..e4ae3c0 --- /dev/null +++ b/19_signals_ipc.py @@ -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 diff --git a/20_subprocess.py b/20_subprocess.py new file mode 100755 index 0000000..4a4742b --- /dev/null +++ b/20_subprocess.py @@ -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() diff --git a/21_socket.py b/21_socket.py new file mode 100755 index 0000000..941cf0d --- /dev/null +++ b/21_socket.py @@ -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 + diff --git a/22_socket_echo_client.py b/22_socket_echo_client.py new file mode 100755 index 0000000..aef4983 --- /dev/null +++ b/22_socket_echo_client.py @@ -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() + diff --git a/23_sockerserver_framework.py b/23_sockerserver_framework.py new file mode 100755 index 0000000..da4a92b --- /dev/null +++ b/23_sockerserver_framework.py @@ -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() diff --git a/24_werkzeug.py b/24_werkzeug.py new file mode 100755 index 0000000..202f71f --- /dev/null +++ b/24_werkzeug.py @@ -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) diff --git a/25_flask.py b/25_flask.py new file mode 100755 index 0000000..5527027 --- /dev/null +++ b/25_flask.py @@ -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) diff --git a/26_simplehttpserver.py b/26_simplehttpserver.py new file mode 100755 index 0000000..d90c94b --- /dev/null +++ b/26_simplehttpserver.py @@ -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 diff --git a/27_simplehttpserver_socketserver.py b/27_simplehttpserver_socketserver.py new file mode 100755 index 0000000..1c993ed --- /dev/null +++ b/27_simplehttpserver_socketserver.py @@ -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() diff --git a/28_raw_sockets_struct.py b/28_raw_sockets_struct.py new file mode 100755 index 0000000..c88a2e3 --- /dev/null +++ b/28_raw_sockets_struct.py @@ -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" diff --git a/29_raw_socket_struct_binascii.py b/29_raw_socket_struct_binascii.py new file mode 100755 index 0000000..b9b8f6d --- /dev/null +++ b/29_raw_socket_struct_binascii.py @@ -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) diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..94fb7f8 --- /dev/null +++ b/README.txt @@ -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.