本文主要参考和对官方文档进行二次浓缩而成
在使用
Python
编写程序的时候,我们常常会使用
Linux
系统下面的命令,比如需要执行一个
ifconfig
命令等。这时候,我们常常需要使用
os.popen
、
os.system
、
commands
或
subprocess
来完成,但是使用起来还是很不方便,有违和感。但是通过
sh
可以像调用函数一样调用
Linux
下系统命令。
源码,然后思考思考。
import sys
from types import ModuleType
class Tenv(ModuleType):
def __init__(self, self_module):
self.self_module = self_module
def __getattr__(self, name):
return f'{name} to -> test'
if __name__ == "__main__":
else:
self = sys.modules[__name__]
sys.modules[__name__] = Tenv(self)
>>> import test
>>> print test.ls
('ls' to -> test)