popen2モジュールを使ったサブプロセスの実行(実行時刻を表示)
先日作成したcmd_wrapper2.pyの中のサブプロセスを実行する部分をモジュール化した。
さらに、プロセスの開始と終了時にそれぞれの時刻を表示する(time.ctime)ようにする。
以下、そのモジュール ExecCmd.pyを示す。
#!/usr/bin/env python """ Program name: ExecCmd.py Note : executing cmd_name Version : 0.1 Usage : """ import sys import popen2 import time def execmd(cmd_name, lines, output): """ start sub-process """ print 'inf> start %s [%s]' % (cmd_name, time.ctime(time.time())) r, w, e = popen2.popen3(cmd_name) success = True for x in lines: w.write(x) if lines: try: w.flush() except: success = False while True: s = r.readline() if s == '': break if output: output.write(s) s = e.read() if s: # print s if output: output.write(s) if not success or r.close() or w.close() or e.close(): success = False print 'err> failed %s [%s]' \ % (cmd_name, time.ctime(time.time())) else: print 'inf> done %s [%s]' % (cmd_name, time.ctime(time.time())) return success