Python 中的模块
module定义
对于可复用的函数集,可以对其进行分组,整合到一个或者若干个.py文件中,而在python中,一个.py文件就叫做一个模块。变量,函数。
module注意点
- 为了避免命名冲突,python中引入目录组织的方式,这里称之为包(package)
每个包下都会有一个__init__.py文件,这个文件是必须存在的。否则python会把这个目录当作普通目录,而不是一个包。同时__init__.py文件本身是一个模块
module的导入方法
import module_name
import module_name,module2_name
from module_name import func1,func2,func3
from module_name import *
import module_name import func as func_local
由上可知,import实际上路径搜索和搜索路径,导入模块的本质就是把python文件解释一遍。执行__init__.py文件。试图加载某一个模块的时候,如果找不到就会报错。模块的搜索顺序为当前路径( ightarrow)内置模块( ightarrow)第三方库
import sys
sys.path.append('/Users/michael/my_py_scripts')
这种方法是运行时修改,运行结束后失效
常用module
- date,datetime,datetime stamp
- range
- os
- sys
- shelve
- xml
- configparser
- hashlib,hmac
date,datetime,datetime stamp
from datetime import datetime,tzinfo,timedelta
import time
class GMT1(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=1)
def dst(self,dt):
return timedelta(hours=0)
def tzname(self,dt):
return "Europe/Prague"
timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(timestamp)
timestamp=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
print(timestamp)
timestamp=datetime.now()
print(datetime.strftime(timestamp,"%Y-%m-%d %H:%M:%S"))
#timedelta表示一段时间
year=timedelta(days=365)
another_year= timedelta(weeks=40,days=84,hours=23,minutes=50,seconds=600)
print(year.total_seconds())
print(year==another_year)
timestamp=datetime.now()
#这里将timestamp加上一天时间
timestamp+=timedelta(days=1)
print(timestamp.strftime("%Y-%m-%d %H:%M:%S"))
#两个timedelta的运算
timestamp+=timedelta(days=1)+timedelta(hours=1)
print(timestamp.strftime("%Y-%m-%d %H:%M:%S"))
#除运算,返回float类型
value=timedelta(days=1)/timedelta(hours=2)
print(value)
#在秒级别进行运算,返回integer类型
value=timedelta(days=1)//timedelta(hours=2)
print(value)
#q=t1//t2 r=t%t2 一天和三个小时进行运算,所以这里,第一个应当返回整数8,第二个应当返回0,取余运算的返回类型为timedelta
q,r=divmod(timedelta(days=1),timedelta(hours=3))
print(q,r)
# 返回字符串格式为 [D day[s], ][H]H:MM:SS[.UUUUUU]
print(str(timedelta(days=-1,hours=-1))) #output: -2 days, 23:00:00,这里会自动进行时间的运算
datetimestamp=time(12,10,30,tzinfo=GMT1())
gmt=GMT1()
print(datetimestamp)
Random模块
import random
import collections
from statistics import mean,median,stdev
from random import choices,expovariate,gauss,shuffle
#这里的random()是生成一个0<=x<=1的随机数
print(random.random())
#uniform(2.5,10),生成一个2.5到10之间的一个随机数
print(random.uniform(2.5,10))
#指数分布
print(random.expovariate(1/5))
#区间内随机数
print(random.randrange(1,100))
#(start,end,step)三个参数
print(random.randrange(0,101,2))
#序列随机结果
print(random.choice(['hero','piro','maro']))
#短句随机打乱
deck='ace are split to four'.split()
random.shuffle(deck)
print(deck)
#从一个序列中随机抽样
sequence=['1','3','4','5','7','8','6']
print(random.sample(sequence,k=4))
#类似高中数学里一个袋子里有18个红球,18个黑球,2个绿球。从中随机抽出6个的意思
choice=random.choices(['red', 'black', 'green'], [18, 18, 2], k=6)
print(choice)
deck = collections.Counter(tens=16, low_cards=36)
seen = random.sample(list(deck.elements()), k=20)
print(seen.count('tens') / 20)
trial = lambda: random.choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5
print(sum(trial() for i in range(10000)) / 10000)
trial = lambda : 2500 <= sorted(random.choices(range(10000), k=5))[2] < 7500
print(sum(trial() for i in range(10000)) / 10000)
data = 1, 2, 4, 4, 10
means = sorted(mean(choices(data, k=5)) for i in range(20))
print(f'样本均值 {mean(data):.1f} 置信水平 90% '
f'interval from {means[1]:.1f} to {means[-2]:.1f}')
drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
observed_diff = mean(drug) - mean(placebo)
n = 10000
count = 0
combined = drug + placebo
for i in range(n):
shuffle(combined)
new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):])
count += (new_diff >= observed_diff)
print(f'{n} label reshufflings produced only {count} instances with a difference')
print(f'at least as extreme as the observed difference of {observed_diff:.1f}.')
print(f'The one-sided p-value of {count / n:.4f} leads us to reject the null')
print(f'hypothesis that there is no difference between the drug and the placebo.')
average_arrival_interval = 5.6
average_service_time = 5.0
stdev_service_time = 0.5
num_waiting = 0
arrivals = []
starts = []
arrival = service_end = 0.0
for i in range(20000):
if arrival <= service_end:
num_waiting += 1
arrival += expovariate(1.0 / average_arrival_interval)
arrivals.append(arrival)
else:
num_waiting -= 1
service_start = service_end if num_waiting else arrival
service_time = gauss(average_service_time, stdev_service_time)
service_end = service_start + service_time
starts.append(service_start)
waits = [start - arrival for arrival, start in zip(arrivals, starts)]
print(f'Mean wait: {mean(waits):.1f}. Stdev wait: {stdev(waits):.1f}.')
print(f'Median wait: {median(waits):.1f}. Max wait: {max(waits):.1f}.')
os模块
import os
#Executing a shell command
os.system()
#Get the users environment
os.environ()
#Returns the current working directory.
os.getcwd()
#Return the real group id of the current process.
os.getgid()
#Return the current process’s user id.
os.getuid()
#Returns the real process ID of the current process.
os.getpid()
#Set the current numeric umask and return the previous umask.
os.umask(mask)
#Return information identifying the current operating system.
os.uname()
#Change the root directory of the current process to path.
os.chroot(path)
#Return a list of the entries in the directory given by path.
os.listdir(path)
#Create a directory named path with numeric mode mode.
os.mkdir(path)
#Recursive directory creation function.
os.makedirs(path)
#Remove (delete) the file path.
os.remove(path)
#Remove directories recursively.
os.removedirs(path)
#Rename the file or directory src to dst.
os.rename(src, dst)
#Remove (delete) the directory path.
os.rmdir(path)
Sys模块
import sys
print('Version info:')
print()
print('sys.version =', repr(sys.version))
print('sys.version_info =', sys.version_info)
print('sys.hexversion =', hex(sys.hexversion))
print('sys.api_version =', sys.api_version)
print('This interpreter was built for:', sys.platform)
print('Name:', sys.implementation.name)
print('Version:', sys.implementation.version)
print('Cache tag:', sys.implementation.cache_tag)
if sys.flags.bytes_warning:
print('Warning on bytes/str errors')
if sys.flags.debug:
print('Debuging')
if sys.flags.inspect:
print('Will enter interactive mode after running')
if sys.flags.optimize:
print('Optimizing byte-code')
if sys.flags.dont_write_bytecode:
print('Not writing byte-code files')
if sys.flags.no_site:
print('Not importing "site"')
if sys.flags.ignore_environment:
print('Ignoring environment')
if sys.flags.verbose:
print('Verbose mode')
print('Default encoding :', sys.getdefaultencoding())
print('File system encoding :', sys.getfilesystemencoding())
class ExpressionCounter:
def __init__(self):
self.count = 0
self.previous_value = self
def __call__(self, value):
print()
print(' Previous:', self.previous_value)
print(' New :', value)
print()
if value != self.previous_value:
self.count += 1
sys.ps1 = '({:3d})> '.format(self.count)
self.previous_value = value
sys.__displayhook__(value)
print('installing')
sys.displayhook = ExpressionCounter()
print('Interpreter executable:')
print(sys.executable)
print('
Installation prefix:')
print(sys.prefix)
Shelve
import shelve
d = shelve.open(filename) # open -- file may get suffix added by low-level
# library
d[key] = data # store data at key (overwrites old data if
# using an existing key)
data = d[key] # retrieve a COPY of data at key (raise KeyError
# if no such key)
del d[key] # delete data stored at key (raises KeyError
# if no such key)
flag = key in d # true if the key exists
klist = list(d.keys()) # a list of all existing keys (slow!)
# as d was opened WITHOUT writeback=True, beware:
d['xx'] = [0, 1, 2] # this works as expected, but...
d['xx'].append(3) # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!
# having opened d without writeback=True, you need to code carefully:
temp = d['xx'] # extracts the copy
temp.append(5) # mutates the copy
d['xx'] = temp # stores the copy right back, to persist it
# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.
d.close() # close it