1、gevent使用
# -*- coding: utf-8 -*- import gevent import platform from gevent import subprocess def _test_shell(script): excute_data=[]; err_data=[]; if platform.system() == "Windows": popen = subprocess.Popen(script, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) excute_data = popen.stdout.readlines() err_data = popen.stderr.readlines() for msg_line in excute_data: print "return: %s" %(msg_line.strip()) for err_line in err_data: print "err:%s" %(err_line.strip()) def talk(msg): print(msg) def _test_spwan(): gevent.spawn(talk,"Fredirc") if __name__ == '__main__': _test_shell('java -version') _test_spwan() gevent.sleep(0.5) #上面例子打印输出 #err:java version "1.6.0_37" #err:Java(TM) SE Runtime Environment (build 1.6.0_37-b06) #err:Java HotSpot(TM) Client VM (build 20.12-b01, mixed mode, sharing) #Fredirc
2、logging使用
import logging import os from logging import FileHandler def get_logger(): logger = logging.getLogger('fredric_file') log_format = '%(asctime)s %(filename)s %(lineno)d %(levelname)s %(message)s' formatter = logging.Formatter(log_format) logfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'log', 'fredric_log.log') handler = FileHandler(logfile, "a") handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.ERROR) return logger def get_logger_console(): logger = logging.getLogger("fredric_console") log_format = '%(asctime)s %(filename)s %(lineno)d %(levelname)s %(message)s' formatter = logging.Formatter(log_format) console = logging.StreamHandler() console.setFormatter(formatter) logger.addHandler(console) logger.setLevel(logging.DEBUG) return logger logger_file = get_logger() logger_console = get_logger_console() if __name__ == '__main__': logger_file.error("fiel error") logger_console.error("console error") logger_file.info("fiel error") logger_console.info("console error")
3、imp使用(类似JAVA反射)
# -*- coding: utf-8 -*- import imp if __name__ == '__main__': #获取这个模块 module = imp.load_module("Test", *imp.find_module("test", ["./"])) #实例化这个模块中的类 temp=module.__getattribute__("Test")(); #执行类包含的方法 temp.do_staff() #打印:do_staff: Test Class print temp.__str__() #打印:to_string:Test Class