【Python】python 策略模式 工厂模式 实现不同os 的命令执行


# -*- coding: utf-8 -*
# python2.7

import commands
import os
import platform
import logging


logging.basicConfig(
    level    = logging.DEBUG,
    format   = '%(asctime)s %(levelname)s %(process)d --- [%(threadName)s] %(filename)s %(funcName)s %(lineno)d : %(message)s',
    datefmt  = '%Y-%m-%d %H:%M:%S',
)


class OSPlatform(object):
    def execute(self, command):
        pass

class WindowsPlatform(OSPlatform):
    def execute(self, command):
        return os.system(command)

class LinuxPlatform(OSPlatform):
    def execute(self, command):
        return commands.getoutput(command)


class ExecContext(object):
    def __init__(self, os_platform):
        assert isinstance(os_platform, OSPlatform), "os_platform must be OSPlatform"
        self.__os_platform = os_platform 

    def get_result(self, command):
        return self.__os_platform.execute(command)


class ContextFactory(object):

    @staticmethod
    def get_context():
        station = platform.system()
        if station == "Windows":
            return  ExecContext(WindowsPlatform())
        elif station == "Linux":
            return  ExecContext(LinuxPlatform())
        else:
            logging.error("Does not support except Windows and Linux")
            
        

def print_VMFlags():
    context = ContextFactory.get_context()
    result = context.get_result("jps -l -m")
    print result

if __name__ == "__main__":
    print print_VMFlags()

    

“年轻时,我没受过多少系统教育,但什么书都读。读得最多的是诗,包括烂诗,我坚信烂诗早晚会让我邂逅好诗。” by. 马尔克斯
原文地址:https://www.cnblogs.com/jzsg/p/11018169.html