Python / Ref



ファイル操作

ファイルへの書き込み

f = file('a.txt', 'w+')
f.write('Hello, World!')
f.close()

オプション引数

単純なコマンドライン引数の取得

import sys
print sys.argv[1]
  • もちろん最初の引数argv[1]が表示される。
  • argc に対応するのは ... len(sys.argv) で代用かなぁ。

引数の解析(optparse編)

parser = optparse.OptionParser()

# 引数指定ありのオプションの場合
parser.add_option('-f', '--file', dest='filename',
                  help='write report to FILE', metavar='FILE')

# 引数指定なしのオプションの場合 "store_true"を指定。デフォルト値も指定。
parser.add_option("-a", action="store_true", dest="allInfo", default=False,
                  help='print all info')
(options, args) = parser.parse_args()


# options.(destで指定したもの)でアクセス可能。 
# そして勝手に -h で表示されるヘルプも作ってくれている。

if options.filename != None:
    print "file = options.filename"
else:
    print "file = None"

if options.allInfo:
    print "allInfo = True"
else:
    print "allInfo = False"

ネットワーク関連

HTTP通信を行う(HTTPConnection)

GETリクエストの送信

import httplib

con = httplib.HTTPConnection('www.yahoo.co.jp')  # とりあえず作る(コネクトはまだしてない)
con.request('GET', '/index.html')                # リクエストを送って..
response = con.getresponse()                     # レスポンス受信。
print response.read()                            # 中身読む。

プロキシを使う。

import httplib

con = httplib.HTTPConnection("proxy-url", 8080);
#con = httplib.HTTPConnection("proxy-url:8080"); も可!
con.request('GET', "http://www.yahoo.co.jp")
response = con.getresponse()

文字コード関連


文字コードの判別

#!/usr/bin/python
# -*- coding: utf-8 -*-
import chardet
print chardet.detect("あいう")['encoding']
  • chardet.detect() を呼び出せば判別できる。
  • chardetライブラリ(Universal Encoding Detector)はこちらから
  • よくわからないが、"-*- cording:"宣言しとかないとうまく動かない。

EUC→unicode

u = unicode('EUCの文字列', 'euc_jp')  # EUCの文字列を..
print u.encode('utf_8')               # utf-8で表示。ファイルとかにしなきゃわからんけど
  • Shift-JISの場合は'shift_jis'と指定。
  • 実際のところ2行目はいらないと思う、がshift_jisとかしたいとき用のメモとして。

MenuBar


最新の20件

2015-05-15 2014-12-07 2008-11-17 2007-08-30 2007-04-21 2007-03-13 2007-03-12
  • Python/Ref
2007-02-20 2007-02-14 2007-02-04 2006-11-26 2006-11-23 2006-11-20 2006-11-18 2006-11-13

  • counter: 1018
  • today: 1
  • yesterday: 0
  • online: 1