แนะนำโมดูลน่าสน (Standard Module)

  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.
  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.

เลียนแบบมาจากรวมรีวิวซอฟต์แวร์ใน Blognone ที่น่าจะใช้ได้ใน Python เหมือนกันเพราะแนวคิด Battery Included ของ Python เอง ช่วงแรกนี้ขอเฉพาะโมดูลมาตรฐานก่อน แล้วตอนหลังค่อยเขยิบไปเล่นแนะนำโมดูลรอบนอกกัน ข้อมูลที่ต้องให้ก็ชื่อโมดูล คำอธิบายถึงการใช้งานสั้นๆ และตัวอย่างโค้ด เช่น

StringIO

โมดูลสำหรับสร้างสตริงให้เป็น file-like object มีประโยชน์มาเมื่อใช้ร่วมกับ unittest ทำให้ได้ไฟล์ที่ต้องการรวมอยู่ในตัวโมดูลเอง

>>> import StringIO
>>> f = StringIO.StringIO("ascdef")
>>> f.read(2)
'as'
>>> f.tell()
2
>>> f.seek(0)
>>> f.read()
'ascdef'
mk's picture

มาเสริมให้ว่าตอนนี้ถ้าอยากใส่โค้ด ให้ใช้แท็ก pre ไปพลางๆ ก่อน ตัว code filter กำลังจะตามมาครับ

ของ Ruby
StringIO

pittaya's picture

ปกติผมใช้ cStringIO นะ
เค้าว่ามันเร็วกว่า

sugree's picture

มีปัญหานิดหน่อยกับ cStringIO มันรับ unicode ที่ไม่สามารถแปลงเป็น ascii ไม่ได้ และมันก็ไม่เหมือนกันซะทีเดียว

>>> from cStringIO import StringIO
>>> r = StringIO('abcdef')
>>> w = StringIO()
>>> dir(r)
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'close', 'closed', 'flush', 'getvalue', 'isatty', 'next', 'read', 'readline', 'readlines', 'reset', 'seek', 'tell', 'truncate']
>>> dir(w)
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'close', 'closed', 'flush', 'getvalue', 'isatty', 'next', 'read', 'readline', 'readlines', 'reset', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines']
  • ถ้าใส่ค่าเริ่มต้นจะมีแต่ read ไม่มี write
  • ถ้าไม่ใส่ค่าเริ่มต้นจะมี read และ write

ปกติผมก็ใช้ cStringIO แต่จะใช้ด้วย from cStringIO import StringIO เผื่อเปลี่ยนใจทีหลังจะได้แก้แค่ที่เดียว

sugree's picture

ConfigParser

ถ้าต้องการเก็บค่าไว้ในไฟล์ข้างนอกแบบง่ายๆ หน้าตาคล้าย ini บนวินโดส์ก็สามารถใช้ ConfigParser ได้ทันที

หน้าตาของค่าที่เก็บจะประกอบด้วย section และ option อยู่ข้างใน

# none.conf
[codenone]
base = http://www.codenone.com/
forum = %(base)sforum
 
[blognone]
base = http://www.blognone.com/
forum = %(base)sforum

ซึ่งหมายความว่ามี section ชื่อ codenone และ blognone ซึ่งมี option ชื่อ base และ forum เหมือนๆ กัน # หมายถึงคำอธิบาย

เวลาใช้ก็ง่ายดาย

from ConfigParser import ConfigParser
cfg = ConfigParser()
print cfg.read('none.conf')
# ['none.conf']
print cfg.get('blognone','base')
# http://www.blognone.com/
print cfg.get('codenone','forum')
# http://www.codenone.com/forum
print cfg.get('blognone','forum',raw=True)
# %(base)sforum

นอกจาก get() แล้วก็ยังมี getint() getfloat() getboolean() ด้วย ส่วนการเขียนก็ทำได้คล้ายๆ กัน

cfg.add_section('nonenone')
cfg.set('none','base','http://www.nonenone.com/')
cfg.set('none','forum','%(base)sforum')
cfg.write(open('none.conf','w'))
omni_kh's picture

Tempfile

สร้างและจัดการ Temporary File แบบไม่ขึ้นต่อระบบปฏิบัติการ

>>> import tempfile

สองฟังก์ชั่นข้างล่างนี้ให้ file object ของ tempfile มา ไฟล์จะถูกลบเมื่อ close()หรือ เมื่อ file object ถูก garbage collection
* TemporaryFile(): ใช้เมื่อไม่ต้องการ access file โดยใช้ path
* NamedTemporaryFile(): มี path ให้ โดยเรียกดูผ่าน attribute name

>>> f = tempfile.TemporaryFile()
>>> repr(f)
"<open file '<fdopen>', mode 'w+b' at 0x00AAFE30>"
>>> f2 = tempfile.NamedTemporaryFile()
>>> f2.name
'c:\\docume~1\\chat\\locals~1\\temp\\tmpeyftpy'

Temporary Directory บ้าง (ต้องจัดการลบเองด้วยนะ)
* mkdtemp(): ให้ absolute path ของ directory ที่สร้างขึ้น

>>> temp_path = tempfile.mkdtemp()
>>> print temp_path
c:\docume~1\chat\locals~1\temp\tmp74js8x
sugree's picture

shutil

เข้าเมืองตาหลิ่วก็ต้องหลิ่วตาตาม เวลาจะทำสำเนาไฟล์หรือไดเรกทอรี่ใน Python ก็มีวิะีของ Python ที่ใช้ได้เสมอ อย่าไปอุตริใช้แต่ os.system() โมดูลที่ว่าก็คือ shutil นี่เอง ยกเว้นตอนลบต้องใช้ os.link()

>>> import shutil
>>> shutil.copyfile('/etc/hosts','tmp')
>>> shutil.copyfileobj(open('/etc/hosts','r'),open('tmp2','w'))
>>> shutil.copytree('/var/log/httpd','tmplog')
>>> shutil.move('tmplog','tmplog2')
>>> shutil.rmtree('tmplog2')
>>> import os
>>> os.unlink('tmp')
>>> os.unlink('tmp2')

ยังมีเพิ่มเติมอีกหน่อยลองไปอ่านที่ Library Reference

ctypes

เพิ่งเข้ามาเป็น Standard ใน Python 2.5 แต่ใน 2.4 ก็ใช้งานได้เหมือนกัน โดยหลักมันคือโมดูลเพิ่มความสามารถในการเรียกฟังก์ชั่นจากภาษา C มาใช้งานใน Python ใช้งานง่ายอย่างไม่น่าเชื่อจนผมติดนิสัยเอา C Function มาใช้ในโหมด Interactive อยู่เรื่อยๆ

ตัวอย่างไฟล์ hello.c

#include "stdio.h"
void hello(){
  printf("Hello Python.\n");
}
>>> import ctypes
>>> hello = ctypes.CDLL("./hello.so")
>>> hello.hello()
Hello Python.
14
sugree's picture

SimpleHTTPServer

บางทีโปรแกรมเราก็ต้องติดต่อกับโลกภายนอกบ้าง ถ้าเป็นโปรแกรม interactive ก็ง่ายหน่อย แต่ถ้าโปรแกรมที่ว่าดันรัน background ก็ต้องใช้เน็ตเวิร์คกันละ วิธีที่ทำง่ายและไม่ซับซ้อนก็คือสร้างเว็บเซิร์ฟเวอร์จิ๋วขึ้นมาในตัวโปรแกรมเอง ซึ่งอาจจะไปเรียกโปรแกรมภายนอกอื่นหรือไม่ก็ได้ ใน Python นั้นมีโค้ดสำหรับสร้างเซิร์ฟเวอร์หลายแบบให้เลือกใช้ รวมไปถึงเว็บเซิร์ฟเวอร์ด้วย ซึ่งใช้ง่ายสุดๆ เช่นข้างล่าง

from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
 
httpd = HTTPServer(('',8080),SimpleHTTPRequestHandler)
httpd.serve_forever()

ผมชอบใช้สำหรับการดาวน์โหลดไฟล์จากไดเรกทอรี่ปัจจุบัน หลังจากพิมพ์โค้ดนี้แล้วก็เปิดเบราเซอร์ได้ http://localhost:8080/ ก็จะเห็นไฟล์ในนั้นให้เลือกกดโหลดหรือเข้าไปข้างในได้เรื่อยๆ โค้ดนี้รับได้แค่ทีละ 1 ไคลเอนต์เท่านั้น เพราะยังไม่มี fork หรือ thread มาเกี่ยวข้อง

mk's picture

หมายความว่ามันจะแม็ปไดเรคทอรีปัจจุบันกับ localhost:8080 ให้เลย ไม่ต้องไปทำ public_html ตามปกติให้เสียเวลา?

sugree's picture

ถูกต้องนะคร้าบ โหลดไฟล์ได้ ไม่มี CGI ถ้าอยากได้ CGI ก็เปลี่ยน handler ซะหน่อย

veer's picture

ผมใช้ cherrypy เลย จริงๆแล้วนึกอะไรไม่ออกก็ใช้ turbogears เลย บางทีก็ใช้ (แต่เอามาทำเป็น REST)

work4best's picture

ลบยังไงครับ

ย้าย Codenone

ประกาศย้าย Codenone ไปใช้ Forum ของ Blognone แทนครับ ตามไปตั้งกระทู้ต่อได้ที่ Codenone Forum (รายละเอียดอ่านจากกระทู้ ย้าย Codenone ไปรวมกับ Blognone)

กระทู้เก่าๆ จะย้ายตามไปในภายหลัง ตอนนี้ปิดการโพสต์กระทู้ไว้ เหลือไว้เฉพาะอ้างอิงเท่านั้น