Skip to main content

75 posts tagged with "Python"

View All Tags

Python: SimpleHTTPServerでWebサーバをたてる

· 2 min read
Yu Sasaki
Enterprise Security Manager / Advisor

Python のみでWebサーバを提供できるのでその動作確認。今回は下記SimpleHTTPServerモジュールを使用する。

import SimpleHTTPServer
SimpleHTTPServer.test()

上記コードを実行すると下記のようにWebサーバをポート8000番(デフォルト)で提供する。

Python: Beautiful Soupのインストール - Mac OS編

· 2 min read
Yu Sasaki
Enterprise Security Manager / Advisor

インストール方法自体は配布元に記載の方法で実施。

参考サイト

  1. Beautiful Soup: We called him Tortoise because he taught us.
  2. Beautiful Soup Documentation — Beautiful Soup 4.0.0 documentation

The current release is Beautiful Soup 4.1.3 (August 20, 2012). You can install it with pip install beautifulsoup4 or easy_install beautifulsoup4. It's also available as the python-beautifulsoup4 package in recent versions of Debian and Ubuntu.

Python: UDP/IPv4 Socket Server/Client (1 Client接続のみ)

· 2 min read
Yu Sasaki
Enterprise Security Manager / Advisor

先日はTCPでのデータ送受だったので、今回はUDPプロトコルを用いた確認をする。

ソースコード(for Python 2.7)

補足はソースコード中のコメントを参照。サンプルの為、サーバ・クライアントは同一マシン上での実行を想定。 tsUdpServ.py

# coding: utf-8
from socket import *
from time import ctime
HOST = gethostname()
PORT = 34512
BUFSIZE = 1024
ADDR = (gethostbyname(HOST), PORT)
USER = 'Server'
udpServSock = socket(AF_INET, SOCK_DGRAM) # IPv4/UDPでソケット作成
udpServSock.bind(ADDR) # HOST, PORTでbinding
while True:
print 'Waiting for message...'
data, addr = udpServSock.recvfrom(BUFSIZE) # データ受信
print '...received from and returned to:', addr
udpServSock.sendto('%s > [%s] %s' % (USER, ctime(), data), addr) # データ送信
udpServSock.close()

TCPと大きく変わるところは、ソケットの作成時にソケットファミリーをSOCK_DGRAMとすること。また、listen()とaccept()メソッドが不要となったところあたりかな。 tsUdpClnt.py

# coding: utf-8
from socket import *
HOST = gethostname()
PORT = 34512
BUFSIZE = 1024
ADDR = (gethostbyname(HOST), PORT)
USER = 'Client'
udpClntSock = socket(AF_INET, SOCK_DGRAM)
while True:
data = raw_input('%s > ' % USER) # 標準入力からのデータ入力
if not data:
break
udpClntSock.sendto(data, ADDR) # データ送信
data, ADDR = udpClntSock.recvfrom(BUFSIZE) # データ受信
if not data:
break
print data # データ出力
udpClntSock.close()

Python: TCP/IPv4 Socket Server/Client (1 Client接続のみ)

· 2 min read
Yu Sasaki
Enterprise Security Manager / Advisor

PythonでSocketサーバ、クライアントの接続方法を下記のソースコードを用いて確認。C言語のどう程度のサンプルと比較すると行数が少なく、書きやすい。これがThreadやノンブロッキング・多重化を用いた時にどの程度膨らむかは今後確認予定。

ソースコード(for Python 2.7)

補足はソースコード中のコメントを参照。サンプルの為、サーバ・クライアントは同一マシン上での実行を想定。 tsTcpServ.py

# coding: utf-8
from socket import *
from time import ctime
HOST = gethostname()
PORT = 34567
BUFSIZE = 1024
ADDR = (gethostbyname(HOST), PORT)
USER = 'Server'
tcpSerSock = socket(AF_INET, SOCK_STREAM) # IPv4/TCPソケットとして作成
tcpSerSock.bind(ADDR) # アドレス、ポートのbinding
tcpSerSock.listen(5) # サーバソケットの最大接続要求の順番待ち数
while True:
print 'Waiting for connection...'
(tcpCliSock, addr) = tcpSerSock.accept() # 接続待受開始
print '...connected from.' , addr
while True:
data = tcpCliSock.recv(BUFSIZE) # C->Sデータの受信
if not data:
break
tcpCliSock.send('%s > [%s] %s' % (USER, ctime(), data)) # S->Cデータの送信
tcpCliSock.close() # Clientソケットのclose
tcpSerSock.close() # Serverソケットのclose (到達不能コード)

tsTcpclnt.py

# coding: utf-8
from socket import *
HOST = gethostname()
PORT = 34567
BUFSIZE = 1024
ADDR = (gethostbyname(HOST), PORT)
USER = 'Client'
tcpClntSock = socket(AF_INET, SOCK_STREAM)
tcpClntSock.connect(ADDR)
while True:
data = raw_input('%s > ' % USER) # 標準入力からのデータ入力
if not data:
break
tcpClntSock.send(data) # C->Sへデータ送信
data = tcpClntSock.recv(BUFSIZE) # S->Cのデータ受信
if not data:
break
print data
tcpClntSock.close()

Python: ソースコード中でのUTF-8文字(日本語等)のエンコーディング指定

· One min read
Yu Sasaki
Enterprise Security Manager / Advisor

Pythonスクリプトの実行(コンパイル→実行)の際に下記のエラーが発生した場合、

SyntaxError: Non-ASCII character '\ABC' in file C:\XXX\YYY\ZZZ.py on line MM,
but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

ソースコード中にASCII以外の文字(日本語など)が含まれているがエンコードの指定が無いことが原因となる。 対処法はスクリプトの先頭行に下記の何れかの1行記述することでUTF-8文字の使用を宣言する。

# coding: utf-8

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

参考サイト

Python: MS Word ファイルからテキストファイルへ変換

· 2 min read
Yu Sasaki
Enterprise Security Manager / Advisor

COM(Component Object Model)を使用してWordファイル内のテキストをテキストファイルへ抽出・変換するスクリプト。

ソースコード

# coding: utf-8
import fnmatch, os, sys, win32com.client
if __name__ == '__main__':
wa = win32com.client.gencache.EnsureDispatch("Word.Application")
try:
for path, dirs, files in os.walk(sys.argv[1]): # コマンドラインより探索ディレクトリpathを取得
for filename in files:
if not fnmatch.fnmatch(filename, "*.doc"): continue # wordファイルの拡張子かをパターン・マッチング
doc = os.path.abspath(os.path.join(path, filename)) # wordファイルへの絶対パスを作成
print "processing %s in %s" % (doc, path)
wa.Documents.Open(doc)
txt = doc[:-3] + 'txt' # 変換保管するテキストファイル名
wa.ActiveDocument.SaveAs(txt, FileFormat=win32com.client.constants.wdFormatText)
wa.ActiveDocument.Close()
finally:
wa.Quit() # Wordの終了