module in python

Python 中的模塊

module定義

對於可複用的函數集,能夠對其進行分組,整合到一個或者若干個.py文件中,而在python中,一個.py文件就叫作一個模塊。變量,函數。html

module注意點

  • 爲了不命名衝突,python中引入目錄組織的方式,這裏稱之爲包(package)python

    每一個包下都會有一個__init__.py文件,這個文件是必須存在的。不然python會把這個目錄看成普通目錄,而不是一個包。同時__init__.py文件自己是一個模塊shell

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文件。試圖加載某一個模塊的時候,若是找不到就會報錯。模塊的搜索順序爲當前路徑\(\rightarrow\)內置模塊\(\rightarrow\)第三方庫api

import sys
sys.path.append('/Users/michael/my_py_scripts')

這種方法是運行時修改,運行結束後失效app

經常使用module

modulesdom

  • date,datetime,datetime stamp
  • range
  • os
  • sys
  • shelve
  • xml
  • configparser
  • hashlib,hmac
date,datetime,datetime stamp

datetimeide

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('\nInstallation 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
相關文章
相關標籤/搜索