소스
def mesg(): a = 1 return a print mesg() |
결과
1 |
소스
a = 10 b = 10 def mesg(a, b): c = a + b return c print mesg(a, b) |
결과
20 |
소스
a = 10 b = 10 def mesg(a, b): c = a + b return c if __name__ == '__main__': print mesg(a, b) |
결과
20 |
소스
#!/usr/bin/env python from gtk import * # FirstClass 라는 객체를 만듭니다. class FirstClass: def setdata(self, value): # 어떤 값을 받는 setdata 함수를 만듭니다. self.data = value def display(self): # setdata 에서 받은 값을 출력합니다. print self.data x = FirstClass() y = FirstClass() x.setdata("Kim Yong-Il") x.display() y.setdata("3.14159") y.display() print "오게 바리" |
결과
python hello1.py
Kim Yong-Il 3.14159 오게 바리 |
소스
#!/usr/bin/env python from gtk import * # FirstClass 라는 객체를 만듭니다. class FirstClass: def setdata(self, value): # 어떤 값을 받는 setdata 함수를 만듭니다. self.data = value def display(self): # setdata 에서 받은 값을 출력합니다. print self.data # SecondClass 라는 객체를 만듭니다. # SecondClass 라는 객체는 FirstClass 객체를 포함합니다. class SecondClass(FirstClass): def display(self): # 화면 출력 함수를 만듭니다. print 'Current value = "%s"' % self.data z = SecondClass() z.setdata(42) z.display() print "오게 바리" |
결과
python hello2.py
Current value = "42" 오게 바리 |
소스
#!/usr/bin/env python from gtk import * # FirstClass 라는 객체를 만듭니다. class FirstClass: def setdata(self, value): # 어떤 값을 받는 setdata 함수를 만듭니다. self.data = value def display(self): # setdata 에서 받은 값을 출력합니다. print self.data # SecondClass 라는 객체를 만듭니다. # SecondClass 라는 객체는 FirstClass 객체를 포함합니다. class SecondClass(FirstClass): def display(self): # 화면 출력 함수를 만듭니다. print 'Current value = "%s"' % self.data # ThirdClass(SecondClass): # Third 라는 객체는 Second 객체를 포함합니다. class ThirdClass(SecondClass): def __init__(self, value): self.data = value def __add__(self, other): return ThirdClass(self.data + other) a = ThirdClass("abc") a.display() b = a + 'xyz' b.display() print "오게 바리" |
결과
python hello3.py
Current value = "abc" Current value = "abcxyz" 오게 바리 |
소스
#!/usr/bin/env python from gtk import * class Subclass: data = 'spam' def __init__(self, value): self.data = value def display(self): print self.data, Subclass.data x = Subclass(1) y = Subclass(2) x.display() y.display() print "오게 바리" |
결과
python hello4.py
1 spam 2 spam 오게 바리 |
소스
#!/usr/bin/env python from gtk import * class Super: def method(self): print 'in Super.method' class Sub(Super): def method(self): print 'starting Sub.method' Super.method(self) print 'ending Sub.method' x = Super() x.method() print "------------------>" x = Sub() x.method() |
결과
python hello5.py
in Super.method ------------------> starting Sub.method in Super.method ending Sub.method |
소스
#!/usr/bin/env python from gtk import * class Super: def method(self): print 'in Super.method' def delegate(self): self.action() class Inheritor(Super): pass class Replacer(Super): def method(self): print 'in Replacer.method' class Extender(Super): def method(self): print 'starting Extender.method' Super.method(self) print 'ending Extender.method' class Provider(Super): def action(self): print 'in Provider.action' if __name__ == '__main__': for klass in (Inheritor, Replacer, Extender): print ' ' + klass.__name__ + '...' klass().method() print ' Provider...' Provider().delegate() |
결과
python hello6.py
ending Extender.method Inheritor... in Super.method Replacer... in Replacer.method Extender... starting Extender.method in Super.method Provider... |
소스
#!/usr/bin/env python from gtk import * class Number: def __init__(self, start): self.data = start def __sub__(self, other): return Number(self.data - other) x = Number(5) y = x -2 y.data print y.data |
결과
python hello7.py
3 |
소스
#!/usr/bin/env python from gtk import * class indexer: def __getitem__(self, index): return index ** 2 x = indexer() for i in range(5): print x[i], |
결과
python hello8.py
0 1 4 9 16 |
최희철 소스, ironyjk (at) kldp.org
/var/mail 에 있는 메일을 원하는 메일 주소로 보낸다.
실행 : cd /var/mail
python stmp.py ID 멜주소
smtp.py
import smtplib , sys , string def sendmail ( ff , to , text ) : if string.find ( ff , "@" ) == -1 : print "%s Break" % ff return # print " toaddr = %s" % ff # print " text == %s" % text server = smtplib.SMTP('localhost') server.sendmail(ff , to , text) server.quit() fromaddr = "root@localhost" toaddr = sys.argv[2] f = open ( sys.argv[1] ) line = f.readline() text = "" while line : if len ( string.split ( line ) ) > 2 and string.split ( line )[0] == "From" : sendmail ( fromaddr , toaddr , text ) fromaddr = string.split ( line )[1] text = "" text = text + line line = f.readline() if ( text != "" ) : sendmail ( fromaddr , toaddr , text ) |
최희철씨 소스 , ironyjk (at) kldp.org
점심때 무엇을 먹을까 고민할때 한번 실행해주면 됩니다.
bab.py
import random,smtplib,sys list = ['한국회관:해물된장','한국회관:갈비탕', '한국회관:갈비탕', '한국회관:비빔밥','한국회관:설렁탕' ,'한국회관:육계장' ,'삼익식당:>만두국','삼익식당:백반' ,'삼익식당:제육볶음' , '삼익식당:김치찌게' , '삼익식당:김치찌게' , '중국집:복음밥' , '중국집:짬뽕', '중국집:>짜장면' , '삼익식당:야채볶음밥' ,'분식집:김치복음밥','분식집:부대찌개'] menu = list [ int ( (random.random () * 100 ) % len (list) ) ] fromaddr = "ID@address.org" toaddr = "ID@address.org" msg = "To: %s Subject:오늘의 메뉴! 오늘의 메뉴는 %s 입니다." % ( toaddr , menu ) if len ( sys.argv ) > 1 : msg = msg + "즐거운 저녁식사입니다. 저녁식사 안하실 분은 관리자에게 신고 바랍니다. " lastmenu = "" msg = msg + " -- 현재 메뉴 현황 -- " for i in list : if lastmenu != i : msg = msg + " - %s " % i lastmenu = i msg = msg + " 새로운 메뉴의 추가는 언제나 환영합니다. 새로운 메뉴는 ID@address.org 메일 보내주시기 바랍니다." server = smtplib.SMTP('address.org') server.sendmail(fromaddr, toaddr, msg) server.quit() |
mysql 데이타를 가져 옵니다.
#!/usr/bin/python import MySQLdb db = MySQLdb.connect(host="localhost", db="test", user="root" , passwd="") hash = db.cursor() hash.execute("select * from test") result = hash.fetchall() for i in result: print result[0] db.close() |
소스
#!/usr/bin/python import curses import time stdscr=curses.initscr() curses.start_color() curses.init_pair(1,curses.COLOR_CYAN, curses.COLOR_BLACK) stdscr.addstr(10,10,"test", curses.color_pair(1)) stdscr.addstr(12,10,"aaaaaaaa", curses.A_REVERSE) stdscr.refresh() time.sleep(5) curses.endwin() |
서버 실행하기
/usr/lib/python1.5$ python CGIHTTPServer.py Serving HTTP on port 8000 ... |
루트권한 사용하기
vi CGIHTTPServer.py
nobody = nobody_uid() # 여기서 시스템의 nobody 계정 UID를 가져 옵니다. self.wfile.flush() # Always flush before forking pid = os.fork() if pid != 0: # Parent pid, sts = os.waitpid(pid, 0) if sts: self.log_error("CGI script exit status %#x", sts) return # Child try: try: # 이부분을 nobody로 사용할 경우는 다음과 같이 하고, 루트를 사용할경우는 주석처리합니다. os.setuid(nobody) except os.error: pass os.dup2(self.rfile.fileno(), 0) os.dup2(self.wfile.fileno(), 1) os.execve(scriptfile, args, env) except: self.server.handle_error(self.request, self.client_address) |
CGIHTTPServer 모듈에서 CGI 실행하기
모듈을 이용해서 다음과 같이 간단한 서버 프로그램을 할수 있습니다.
#!/usr/bin/env python import CGIHTTPServer import BaseHTTPServer Handler = CGIHTTPServer.CGIHTTPRequestHandler PORT = 8080 httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler) print "Serving at port ", PORT httpd.serve_forever() |
GIHTTPServer.py 에 소스에 보면 cgi 디렉토리가 다음과 같이 설정이 되어 있습니다.
필요시 변경을 할수 있습니다.
cgi_directories = ['/cgi-bin', '/htbin']
cgi 프로그램 (test.py)
#!/usr/bin/env python print """Content-type: text/html 성공 했습니다. """ |
위와 같은 예제를 이용해서 cgi-bin 밑에 넣어서 다음과 같이 실행을 하면 됩니다.
http://localhost:8080/cgi-bin/test.py
소스
import MySQLdb connection = MySQLdb.connect(user='root', passwd='', db='nalabi') cursor = connection.cursor() # 커서 객체를 얻어온다. cursor.execute('select * from test') res = cursor.description for record in res: print "%-10s %-10s %-10s %-10s %-10s %-10s %-10s" % record cursor.close() |
결과
no 3 2 6 6 0 0 num 3 2 6 6 0 0 idx 3 2 6 6 0 0 date 3 9 11 11 0 0 host 252 13 255 255 0 1 name 252 6 255 255 0 1 passwd 253 13 13 13 0 1 email 252 18 255 255 0 1 url 252 19 255 255 0 1 title 252 20 255 255 0 1 text 252 3243 16777215 16777215 0 1 refer 3 1 6 6 0 0 reyn 3 1 1 1 0 0 reno 3 1 6 6 0 0 rede 3 1 6 6 0 0 reto 3 1 6 6 0 0 html 3 1 1 1 0 0 moder 3 1 1 1 0 0 bofile 253 18 100 100 0 1 bcfile 253 14 100 100 0 1 bfsize 3 5 4 4 0 1 |
소스
import commands, string, os import os out=commands.getoutput("ls -l") a = string.split ( out , '\n' ) for i in range(len(a)): b = string.split ( a[i]) if (b[0] != "\307\325\260\350") : print b[8] cc = "chown %s:%s %s" % (b[8], b[8], b[8]) commands.getoutput(cc) |