Python编码技术:使用另一个方法作为接口来进行系统调用的类方法

2024-03-29 15:18:33 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以更好地利用python编码技术来实现我的代码,因为我有几个方法都是包装一个特定的方法,并在其中添加一些预/后处理

希望利用python编码技术(认为python装饰器可能有助于清理这一点)来实现下面的类

我有一个类,它有一个方法与外部世界接口,类中的其他方法用来执行操作和对一些数据进行预/后处理

import subprocess as sp


class MyClass():

    def _system_interface(self, command):
        hello = ["echo", "'hello'"]
        start = ["echo", "'start'"]
        stop = ["echo", "'reset'"]
        reset = ["echo", "'reset'"]

        cmd = sp.Popen(locals()[command], stdout=sp.PIPE)
        output = cmd.stdout.readlines()
        print(output)
        return cmd.stdout.readlines()

    def call_one(self):
        # Do some processing
        self._system_interface("hello")

    def call_two(self):
        # Do some processing
        self._system_interface("start")

    def call_three(self):
        # Do some processing
        self._system_interface("stop")

    if __name__ == "__main__":
        c = MyClass()
        c.call_one()
        c.call_two()
        c.call_three()

Tags: 方法echoselfcmdhellodefstdoutsome
1条回答
网友
1楼 · 发布于 2024-03-29 15:18:33

您可以使用一个类,该类在实例化时接受命令,在调用时返回一个decorator函数,该函数使用从实例化期间给定的命令派生的命令调用Popen

import subprocess as sp

class system_interface:
    def __init__(self, command):
        self.command = command

    def __call__(self, func):
        def wrapper(*args, **kwargs):
            func(*args, **kwargs)
            cmd = sp.Popen(['echo', self.command], stdout=sp.PIPE)
            output = cmd.stdout.readlines()
            print(output)
            return cmd.stdout.readlines()

        return wrapper

class MyClass():
    @system_interface('hello')
    def call_one(self):
        print('one: do some processing')

    @system_interface('start')
    def call_two(self):
        print('two: do some processing')

    @system_interface('stop')
    def call_three(self):
        print('three: do some processing')

if __name__ == "__main__":
    c = MyClass()
    c.call_one()
    c.call_two()
    c.call_three()

这将输出:

one: do some processing
[b'hello\n']
two: do some processing
[b'start\n']
three: do some processing
[b'stop\n']

相关问题 更多 >