python的语言类型
模块
from…import…和import …
print('模块foo==>')
x = 1
def get():
print(x)
def change():
global x
x=0
print(x)
from test import x
from test import get
from test import change
print(x) # 1
get() # 1
change() # 0
get() # 0 (此时test空间中的x被change改掉了)
print(x) # 1 (该x还是demo空间中的x,而不是test中的x)
from test import x # (再次导入test空间中的x)
print(x) # 0 (x才会改变)
包
init.py文件
foo
│ m1.py
│ m2.py
│ m3.py
└─ __init__.py
direction1
└─demo.py
# 1. 绝对导入
from foo.m1 import f1
from foo.m2 import f2
from foo.m3 import f3
print("init")
# 方式1:
import foo
foo.f1()
# 方式2:
from foo import f1
f1()
常用模块
https://www.cnblogs.com/linhaifeng/articles/6384466.html#_label3
随机验证码random
# 应用场景:随机验证码
def make_code(n):
res=""
for i in range(n):
alpha = chr(random.randint(97, 122))
number = str(random.randint(0, 9))
res +=random.choice([alpha, number])
return res
print(make_code(8))
sys.argv使用场景
打印进度条
可以使用tqdm模块
print('[%-50s]' %'#')
"""
%s:格式化字符
%50s: 规定最小50个字符,不够补空格,默认右对齐
%-50s:左对齐
\r:从头开始
\n:换行
"""
https://wenku.baidu.com/view/8b03542a497302768e9951e79b89680202d86b4d.html
日志配置文件
logging.basicConfig(
# 1、日志输出位置:1、终端 2、文件
filename='access.log', # 不指定,默认打印到终端
# 2、日志格式
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
# 3、时间格式
datefmt='%Y-%m-%d %H:%M:%S %p',
# 4、日志级别
# critical => 50
# error => 40
# warning => 30
# info => 20
# debug => 10
level=30,
)