How to run your cmd as a function in module?

题目即问题。

开了一下脑洞,想要把终端里的命令映射成module里的自由函数。

# file: shell.py
import sys
import subprocess
from functools import partial


class Shell(object):

    def __getattr__(self, name):
        return partial(self.__shell__, name)

    @staticmethod
    def __shell__(*args):
        return subprocess.call(args)


sys.modules[__name__] = Shell()

但是失败了...

>>> import shell
>>> shell.ls()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "shell.py", line 11, in __getattr__
    return partial(self.__shell__, name)
TypeError: 'NoneType' object is not callable

btw, 注释掉最后一行可以勉强用

>>> from shell import Shell
>>> s = Shell()
>>> s.echo('hello')
hello
0
2 comments