ラベル インターネット の投稿を表示しています。 すべての投稿を表示
ラベル インターネット の投稿を表示しています。 すべての投稿を表示

2009年10月31日土曜日

URIからパスを取得する

urlparse モジュールを使う

# -*- coding: utf-8 -*-

import urlparse
import urllib

o = urlparse.urlparse("file:///home/yoshi")
s = o.path

# 日本語が含まれている場合
s = urllib.unquote(s)

print o
print s

実行すると
ParseResult(scheme='file', netloc='', path='/home/yoshi', params='', query='', fragment='')
/home/yoshi

詳細はドキュメントで

2009年10月19日月曜日

URLからソースを取得する

urllibモジュールを使う

# -*- coding: utf-8 -*-

import urllib

filehandle = urllib.urlopen("http://www.python.jp/doc/release/lib/module-urllib.html")

for i in range(19):
    print filehandle.readline().decode("euc-jp"),

実行すると
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<link rel="STYLESHEET" href="lib.css" type='text/css' />
<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
<link rel='start' href='../index.html' title='Python ドキュメントインデクス' />
<link rel="first" href="lib.html" title='Python ライブラリリファレンス' />
<link rel='contents' href='contents.html' title="Contents" />
<link rel='index' href='genindex.html' title='Index' />
<link rel='last' href='about.html' title='About this document...' />
<link rel='help' href='about.html' title='About this document...' />
<link rel="next" href="module-urllib2.html" />
<link rel="prev" href="module-wsgiref.html" />
<link rel="parent" href="internet.html" />
<link rel="next" href="urlopener-objs.html" />
<meta http-equiv="Content-Type" content="text/html; charset=EUC-JP" />
<meta name='aesop' content='information' />
<title>18.5 urllib -- URL による任意のリソースへのアクセス</title>
</head>

詳細はドキュメントで

Webブラウザを開く

webbrowserモジュールを使う

import webbrowser

webbrowser.open("http://www.python.jp/doc/release/lib/module-webbrowser.html")

実行するとWebブラウザが開く

詳細はドキュメントで

ソケット通信

socketモジュールを使う

# -*- coding: utf-8 -*-

import socket

def server(host, port):
    s = socket.socket()
    s.bind((host, port))
    s.listen(1)
    conn, addr = s.accept()  # クライアントの接続を待つ
    data = conn.recv(1024)  # クライアントからのデータを受信する
    print "server: receive '%s'" % data
    conn.send(data.upper())  # クライアントにデータを送信する
    conn.close()
    s.close()

def client(host, port):
    s = socket.socket()
    s.connect((host, port))
    s.send("hello")  # サーバにデータを送信する
    data = s.recv(1024)  # サーバからのデータを受信する
    print "client: receive '%s'" % data
    s.close()

# 実行してみる
import threading
class Server(threading.Thread):
    def run(self):
        server("", 50007)
s = Server()
s.start()
client("", 50007)

実行すると
server: receive 'hello'
client: receive 'HELLO'

詳細はドキュメントで

2009年10月13日火曜日

CGI

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cgi

print "Content-Type: text/html"
print ""  # ヘッダ部の終了を示す空行

print """<html>
<title>cgi-test</title>
<body>
<h1>Hello</h1>"""

form = cgi.FieldStorage()

if form.has_key("name"):
    n = form["name"].value
    print n + "<br/>"

print """</body>
</html>"""

詳細はドキュメントで

2009年10月1日木曜日

メールを送信する

import smtplib
import email.mime.text

def send_mail(to, from_="", subject="", text=""):
    msg = email.mime.text.MIMEText(text)
    msg["Subject"] = subject
    msg["From"] = from_
    msg["To"] = to

    s = smtplib.SMTP("localhost")
    s.sendmail(from_, [to], msg.as_string())
    s.quit()

Gmailで送信する場合
ついでに、日本語のエンコーディングと日付のローカル化
# -*- coding: utf-8 -*-

import smtplib
import email.mime.text
import email.header
import email.utils

#引数subjectとtextは日本語が含まれているときはUnicodeで渡す
def send_mail_from_gmail(to, user, password, subject="", text="", encoding="ISO-2022-JP"):
    msg = email.mime.text.MIMEText(text.encode(encoding), "plain", encoding)
    msg["Date"] = email.utils.formatdate(localtime=True)
    msg["Subject"] = email.header.Header(subject, encoding)
    msg["From"] = user
    msg["To"] = to

    s = smtplib.SMTP()
    s.connect("smtp.gmail.com", 587)
    s.starttls()
    s.login(user, password)
    s.sendmail(user, [to], msg.as_string())
    s.close()

ついでにメールボックスの操作
import mailbox
import email.header

for msg in mailbox.Maildir("/home/yoshi/Maildir"):
    h = email.header.decode_header(msg["Subject"])[0]
    print h[0]
実行すると件名が表示される

詳細はドキュメントで