Python代码片段分享

Python代码片段分享
Page content

不常用但很好用

0x00 判断是否虚拟环境

import sys

def is_venv():
    return (hasattr(sys, 'real_prefix') or
            (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))

0x01 多文件开启

names = ['file_a','file_b']

# 全版本适用
with open(names[0], 'w') as A, open(names[1], 'w') as B:
    ...

# 3.3+ 适用
filenames = ['file_a','file_b']
with ExitStack() as stack:
    files = [stack.enter_context(open(_,'w')) for _ in names]
    ...