Python introduction

Language that lets you work more quickly and integrate your systems more effectively.

Created by Choi Hong Jun / 2013-Q1
Prof : Jong Tae Park

What is Python?

Python is..



  • General-purpose
  • High-level programming language
  • Emphasizes code readability
  • Object-oriented & functional programming
  • Fully dynamic type
  • And Scripting language

Who made it?


Guido van Rossum, the creator of Python
And Now, Developer Python Software Foundation
Appeared in

1991

About the origin of Python, Van Rossum wrote in 1996:
Over six years ago, in December 1989,
I was looking for a "hobby" programming project that would keep me occupied during the week around Christmas.
My office ... would be closed, but I had a home computer, and not much else on my hands.
I decided to write an interpreter for the new scripting language I had been thinking about lately: a descendant of ABC that would appeal to Unix/C hackers.
I chose Python as a working title for the project, being in a slightly irreverent mood
(and a big fan of Monty Python's Flying Circus).

monty python and the holy grail

The core philosophy of the language

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Readability counts.
Python Offical Page

Features of Python

Middle language


Take pros both of script language & system language
Usally support byte compiler, but some Implementation,
they use just-in-time (JIT) compilation to machine code.

object-oriented programming

 
class Person:
    def __init__(self, name, height):
        self.name = name
        self.height = height
 
    def sayGreeting(self):
        print "Hello!  My name is", self.name,
        print "I am", self.height, "feet tall!"
						 

Functional Programming

 
>>> def better_outer():
...     count = [0]
...     def inner():
...         count[0] += 1
...         return count[0]
...     return inner
...
>>> counter = better_outer()
					 

dynamic languages

Java - Static
 
// print the integers from 1 to 9
for (int i = 1; i < 10; i++)
{
   System.out.println(i);
}
						 
Python -Dynamic
 
# print the integers from 1 to 9
for i in range(1,10):
    print i
						 

Simplicity of script programming language


In Why Python? Eric S. Raymond notes that:
Python … is compact — you can hold its entire feature set (and at least a concept index of its libraries) in your head.


In Why I Love Python Bruce Eckel notes that Java is not compact.
I can remember many Python idioms because they’re simpler. That’s one more reason I program faster [in Python]. I still have to look up how to open a file every time I do it in Java. In fact, most things in Java require me to look something up.

On Code comparison with Java

Java
 
import java.io.*;
...

BufferedReader myFile =
    new BufferedReader(
        new FileReader(argFilename));


						 
Vs. Python
 
# open an input file
myFile = open(argFilename)							
							
						 
Looks like Simple?

How about this?

Consider following HTTP POST example...
Java
 
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

public class java_post {

public static void main (String args[]) throws Exception {
    System.out.println(
        executePost("http://www.smh.com.au/execute_search.html",
                    "text=fluoride")
    );
}

public static String executePost(String targetURL, String urlParameters){
    URL url;
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                                      "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", "" +
               Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setUseCaches (false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream (
                  connection.getOutputStream ());
        wr.writeBytes (urlParameters);
        wr.flush ();
        wr.close ();

        //Get Response    
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if(connection != null) {
            connection.disconnect();
        }
    }
  }
}						 
Vs. Python
 import urllib, urllib2
data = urllib.urlencode({
                'text' : 'fluoride',
        })
req = urllib2.Request('http://www.smh.com.au/execute_search.html', data)
response = urllib2.urlopen(req)
print response.read()						
						 

python data abstraction

Java
 
public Vector aList = new Vector;
public int    aNumber      = 5;
public int    anotherNumber;

aList.addElement(aNumber);
anotherNumber = aList.getElement(0);

						 
Vs. Python
 
aList = []
aNumber = 5

aList.append(aNumber)
anotherNumber = aList[0]
						 

High performance! - Speed

High performance! - Memory Usage

Battery Included

built-in functions.
  • Large standard library
  • Internet-facing applications
  • Modules for creating graphical user interfaces
  • Modules for connecting to relational databases
  • Modules for rithmetic with arbitrary precision decimals
  • Modules for Manipulating regular expressions
  • Modules for doing unit testing


Need More? : PyPI - the Python Package Index
All List of PyPi

Why Python?

Google Trend

For productivity

Productivity and Finger Typing
This is all very informal, but I heard someone say a good programmer can reasonably maintain about 20,000 lines of code.
Whether that is 20,000 lines of assembler, C, or some high-level language doesn't matter. It's still 20,000 lines.
If your language requires fewer lines to express the same ideas, you can spend more time on stuff that otherwise would go beyond those 20,000 lines.
A 20,000-line Python program would probably be a 100,000-line Java or C++ program.
It might be a 200,000-line C program, because C offers you even less structure.
Looking for a bug or making a systematic change is much more work in a 100,000-line program than in a 20,000-line program.
For smaller scales, it works in the same way. A 500-line program feels much different than a 10,000-line program.

Google Likes Pyhton


G Mail, App Engine, Google API etc..

Even Sublime text2 !

Extansion As Glue Language

If you find something that Python cannot do, or if you need the performance advantage of low-level code, you can write extension modules in C or C++, or wrap existing code with SWIG or Boost.Python. The reason why Py so quick.

Conclusion

속도를 고려하지 않는다면 뭐든지 할 수 있고, 속도가 필요하다면 PyPy를 쓰시면 됩니다.
기본적으로 C/C++로 코드를 투자하는 만큼 성능 향상이 이루어지지 않는다면 파이썬을 쓰는 게 유리합니다.
(I/O 같이 언어 구현 성능에 별 영향을 안 주는 곳에서는 이미 C/C++가 많이 힘을 잃었고요, PyPy 같은 경우 C/C++랑 비교해서 많아야 3~5배 느린 경우가 태반이니까요.)

파이썬으로 프로토타이핑을 한 뒤에 필요한 부분만 C/C++로 대체하는 방법도 있습니다.

How Python?

Version ?

  • 2.X
  • 3.X

Partial Syntex compatibility!
Recommend?

=> 2.X ! For modules dependencies


Deep Inside? :Python documentation Page

Implementations

  • CPython : The main Python implementation
  • PyPy : fastest just-in-time compiler
  • Stackless Python : allowing massively concurrent programs
  • Psyco : specialising just in time compiler
  • Jython : compiles into Java byte code , Run on JVM
  • IronPython : to run Python programs on the .NET Common Language Runtime


주의! : CPython과 이외의 구현체들의 GIL차이에 따른에 따른 Thread작성
파이썬 GIL과 동기화

unrestricted Python, a restricted subset of Python langauge

  • Cython : compile to C
  • Pyrex : compile to C
  • RPython : compiled to C, Java bytecode or Common Intermediate Language
  • Shed Skin : compiles Python to C++
  • Pyjamas : compiles Python to JavaScript



It's Not Implementations, it's SubSet of Python langauge.

Installation

For Linux
 
.configure
make install
make

or

apt-get install python
						 
For Mac
 
brew install python
						 
Windows는 그냥 exe파일 여시면 돼요.
( 크롬확장 : 'Python Shell' )

Open Console or Execute Batch File

Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Date Structure on Python

  1. 숫자형 (Number)
  2. 튜플 (tuple)
  3. 리스트 (List)
  4. 문자열 (String)
  5. 딕셔너리 (Dictionary)
  6. 참과 거짓 (Boolean)

숫자형 (Number) Data type

Ellipsis -> Number : This type has a single value. There is a single object with this value.

정수          123, -345, 0
실수          123.45, -1234.5, 3.4e10
복소수        1 + 2j, -3j
8진수         034, 025
16진수        0x2A, 0xFF 
						

숫자형 (Number) Data type

사실 Object 에요!

>>> a = 1+2j
>>> a.real
1.0
>>> a.imag
2.0
>>> a.conjugate()
(1-2j)
						

리스트 (List) Data type

Sequences -> Mutable sequences -> List :

The items of a list are arbitrary Python objects. Lists are formed by placing a comma-separated list of expressions in square brackets. (Note that there are no special cases needed to form lists of length 0 or 1.)

"[ ]" with ","


>>> a = []
>>> a = [1, 2, 3]
>>> c = ['Life', 'is', 'too', 'short']
>>> d = [1, 2, 'Life', 'is']
>>> e = [1, 2, ['Life', 'is']]
>>> a[0]
1
						

>>> a = [1, 2, 3]
>>> a[2] = 4 # Modified
>>> del a[1] # delete it.
>>> a
[1, 4]
						

List : Can Change. Editable.

리스트 (List) Data type

리스트의 인덱스

>>> a = [1, 2, 3]
>>> a[0]
1
>>> a[0] + a[2]
4
>>> a[-1]
3
						
순환구조(circular queue) : 그렇다면 -2가 가르키는 인덱스는?

리스트 (List) Data type

유용한 메소드들

l = range(10)
print l

print list1[0] # get ITEM.
list1[0] = -1 # write ITEM.
print len(list1) # length

# addtion.
list1.append(1)
list1.extend([1,2,3])

#sorting
list1.sort()
list1.reverse()

#insert and delete.
list1.insert(3,"hello")
del list1[3]			
Tuple, string, list등 Sequences계열 Data들은 모두 사용가능!

리스트 (List) Data type


>>> a = [1, 2, ['a', 'b', ['Life', 'is']]]
>>> a[2][2][0]
'Life'
						
중첩구조 리스트 값 읽기 : C의 배열처럼~!

리스트 (List) Data type


>>> a = [1, 2, 3, 4, 5]
>>> a[0:2]
[1, 2]
>>> a = [1, 2, 3, 4, 5]
>>> b = a[:2]
>>> c = a[2:]
>>> b
[1, 2]
>>> c
[3, 4, 5]
						
슬라이싱은 ? ":" 로 구분!

리스트 (List) Data type

List 합치기와 곱하기 연산.

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a + b
[1, 2, 3, 4, 5, 6]

>>> a = [1, 2, 3]
>>> a * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
						
같은 operator라도 숫자일때랑 다름!
(+는 Extend, *은 multiplied Extend)

리스트 (List) Data type

Sequences -> Mutable sequences -> List :

List 객체(Object)의 유용한 메소드들
>>> a = [1, 2, 3] 
>>> a.append(4)
>>> a
[1, 2, 3, 4]

>>> a = [1, 4, 3, 2]
 >>> a.sort()
>>> a
[1, 2, 3, 4]

>>> a = [1,2,3,1,2,3]
>>> a.remove(3)
[1, 2, 1, 2, 3]

>>> a = [1,2,3,1]
>>> a.count(1)
2					

리스트 (List) Data type

유용한 내장함수 range, xrange

“range” creates a list of numbers in a specified range
Hong-Jun-Choiui-MacBook-Pro:~ teemo$ python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(10,0,-1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> 




							
							
						
range([start,] stop[, step]) -> list of integers

튜플 (tuple) Data type

Sequences -> Immutable sequences -> Tuples :

The items of a tuple are arbitrary Python objects.
Tuples of two or more items are formed by comma-separated lists of expressions.
A tuple of one item (a ‘singleton’) can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions).

Index : Start with 0.

>>> t1 = ()
>>> t2 = (1,)
>>> t3 = (1,2,3)
>>> t4 = 1,2,3
>>> t5 = ('a', 'b', ('ab', 'cd'))
>>> t1 = (1, 2, 'a', 'b')
>>> t1[0]
1
>>> t1[3]
'b'
						

Tuple : Can't Change. Read Only.

문자열 (String) Data type

Sequences -> Immutable sequences -> Strings :

The items of a string are characters. There is no separate character type; a character is represented by a string of one item. Characters represent (at least) 8-bit bytes.

>>> food = "Python's favorite food is perl"
>>> food = 'Python's favorite food is perl'
>>> say = '"Python is very easy." he says.'
>>> multiline="""Life is too short
		You need python
		Python is powerful language"""
						
List that all items are characters.

('string'와 "string"와 '''strings with multi-lines'''와 """strings with multi-lines"""를 이용해 구분한다! )

문자열 (String) Data type


>>> head = "Python"
>>> tail = " is fun!"
>>> print head + tail
Python is fun!

>>> a = "python"
>>> print a * 2
pythonpython						
LIST랑 똑같죠? string 합치기, 곱하기.

문자열 (String) Data type


>>> a = "20010331Rainy"

>>> date = a[:8]
>>> weather = a[8:]

>>> date
'20010331'

>>> weather
'Rainy'
						
Slicing도 똑같아요.

문자열 (String) Data type


>>> print "I have %s apples" % 3
I have 3 apples
>>> print "Todays rate is %s" % 3.234
Todays rate is 3.234
						
C의 Formatting과 유사! : "%" 를 사용.

문자열 (String) Data type


>>> a = "Python is best choice"
>>> a.find('b')
10

>>> a = "Life is too short"
>>> a.split()
['Life', 'is', 'too', 'short']

>>> a = "a:b:c:d"
>>> a.split(':')
['a', 'b', 'c', 'd']

>>> a = "Life is too short"
>>> a.replace("Life", "Your leg")
'Your leg is too short'
						
여러분 이거 다~ Object인거 아시죠?
: find, split, replace 메소드.

딕셔너리 (Dictionary) Data type

Mappings -> Dictionaries :

These represent finite sets of objects indexed by nearly arbitrary values. The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant. Numeric types used for keys obey the normal rules for numeric comparison.

>>> dic = {'name':'pey', 'phone':'0119993323', 'birth': '1118'}
>>> a = { 'a': [1,2,3]}
>>> grade = {'pey': 10, 'julliet': 99}
>>> grade['pey']
10
>>> grade['julliet']
99
>>> a = {1: 'a'}
>>> a[2] = 'b'
>>> a
{2: 'b', 1: 'a'}
						

참과 거짓(Boolean) Data type


("", [], (), {}, NULL, 0) 중 하나 이면 False,

이외에는 Ture!
						
이건 Object가 아닙니다.

4줄 요약.

  • 숫자 : number1 = 3.14
  • 튜플 : tuple1 = (1,2,3)
  • 리스트 : List1 = [1,2,3]
  • 문자열 : string1 ='hi', string2 = "bye"



이정도만 알아두셔도 되요.

이 외에도 다른 자료형이 존재합니다.

  • Byte Arrays
  • Sets
  • Frozen sets
  • Callable types
  • NotImplemented



잘쓰진 않아요.

Indentation 들여쓰기

C언어나 자바와 달리 { } 이런 중괄호로 함수의 시작과 끝을 정의하지는 않고,
들여쓰기(Indentation) 로, 함수의 본체와 끝을 정의

### C++ ###
int sum(int a, int b){
	
	int c = a + b;

	return c;
}

### Python ###
def sum(a,b):
	c = a + b
	return c			

Indentation 들여쓰기

Indentation Error 1

if <조건문>:
    <수행할 문장1>
<수행할 문장2>
    <수행할 문장3>
						
Indentation Error 2

if <조건문>
    <수행할 문장1>
    <수행할 문장2>
      <수행할 문장3>
						

tab과 space혼용도 주의!

Syntax in Conditions

and, or, not

>>> money = 2000
>>> watch = 1
>>> if money >= 3000 or watch:
...     print "택시를 타고 가라"
... else:
...     print "걸어가라"
...
택시를 타고 가라
>>>
						
x in s, x not in s

>>> 1 in [1, 2, 3]
True
>>> 1 not in [1, 2, 3]
False
						

Syntax in Conditions

재미있는 Condition 판별.


>>> a = 2
>>> 1 < a < 3
True
>>> 
						

제어문

[1] if문 [2] while문 [3] for문

if문


If <조건문>:
    <수행할 문장1> 
    ...
elif <조건문>:
    <수행할 문장2>
    ...
elif <조건문>:
    <수행할 문장3>
    ...
...
else:
   <수행할 문장4>
   ... 
						
':'을 잊지 말자!

while문


while <조건문>:
    <수행할 문장1>
    <수행할 문장2>
    <수행할 문장3>
    ...
						

coffee = 10
while 1:
    money = int(raw_input("돈을 넣어 주세요: "))
    if money == 300:
        print "커피를 줍니다."
        coffee = coffee -1
    elif money > 300:
        print "거스름돈 %d를 주고 커피를 줍니다." % (money -300)
        coffee = coffee -1
    else:
        print "돈을 다시 돌려주고 커피를 주지 않습니다."
        print "남은 커피의 양은 %d개 입니다." % coffee
    if not coffee:
        print "커피가 다 떨어졌습니다. 판매를 중지 합니다."
        break
						

for문

For 기본 구조

for 변수 in 리스트(또는 터플, 문자열):
    <수행할 문장1>
    <수행할 문장2>
    ...
						
내장함수 range()

>>> a = range(10) 
>>> a 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  
						
For문 응용 : 1부터 10까지 합구하기.

>>> sum = 0 
>>> for i in range(1, 11): 
. . .     sum = sum + i 
. . . 
>>> print sum 
55
						

함수

def 이라는 키워드(예약어)로 함수를 정의

#!/usr/bin/python
# -*- coding: cp949 -*-


# 가장 간단한 함수 정의
def example():
  print "안녕하세요"


# 함수 호출
example()
# 출력 결과: 안녕하세요




# 함수 인수(매개변수;파라미터)와 반환값 사용
def example2(x, y):
  z = x + y
  return z


# 함수 호출
print example2(2, 3)
# 출력 결과: 5 			

클래스

 
class 클래스이름 [(상속 클래스명)]:
    <클래스 변수 1>
    <클래스 변수 2>
    ...
    def 클래스함수1(self [, 인수1, 인수2, ...]):
        <수행할 문장 1>
        <수행할 문장 2>
        ...
    def 클래스함수2(self [, 인수1, 인수2, ...]):
        <수행할 문장 1>
        <수행할 문장 2>
        ...
    ...
						 
파이썬에서는 관례적으로 메쏘드의 첫 번째 매개변수를 self라고 부른다.
"self" 는 필수! (C++의 this와 같습니다.)

클래스

미리정의된 클래스 속성 클래스에는 미리정의된 속성이 다섯개가 있다:
 
속성	유형	읽기/쓰기	설명
__dict__	사전	R/W	클래스 이름 공간.
__name__	문자열	R/O	클래스의 이름.
__bases__	클래스를 담은 터플	R/O	이 클래스가 상속받은 클래스들.
__doc__	문자열 혹은 None	R/W	클래스 문서화 문자열.
__module__	문자열	R/W	이 클래스가 정의된 모듈의 이름.

						 

클래스

 
# 클래스 선언
class Guest:
    category = 'Guest'   # 클래스 내 변수 설정

    def __init__(self, num): # 생성자 / 객체 생성시 호출되며, GuestID 필요로 한다
         self.GuestID = num
 
    def __del__(self):   # 소멸자 / 객체 소멸시 호출
         print "Guest out"
 
    def printID(self):   # 메소드 / 인스턴스의 GuestID를 출력하는 메소드
         print self.GuestID


						 

클래스

 
# Guest 클래스의 인스턴스 생성, 값 출력, 메소드 호출
A = Guest(3)     # 인스턴스 생성 (GuestID = 3으로 설정)
print A.category    # 인스턴스 내 변수 category 값 출력
print A.GuestID     # 인스턴스의 GuestID 값 출력
A.printID()      # 인스턴스의 printID() 메소드 호출



실행 결과: 
Guest
3
3
Guest out
						 

모듈(module)

import 모듈
 
'''
1. 모듈이름 붙이기 싫은 경우 (모듈 내에 특정함수만 사용하는 경우)

import 모듈이름

모듈이름.함수이름
'''

# module1.py 파일
def sum(a,b):
    return a + b

>>> import module1
>>> module1.sum(2,3)
5
					 
모듈: 함수나 변수들, 또는 클래스들을 모아놓은 파이썬 파일로 다른 파이썬 프로그램에서 사용할 수 있도록 한 것

모듈


form 모듈 import 함수
form 모듈 import *
 
'''
2. 모듈이름 불이기 싫은 경우 (모듈 내의 모든 함수 이용하는 경우 - 가장 일반적인 사용 방법)

from 모듈이름 import *
'''

# module1.py 파일
def sum(a,b):
    return a + b

>>> from module1 import *
>>> sum(2,3)
5
					 

모듈


dir() 함수
 //내장 함수 dir()은 한 모듈이 정의한 이름들을 알아냅니다. 

>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
 '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 
 'builtin_module_names', 'byteorder', 'callstats', 'copyright',
 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook',
 'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags',
 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
 'meta_path', '모듈', 'path', 'path_hooks', 'path_importer_cache',
 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',
 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
 'version', 'version_info', 'warnoptions']
					 

유용한 모듈


math, decimal, datetime, time, re.

For IT-types who will be doing file-oriented work: 

glob, fnmatch, os, os.path, tempfile, and shutil.

Database folks must hear about sqlite and json.

Simulation audience may want to hear about random.

Web developers must hear about urllib2 from a client point of view. Also Beautiful Soup and an XML parser of your choice.

Web developers must hear about logging and wsgiref from a server point of view.
						

socket 모듈로 구현한 예제

server

#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection
						

socket 모듈로 구현한 예제

client

#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done
						

socket 모듈로 구현한 예제


# Following would start a server in background.
$ python server.py & 

# Once server is started run client as follows:

$ python client.py
						

Got connection from ('127.0.0.1', 48437)
Thank you for connecting
						

Python Internet modules

A list of some important modules which could be used in Python Network/Internet programming.

Protocol	Common function	Port No	Python module
HTTP	Web pages	80	httplib, urllib, xmlrpclib
NNTP	Usenet news	119	nntplib
FTP	File transfers	20	ftplib, urllib
SMTP	Sending email	25	smtplib
POP3	Fetching email	110	poplib
IMAP4	Fetching email	143	imaplib
Telnet	Command lines	23	telnetlib
Gopher	Document transfers	70	gopherlib, urllib
					

유용한 모듈

Twisted

Twisted
Twisted is an event-driven networking engine written in Python and licensed under the open source

from twisted.internet import protocol, reactor

class Echo(protocol.Protocol):
    def dataReceived(self, data):
        self.transport.write(data)

class EchoFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return Echo()

reactor.listenTCP(1234, EchoFactory())
reactor.run()
						

Examples of Python Applications

example 1

WEB SERVER. Twisted includes an event-driven web server. Here's a sample web application; notice how the resource object persists in memory, rather than being recreated on each request:

from twisted.web import server, resource
from twisted.internet import reactor

class HelloResource(resource.Resource):
    isLeaf = True
    numberRequests = 0
    
    def render_GET(self, request):
        self.numberRequests += 1
        request.setHeader("content-type", "text/plain")
        return "I am request #" + str(self.numberRequests) + "\n"

reactor.listenTCP(8080, server.Site(HelloResource()))
reactor.run()
 						
More Examples

example 2

Twisted includes a sophisticated IMAP4 client library
 							
import sys

from twisted.internet import protocol, defer, endpoints, task
from twisted.mail import imap4
from twisted.python import failure

@defer.inlineCallbacks
def main(reactor, username="alice", password="secret",
         strport="ssl:host=example.com:port=993"):
    endpoint = endpoints.clientFromString(reactor, strport)
    factory = protocol.Factory()
    factory.protocol = imap4.IMAP4Client
    try:
        client = yield endpoint.connect(factory)
        yield client.login(username, password)
        yield client.select('INBOX')
        info = yield client.fetchEnvelope(imap4.MessageSet(1))
        print 'First message subject:', info[1]['ENVELOPE'][1]
    except:
        print "IMAP4 client interaction failed"
        failure.Failure().printTraceback()

# This API requires Twisted 12.3 or later, or a trunk checkout:
task.react(main, sys.argv[1:])
 							
 						

THE END

CHOI HONG JUN / 2013 @ IT-DEPT @ KNU

print "THX 4 watching, and ANY QUESTION are welcome!"