ss=p='' for s in html_text: #unicodeはMultiBite文字も文字単位処理 if s=='\n' or s=='\r' or p=='\n' or p=='\r' or ss=='': #改行符号と頭の文字の ss=ss+s #前後には空白文字を加えず else: #そうでないなら ss=ss+' '+s #空白文字を加える p=s #直前の文字を代入 html_text=ss #html_textを置換え
が、
今回の「HTMLタグ表示」処理部分
ss = html_text.replace(u'&',u'&').replace(u'<',u'<')\ .replace(u'>',u'>').replace(u'&',u'&') #最後の&の変換がミソ!! html_text = ss
if debug > 1: #debugレベル2: CGI引数の名前と値を表示します。 print '<table><tr><td align="right"><pre align="left" style="text-align:center;\ pre-wrap; white-space: -moz-pre-wrap; white-space: -pre-wrap;\ white-space: -o-pre-wrap; word-wrap: break-word; ">' for p in prms: print '%s: %s' % (p,prms[p]) print '</pre></td></tr></table>'
if 'html_text' in prms: #cgi引数が存在したら、 html_text=unicode(prms['html_text']) # CGIの引数の値はunicode化しないと駄目の様だ ss = html_text.replace(u'&',u'&').replace(u'<',u'<')\ .replace(u'>',u'>').replace(u'&',u'&') #最後の&の変換がミソ!! html_text=ss #html_textを置換え
except: #vividな作成部分はhtm.display_err() if debug > 0: #でdebug情報を取得。運用時はdebug=0 print '' #とし障害内容は表示させない。 display_err(locals()) #>mire.htm.display_err()#Web用の例外処理で障害切分 print '</span>' else: #運用中のdebug message表示はセキュリティ上不適格。通常はdebug=0で以下のmessage print '<pre>Error was occured.\nPlease, contact your system administrators.\n' print 'You? Do Your Best!\n Test html4spam.py with debug=2. Good luck.</pre>'
######################################## ## ## ## 処理実行開始位置 ## ## ## ######################################## try: from mire.htm import display_err, html_header, html_footer html_header(charset='UTF-8', title=u'HTML CODE_TEXT for BLOG 0.0.0 (C) 2009 Mire GPL license' , body=['style="right-margin:0px; background-color:#808080;"']) contents(debug=debug) html_footer() except: if debug > 0: display_err(locals()) #こちらは最後の抑え else: #運用中のdebug message表示はセキュリティ上不適格。通常はdebug=0で以下のmessage print 'Content-type: text/html\n\n<html>\n<head></head><body>' print '<pre>Error was occured.\nPlease, contact your system administrators.\n' print 'You? Do Your Best!\n Test html4spam.py with debug=2.\n\nGood luck.</pre>' print '</pre></body></html>'
## エラー表示関数(コメント行文字化け対策+thread実行時のエラー情報表示の時系列混乱軽減) ## def display_err(self,local, title = '\n\n#### EXCEPTION ERROR ####'): """ ########################################################################################## #エラー表示関数(コメント行文字化け対策 + thread実行時のエラー情報表示の時系列混乱軽減) # #USAGE: 第一引数に「locals()」を指定することで、処理時の変数値を表示します。 # # waitingはthread実行時のエラー情報表示の時系列混乱軽減の為のWAIT処理です。 # # waiting = 0 # # def foo(): # # global waiting # # sleep(waiting) # # try: # # 処理 # # waiting = 0 # # except: # # display_err(locals(),'<例外処理の場所を表すタイトル>')# locals()指定は必須 # # waiting = 1 # # foo() # ########################################################################################## """ import traceback from time import sleep print('Content-type: text/html\n\n<html>\n<head>') print('<body><pre>') if local is None: local =locals() global waiting frame0 = '\n*******************************************************************************' frame1 = '*******************************************************************************\n\n' errs = [frame0, title] errs.append('%s' % (self.dsp_hex(traceback.format_exc()))) #> dsp_hex(s): コメント文字化け対策 sleep(waiting) ls = local keys = list(ls.keys()) errs.append('') for key in keys: # display_err()関係の変数の表示を省く # if not key in ['v', 'ls', 'keys', 'key', 'errs', 'txt', 'er', 'sleep']: er = '* %s: %s' % (repr(key).ljust(24),repr(ls[key])) errs.append(er) errs.append(frame1) txt = '\n'.join(errs) print(txt) print('</pre></body></html>')
## コメント文字化け対策 ## def dsp_hex(self,s): from re import search charsets=['UTF-8','Shift_JIS','EUC-JP','iso-2022-jp'] # どれでもいいので、charsetで、 for charset in charsets: # unicode化し、コメント部分の try: # 文字化けを防ぐ return str(s,charset) except: print('%sでは変換不能でした' % (charset)) pass sss='' for ss in s: # 想定外のcharsetのときは16進数表記に if (ord(ss)>=32 and ord(ss)<=126) or ss.isspace(): # Windowsにはcurses.ascii.isprint()が sss=sss+ss # ないのでcurses/ascii.pyの中身を展開 else: sss=sss+'\\'+hex(ord(ss))[2:].upper() return sss
if debug > 1: #debugレベル2: CGI引数の名前と値を表示します。 print '<pre align="left" style="text-align:center; white-space: pre-wrap;\ white-space: -moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap;\ word-wrap: break-word; ">' for p in prms: print '%s: %s' % (p,prms[p]) print '</pre>'
if 'html_text' in prms: #cgi引数が存在したら、 html_text=unicode(prms['html_text']) # CGIの引数の値はunicode化が必要な様だ ss=p='' for s in html_text: #unicodeはMultiBite文字も文字単位処理 if s=='\n' or s=='\r' or p=='\n' or p=='\r' or ss=='': #改行符号と頭の文字の ss=ss+s #前後には空白文字を加えず else: #そうでないなら ss=ss+' '+s #空白文字を加える p=s #直前の文字を代入 html_text=ss #html_textを置換え else: #引数がないなら html_text='' #0長文字列
except: #vividな作成部分はhtml if debug > 0: print '<span align="left">' display_err(locals()) #>mire.htm.display_err() #用の例外処理で障害切分 print '</span>' else: #運用中のdebug message表示はセキュリティ上不適格。通常はdebug=0で以下のmessage print '<pre>Error was occured.\nPlease, contact your system administrators.\n' print 'You? Do Your Best!\n Test html4spam.py with debug=2. Good luck.</pre>'
######################################## ## ## ## 処理実行開始位置 ## ## ## ######################################## try: from mire.htm import display_err, html_header, html_footer html_header(charset='UTF-8', title=u'SPAM COMMENT SPLITTER (C) 2009 Mire GPL license' , body=['style="right-margin:0px; background-color:#808080;"']) contents(debug=debug) html_footer() except: if debug > 0: display_err(locals()) #こちらは最後の抑え else: #運用中のdebug message表示はセキュリティ上不適格。通常はdebug=0で以下のmessage print 'Content-type: text/html\n\n<html>\n<head></head><body>' print '<pre>Error was occured.\nPlease, contact your system administrators.\n' print 'You? Do Your Best!\n Test html4spam.py with debug=2.\n\nGood luck.</pre>' print '</pre></body></html>'
Microsoft Windows [Version 6.0.6001] Copyright (c) 2006 Microsoft Corporation. All rights reserved.
C:\Users\SysAdm>c:\Python26\python.exe Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import mire >>> help(mire) Help on package mire:
## エラー表示関数(コメント行文字化け対策+thread実行時のエラー情報表示の時系列混乱軽減) ## def display_err(local, title = u'\n\n#### EXCEPTION ERROR ####'): """ ########################################################################################## #エラー表示関数(コメント行文字化け対策 + thread実行時のエラー情報表示の時系列混乱軽減) # #USAGE: 第一引数に「locals()」を指定することで、処理時の変数値を表示します。 # # waitingはthread実行時のエラー情報表示の時系列混乱軽減の為のWAIT処理です。 # # waiting = 0 # # def foo(): # # global waiting # # sleep(waiting) # # try: # # 処理 # # waiting = 0 # # except: # # display_err(locals(),'<例外処理の場所を表すタイトル>')# locals()指定は必須 # # waiting = 1 # # foo() # ########################################################################################## """ import traceback from time import sleep if local is None: local =locals() global waiting frame0 = u'\n*******************************************************************************' frame1 = u'*******************************************************************************\n\n' errs = [frame0, title] errs.append(u'%s' % (dsp_hex(traceback.format_exc()))) #> dsp_hex(s): コメント文字化け対策 sleep(waiting) ls = local keys = ls.keys() errs.append(u'') for key in keys: # display_err()関係の変数の表示を省く # if not key in ['v', 'ls', 'keys', 'key', 'errs', 'txt', 'er', 'sleep']: er = u'* %s: %s' % (repr(key).ljust(24),repr(ls[key])) errs.append(er) errs.append(frame1) txt = u'\n'.join(errs) print txt
## コメント文字化け対策 ## def dsp_hex(s): from re import search charsets=['UTF-8','Shift_JIS','EUC-JP'] # どれでもいいので、charsetで、 for charset in charsets: # unicode化し、コメント部分の try: # 文字化けを防ぐ return unicode(s,charset) except: print u'%sでは変換不能でした' % (charset) pass sss=u'' for ss in s: # 想定外のcharsetのときは16進数表記に if (ord(ss)>=32 and ord(ss)<=126) or ss.isspace(): # Windowsにはcurses.ascii.isprint()が sss=sss+ss # ないのでcurses/ascii.pyの中身を展開 else: sss=sss+'\\'+hex(ord(ss))[2:].upper() return sss
################### #### TEST CODE #### ###################
## threadで実行に組込んだ関数 ## def test_func(): """ datetimeの演算は引算のみ、足算は出来ないぞ """ from time import sleep from datetime import datetime
global waiting sleep(waiting) try: a=datetime.now() b=datetime.now() sleep(waiting) c=datetime.now() a=b-c d=c+b # datetimeを足したいの I what to add datetime object's. print a waiting = 0 except: display_err(locals(),title = u'### main()内例外発生時の情報 ###') # locals()指定は必須 waiting = 1 raise
from thread import start_new_thread from time import sleep try: while 1: try: start_new_thread(test_func,()) #waiting = 0 except: waiting = 1 display_err(locals(), title = u'### thread実行loopでの例外発生時の情報 ###') break sleep(waiting) #print waiting except: display_err(locals(), title = u'### 終了時の情報 ###') # 終了時の情報
以下が、上記テストコードの実行結果だ。連続LOOPの為、当然、Ctrl+Cで停止して取得している。残念ながら、Windowsのコマンドプロンプトでの実行では、「Unhandled exception in thread started by <function test_func at 0x01C6CE30>」の発生内容がECHOされ文字化けしたtraceback情報が表示されている。
******************************************************************************* ### main()内例外発生時の情報 ### Traceback (most recent call last): File "traceback_exc_info_and_locals_within_thread5.py", line 90, in test_func d=c+b # datetimeを足したいの I what to add datetime object's. TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'
Unhandled exception in thread started by <function test_func at 0x01C6CE30> Traceback (most recent call last): File "traceback_exc_info_and_locals_within_thread5.py", line 90, in test_func d=c+b # datetime繧定カウ縺励◆縺・・ I what to add datetime object's. TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'
******************************************************************************* ### main()内例外発生時の情報 ### Traceback (most recent call last): File "traceback_exc_info_and_locals_within_thread5.py", line 90, in test_func d=c+b # datetimeを足したいの I what to add datetime object's. TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'
Unhandled exception in thread started by <function test_func at 0x01C6CE30> Traceback (most recent call last): File "traceback_exc_info_and_locals_within_thread5.py", line 90, in test_func d=c+b # datetime繧定カウ縺励◆縺・・ I what to add datetime object's. TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'
******************************************************************************* ### 終了時の情報 ### Traceback (most recent call last): File "traceback_exc_info_and_locals_within_thread5.py", line 110, in <module> sleep(waiting) KeyboardInterrupt
def print_reply(self, opts, buf, rtt): ip = dpkt.ip.IP(buf) if sys.platform == 'darwin': # XXX - work around raw socket bug on MacOS X ip.data = ip.icmp = dpkt.icmp.ICMP(buf[20:]) ip.len = len(ip.data) #print '%d bytes from %s: icmp_seq=%d ip_id=%d ttl=%d time=%.3f ms' % \ # (len(ip.icmp), opts.ip, ip.icmp.echo.seq, ip.id, ip.ttl, # rtt * 1000)
def ping(ip,wait=0.1,debug=0): from os import popen from time import sleep global PINGs global PING0 global PING1 try: argv = ['-i','%f' % (wait),'-c','1', ip] p= ICMPPing() nw=datetime.now() response = p.main(argv=argv) PINGs.append((ip,response,nw)) if response==1: PING1.append((ip,1,nw)) elif response==0: PING0.append((ip,0,nw)) if debug>2: print ip,response,datetime.now() except: ppi=popen('ping -n 1 -w 1 %s' % (ip)) lines = ppi.readlines() for l in lines: s=l.find('(') e=l.find('%') if s>0 and e>0: loss=int(l[s+1:e]) print ip,int(l[s+1:e]) if loss==100: i=0 while i<=3: try: PINGs.append((ip,0)) PING0.append((ip,0)) i=4 except ProgrammingError,err: print '\a',err i=i+1 sleep(0.01*i) pass elif loss==0: i=0 while i<=3: try: PINGs.append((ip,1)) PING1.append((ip,1)) i=4 except ProgrammingError,err: print '\a',err i=i+1 sleep(0.01*i)
def arp_v_a(): from os import popen,environ if environ['os'].upper()[:3]=='WIN': ppi=popen('arp -v -a') lines = ppi.readlines() datas=[] for l in lines: s = l.strip().split() if len(s)>=3: ip=s[0] mac=s[1] if len(mac.split('-'))>=6 and not mac=='00-00-00-00-00-00': print ip,mac datas.append([ip,mac]) return datas else: #ここは、Mireの開発環境外対応を机上で考えた暫定版である #Windows以外のOSでの処理は利用可能なpythonモジュールに置換えが推奨される。 ppi=popen('arp -v -a') lines = ppi.readlines() datas=[] for l in lines: s = l.strip().split() if len(s)>=3: ip=s[0] mac=s[2] if len(mac.split(':'))>=6 and not mac=='00:00:00:00:00:00': print ip,mac datas.append([ip,mac]) return datas
def pings(wait,debug=0): from datetime import datetime from thread import start_new_thread from time import sleep global PINGs tm_s = datetime.today() tm=tm_s PINGs=[] PING0=[] PING1=[] for i in xrange(254): start_new_thread(ping,('192.168.0.%d' % (i+1),wait,debug,)) #sleep(0.08) # 「Unhandled exception in thread started by」除けお呪い sleep(0.08) # 「Unhandled exception in thread started by」除けお呪い tm_p=tm tm = datetime.now() if debug>0: print tm-tm_p tm_e = datetime.now() sleep(3.0) # 最後に実行したthreadが終了する最大マージン分待つ while not len(PINGs)==254: sleep(0.1) print tm-tm_s macs = arp_v_a()
return PINGs # grobal変数なのでreturnは不要と言えば不要かも
debug=3 wait=3.2 i=0 while i<5: #5は連続実行テスト回数 PINGs=[] PING0=[] PING1=[] datas = pings(wait=wait,debug=debug) for d in datas: print d i=i+1 arp_v_a()
##def ping(ip,conn,cur): def ping(ip): from os import popen ## from kinterbasdb import ProgrammingError from time import sleep global PINGs ppi=popen('ping -n 1 -w 1 %s' % (ip)) lines = ppi.readlines() for l in lines: s=l.find('(') e=l.find('%') if s>0 and e>0: loss=int(l[s+1:e]) print ip,int(l[s+1:e]) if loss==100: i=0 while i<=3: try: ## cur.execute("INSERT INTO PINGS (IP,LIVE)VALUES('%s',0);" % (ip)) PINGs.append((ip,0)) i=4 except ProgrammingError,err: print '\a',err i=i+1 sleep(0.01*i) pass elif loss==0: i=0 while i<=3: try: ## cur.execute("INSERT INTO PINGS (IP,LIVE)VALUES('%s',1);" % (ip)) PINGs.append((ip,1)) i=4 except ProgrammingError,err: print '\a',err i=i+1 sleep(0.01*i) ##【Firebird2が完全なthread freeではない現実】 ## ## ## その1: 多分、カーソルが使用中で書き込めない場合 ## ## Unhandled exception in thread started by ## 192.168.0.21Unhandled exception in thread started by ## Traceback (most recent call last): ## ## Traceback (most recent call last): ## File "alive_hosts.py", line 31, in ping ## File "alive_hosts.py", line 31, in ping ## cur.execute("INSERT INTO PINGS (IP,LIVE)VALUES('%s',1);" % (ip)) ## kinterbasdb100.ProgrammingError: ## (0L, 'Invalid cursor state. The cursor must be open to perform this operation.') ## cur.execute("INSERT INTO PINGS (IP,LIVE)VALUES('%s',1);" % (ip)) ## kinterbasdb.ProgrammingError: (0L, ## 'Invalid cursor state. The cursor must be open to perform this operation.') ## 0:00:00.096000 ## 0:00:00.091000 ## ## ##その2: 状況は判らないが、コンパイルモジュール側で障害が発生し停止する。次期メジャーバージョン待ち ## ## Assertion failed: ps != NULL, file c:\kinterbasdb\kinterbasdb-3.3.0\_kicore_xsqlda.c, line 147 ## ## This application has requested the Runtime to terminate it in an unusual way. ## Please contact the application's support team for more information. ## ##
##def pings(conn=None, cur=None, dsn='', user='SYSDBA', password='masterkey',dialect=3): def pings(): from datetime import datetime from thread import start_new_thread from time import sleep ## from kinterbasdb import connect global PINGs tm_s = datetime.today() tm=tm_s ## if conn is None: ## conn = connect(dsn=dsn,user=user,password=password,dialect=dialect) ## cur = conn.cursor() ## cur.execute('DELETE FROM PINGS;') PINGs=[] for i in xrange(254): ## start_new_thread(ping,('192.168.0.%d' % (i+1),conn,cur,)) start_new_thread(ping,('192.168.0.%d' % (i+1),)) sleep(0.08) # 「Unhandled exception in thread started by」除けお呪い tm_p=tm tm = datetime.today() print tm-tm_p tm_e = datetime.today() sleep(1.0) # 最後に実行したthreadが終了する最大マージン分待つ while not len(PINGs)==254: sleep(0.1) ## conn.commit() ## cur.execute('SELECT IP,LIVE FROM PINGS;') ## datas=cur.fetchall() ## cur.execute('DELETE FROM PINGS;') ## #conn.commit() print tm-tm_s ## return datas return PINGs # grobal変数なのでreturnは不要と言えば不要かも
def create_db(dsn='localhost:DUMMY',user='SYSDBA',password='masterkey',page_size=None): from kinterbasdb import create_database ds=dsn[len(dsn.split(':')[0]):] sql="CREATE DATABASE '%s' USER '%s' PASSWORD '%s'" % (ds,user,password) if not page_size is None: sql=sql+'PAZE_SIZE %d' % (page_size) conn=create_database(sql) conn.commit() conn.close()
def exists_tbl(table,conn=None,cur=None,dsn='', user='SYSDBA', password='masterkey'): """システムテーブル「RDB$RELATIONS」に接続し作成予定のテーブル名が 既存テーブルとダブってないか調査 """ from kinterbasdb import connect sql_exists="""SELECT RDB$RELATION_ID FROM RDB$RELATIONS WHERE RDB$RELATION_NAME='%s';""" % (table) if conn==None: try: conn=connect(dsn=dsn,user=user,password=password) cur=conn.cursor() cur.execute(sql_exists) if len(cur.fetchall())==0: # 存在しなかったら return 0 else: return 1 except: return -1 finally: conn.close() # 接続を閉じる。 else: try: cur.execute(sql_exists) if len(cur.fetchall())==0: # 存在しなかったら return 0 else: return 1 except: return -1 finally: conn.close() # 接続を閉じる。
def init_db(dsn, user='SYSDBA', password='masterkey',dialect=3): if not exists_db(dsn=dsn,user=user,password=password): create_db(dsn=dsn,user=user,password=password)
def init_table(table,sql,conn=None,cur=None,dsn='', user='SYSDBA', password='masterkey',dialect=3): from kinterbasdb import connect if not exists_tbl(table,conn=None,cur=None,dsn=dsn,user=user,password=password): create_tbl(sql=sql,dsn=dsn,user=user,password=password)
#telnet('192.168.0.23',80) ##dsn='localhost:K:\\PyPRec_Alive.fdb' ##user='SYSDBA' ##password='masterkey' ##dialect=3 ##init_db(dsn=dsn,user=user,password=password) ##sql='CREATE TABLE PINGS(IP VARCHAR(16), LIVE INTEGER,PRIMARY KEY(IP));' ##init_table(table='PINGS', sql=sql, conn=None, cur=None, dsn=dsn, user=user, password=password) ##print pings(conn=None, cur=None, dsn=dsn, user=user, password=password, dialect=dialect) i=0 while i<1000: PINGs=[] datas = pings() for d in datas: print d i=i+1