blog icon indicating copy to clipboard operation
blog copied to clipboard

Python 个人使用笔记

Open nkypy opened this issue 8 years ago • 0 comments

  • 获取本机 MAC 地址
def get_mac_addr():
    import uuid
    node = uuid.getnode()
    mac = uuid.UUID(int=node).hex[-12:].upper()
    return mac
  • 简单生成文件
def touch_file(fn):
    open(fn, 'a').close()
  • 类的属性不存在时返回 None
class Mark(object):
    def __init__(self):
        pass

    # 若属性不存在, 则返回 None
    def __getattr__(self, item):
        return None


mark = Mark()
  • for 循环里获取或更新类的值
# 获取
for key in list1:
    val = getattr(Class1, key)
# 更新
for key, val in dict1.items():
    setattr(dict1, key, val)
  • sudo 运行
# 授予sudo权限,有些命令需要sudo权限
def sudo_cmd(command):
    os.popen('echo %s|sudo -S %s' % (sudo_password, command)).read()

nkypy avatar Dec 08 '16 02:12 nkypy