猫史档案馆


【Python模块】一个好用的命令行模块

用户:tq_xyytq_xyy查看:0 回复:0 评论:0 创建时间:2020-05-08T19:58:19


from os import system
def shell(execute,*args,sep=" "):
    """执行命令提示符命令
    execute -> 执行程序或命令名称
    *args ->附带参数
    sep ->分隔符"""
    return system(execute + " " + sep.join(args)) == 0


class compile_metaclass(type):
    """co喵ile_command的元类"""
    def __new__(cls,name,bases,classdict):
        if name == "compile_command":
            return type.__new__(cls,name,bases,classdict)
        if "command" in classdict:
            command = classdict.get("command")
            if type(command) != type([]):
                raise TypeError("command must is list")
        else:
            raise TypeError("must have command")
        if "sep" in classdict:
            sep = classdict.get("sep")
            if type(sep) != type(""):
                raise TypeError("sep must is str")
        else:
            sep = " "
        classdict["execute"] = command[0]
        classdict["sep"] = sep
        if len(command) == 1:
            classdict["onlyd"] = True
        else:  
            classdict["onlyd"] = False
            classdict["args"] = command[1:]
        classdict["frombases"] = ""
        return type.__new__(cls,name,bases,classdict)

class compile_command(object,metaclass=compile_metaclass):
    """编译命令,快速调用
继承此类
        command = 命令 -> list
        sep = 分隔符 -> str 默认" "

直接传参
        (执行程序名称,参数,sep=分隔符默认" ")

参数可以是字符串类型(默认类型)
也可以是元组类型(元组中的参数被忽视,
一个元组代表一个可变参数,需在运行时传参)

运行run()如果调用的可变参数,须传参
示例:
a = compile_command("pause",("a",))
a.run(">nul")

class b(compile_command):
    command = ["echo",("a",)]
c = b()
c.run("hello")"""
    def __init__(self,*args,**kwargs):
        try:
            self.frombases
        except (NameError,AttributeError):
            self.execute = args[0]
            try:
                self.sep = kwargs["sep"]
            except (IndexError,KeyError) as identifier:
                self.sep = " "
            if len(args) == 1:
                self.onlyd = True
            else:
                self.onlyd = False
                self.args = args[1:]
        self._check()
    def _check(self):
        if self.onlyd:
            return None
        temp = {}
        self.formal = {}
        j = 0
        for i in self.args:
            if type(i) == type("a"):
                temp[i] = "default"
            elif type(i) == type(("a",)):
                if len(i) == 1:
                    i = i[0]
                    temp[i] = "args"
                    self.formal[i] = j
                    j += 1
                else:
                    raise TypeError("%s's len must is 1"%i)
            else:
                raise TypeError("%s must is str or tuple"%i)
        del j
        self.args = temp


    def run(self,*args):
        """运行命令"""
        if self.onlyd:
            return shell(self.execute)
        else:
            if not len(args) == len(self.formal):
                raise TypeError("need %d args"%len(self.formal))

            arg = []
            for i in self.args:
                if self.args[i] == "default":
                    arg.append(i)
                elif self.args[i] == "args":
                    arg.append(args[self.formal[i]])
            return shell(self.execute,*arg,sep=self.sep)



#test.py
if __name__ == "__main__":
        
    a = compile_command("pause",">nul",("b",))
    a.run('2>nul')

    class b(compile_command):
        command = ["pause",("a",),("b",)]
    c = b()
    c.run(">nul","2>nul")

center_image


回复

上一页1 页 / 共 0下一页