python标准库学习8

简介:

使用sys重定向输出

import  sys
import  string
 
class  Redirect:
 
     def  _ _init_ _( self , stdout):
         self .stdout =  stdout
 
     def  write( self , s):
         self .stdout.write(string.lower(s))
 
# redirect standard output (including the print statement)
# 重定向标准输出(包括print语句)
old_stdout =  sys.stdout
sys.stdout =  Redirect(sys.stdout)
 
print  "HEJA SVERIGE" ,
print  "FRISKT HUM\303\226R"
 
# restore standard output
# 恢复标准输出
sys.stdout =  old_stdout
 
print  "M\303\205\303\205\303\205\303\205L!"
 
heja sverige friskt hum\ 303 \ 266r
M\ 303 \ 205 \ 303 \ 205 \ 303 \ 205 \ 303 \ 205L !

  

使用sys模块退出程序

import  sys
 
print  "hello"
 
sys.exit( 1 )
 
print  "there"
 
hello

  注意 sys.exit 并不是立即退出. 而是引发一个 SystemExit 异常. 这意味着你可以在主程序中捕获对 sys.exit 的调用

捕获sys.exit调用

import  sys
 
print  "hello"
 
try :
     sys.exit( 1 )
except  SystemExit:
     pass
 
print  "there"
 
hello
there

  如果准备在退出前自己清理一些东西(比如删除临时文件), 你可以配置一个 "退出处理函数"(exit handler), 它将在程序退出的时候自动被调用

另一种捕获sys.exit调用的方法

import  sys
 
def  exitfunc():
     print  "world"
 
sys.exitfunc =  exitfunc
 
print  "hello"
sys.exit( 1 )
print  "there"  # never printed # 不会被 print
 
hello
world

  在 Python 2.0 以后, 你可以使用 atexit 模块来注册多个退出处理函数.

 atexit 模块允许你注册一个或多个终止函数(暂且这么叫), 这些函数将在解释器终止前被自动调用.

调用 register 函数, 便可以将函数注册为终止函数,你也可以添加更多的参数, 这些将作为 exit 函数的参数传递.

使用 atexit 模块

import  atexit
 
def  exit( * args):
     print  "exit" , args
 
# register two exit handler
atexit.register(exit)
atexit.register(exit, 1 )
atexit.register(exit, "hello" , "world" )
 
exit ( 'hello' , 'world' )
exit ( 1 ,)
exit ()

  

time 模块提供了一些处理日期和一天内时间的函数. 它是建立在 C 运行时库的简单封装.

给定的日期和时间可以被表示为浮点型(从参考时间, 通常是 1970.1.1 到现在经过的秒数. 即 Unix 格式), 或者一个表示时间的 struct (类元组).

使用 time 模块获取当前时间

import  time
 
now =  time.time()
 
print  now, "seconds since" , time.gmtime( 0 )[: 6 ]
print
print  "or in other words:"
print  "- local time:" , time.localtime(now)
print  "- utc:" , time.gmtime(now)
 
937758359.77  seconds since ( 1970 , 1 , 1 , 0 , 0 , 0 )
 
or  in  other words:
-  local time: ( 1999 , 9 , 19 , 18 , 25 , 59 , 6 , 262 , 1 )
-  utc: ( 1999 , 9 , 19 , 16 , 25 , 59 , 6 , 262 , 0 )

  

使用 time 模块格式化时间输出

import  time
 
now =  time.localtime(time.time())
 
print  time.asctime(now)
print  time.strftime( "%y/%m/%d %H:%M" , now)
print  time.strftime( "%a %b %d" , now)
print  time.strftime( "%c" , now)
print  time.strftime( "%I %p" , now)
print  time.strftime( "%Y-%m-%d %H:%M:%S %Z" , now)
 
# do it by hand...
year, month, day, hour, minute, second, weekday, yearday, daylight =  now
print  "%04d-%02d-%02d"  %  (year, month, day)
print  "%02d:%02d:%02d"  %  (hour, minute, second)
print  ( "MON" , "TUE" , "WED" , "THU" , "FRI" , "SAT" , "SUN" )[weekday], yearday
 
Sun Oct  10  21 : 39 : 24  1999
99 / 10 / 10  21 : 39
Sun Oct  10
Sun Oct  10  21 : 39 : 24  1999
09  PM
1999 - 10 - 10  21 : 39 : 24  CEST
1999 - 10 - 10
21 : 39 : 24
SUN 283

  在一些平台上, time 模块包含了 strptime 函数, 它的作用与 strftime 相反. 给定一个字符串和模式, 它返回相应的时间对象

使用 time.strptime 函数解析时间

import  time
 
# make sure we have a strptime function!
# 确认有函数 strptime
try :
     strptime =  time.strptime
except  AttributeError:
     from  strptime import  strptime
 
print  strptime( "31 Nov 00" , "%d %b %y" )
print  strptime( "1 Jan 70 1:30pm" , "%d %b %y %I:%M%p" )

  

strptime 不完全实现

import  re
import  string
 
MONTHS =  [ "Jan" , "Feb" , "Mar" , "Apr" , "May" , "Jun" , "Jul" , "Aug" ,
           "Sep" , "Oct" , "Nov" , "Dec" ]
 
SPEC =  {
     # map formatting code to a regular expression fragment
     "%a" : "(?P<weekday>[a-z]+)" ,
     "%A" : "(?P<weekday>[a-z]+)" ,
     "%b" : "(?P<month>[a-z]+)" ,
     "%B" : "(?P<month>[a-z]+)" ,
     "%C" : "(?P<century>\d\d?)" ,
     "%d" : "(?P<day>\d\d?)" ,
     "%D" : "(?P<month>\d\d?)/(?P<day>\d\d?)/(?P<year>\d\d)" ,
     "%e" : "(?P<day>\d\d?)" ,
     "%h" : "(?P<month>[a-z]+)" ,
     "%H" : "(?P<hour>\d\d?)" ,
     "%I" : "(?P<hour12>\d\d?)" ,
     "%j" : "(?P<yearday>\d\d?\d?)" ,
     "%m" : "(?P<month>\d\d?)" ,
     "%M" : "(?P<minute>\d\d?)" ,
     "%p" : "(?P<ampm12>am|pm)" ,
     "%R" : "(?P<hour>\d\d?):(?P<minute>\d\d?)" ,
     "%S" : "(?P<second>\d\d?)" ,
     "%T" : "(?P<hour>\d\d?):(?P<minute>\d\d?):(?P<second>\d\d?)" ,
     "%U" : "(?P<week>\d\d)" ,
     "%w" : "(?P<weekday>\d)" ,
     "%W" : "(?P<weekday>\d\d)" ,
     "%y" : "(?P<year>\d\d)" ,
     "%Y" : "(?P<year>\d\d\d\d)" ,
     "%%" : "%"
}
 
class  TimeParser:
     def  _ _init_ _( self , format ):
         # convert strptime format string to regular expression
         format  =  string.join(re.split( "(?:\s|%t|%n)+" , format ))
         pattern =  []
         try :
             for  spec in  re.findall( "%\w|%%|." , format ):
                 if  spec[ 0 ] = =  "%" :
                     spec =  SPEC[spec]
                 pattern.append(spec)
         except  KeyError:
             raise  ValueError, "unknown specificer: %s"  %  spec
         self .pattern =  re. compile ( "(?i)"  +  string.join(pattern, ""))
     def  match( self , daytime):
         # match time string
         match =  self .pattern.match(daytime)
         if  not  match:
             raise  ValueError, "format mismatch"
         get =  match.groupdict().get
         tm =  [ 0 ] *  9
         # extract date elements
         y =  get( "year" )
         if  y:
             y =  int (y)
             if  y < 68 :
                 y =  2000  +  y
             elif  y < 100 :
                 y =  1900  +  y
             tm[ 0 ] =  y
         m =  get( "month" )
         if  m:
             if  m in  MONTHS:
                 m =  MONTHS.index(m) +  1
             tm[ 1 ] =  int (m)
         d =  get( "day" )
         if  d: tm[ 2 ] =  int (d)
         # extract time elements
         h =  get( "hour" )
         if  h:
             tm[ 3 ] =  int (h)
         else :
             h =  get( "hour12" )
             if  h:
                 h =  int (h)
                 if  string.lower(get( "ampm12" , " ")) == " pm":
                     h =  h +  12
                 tm[ 3 ] =  h
         m =  get( "minute" )
         if  m: tm[ 4 ] =  int (m)
         s =  get( "second" )
         if  s: tm[ 5 ] =  int (s)
         # ignore weekday/yearday for now
         return  tuple (tm)
 
def  strptime(string, format = "%a %b %d %H:%M:%S %Y" ):
     return  TimeParser( format ).match(string)
 
if  _ _name_ _ = =  "_ _main_ _" :
     # try it out
     import  time
     print  strptime( "2000-12-20 01:02:03" , "%Y-%m-%d %H:%M:%S" )
     print  strptime(time.ctime(time.time()))
 
( 2000 , 12 , 20 , 1 , 2 , 3 , 0 , 0 , 0 )
( 2000 , 11 , 15 , 12 , 30 , 45 , 0 , 0 , 0 )

  

使用 time 模块将本地时间元组转换为时间值(整数)

import  time
 
t0 =  time.time()
tm =  time.localtime(t0)
 
print  tm
 
print  t0
print  time.mktime(tm)
 
( 1999 , 9 , 9 , 0 , 11 , 8 , 3 , 252 , 1 )
936828668.16
936828668.0

  

将 UTC 时间元组转换为时间值(整数)

import  time
 
def  _d(y, m, d, days = ( 0 , 31 , 59 , 90 , 120 , 151 , 181 , 212 , 243 , 273 , 304 , 334 , 365 )):
     # map a date to the number of days from a reference point
     return  (((y -  1901 ) * 1461 ) / 4  +  days[m - 1 ] +  d +
         ((m > 2  and  not  y %  4  and  (y %  100  or  not  y %  400 )) and  1 ))
 
def  timegm(tm, epoch = _d( 1970 , 1 , 1 )):
     year, month, day, h, m, s =  tm[: 6 ]
     assert  year > =  1970
     assert  1  < =  month < =  12
     return  (_d(year, month, day) -  epoch) * 86400  +  h * 3600  +  m * 60  +  s
 
t0 =  time.time()
tm =  time.gmtime(t0)
 
print  tm
 
print  t0
print  timegm(tm)
 
( 1999 , 9 , 8 , 22 , 12 , 12 , 2 , 251 , 0 )
936828732.48
936828732

  

使用 time 模块评价算法

import  time
 
def  procedure():
     time.sleep( 2.5 )
 
# measure process time
t0 =  time.clock()
procedure()
print  time.clock() -  t0, "seconds process time"
 
# measure wall time
t0 =  time.time()
procedure()
print  time.time() -  t0, "seconds wall time"
 
0.0  seconds process time
2.50903499126  seconds wall time

  

使用 types 模块

import  types
 
def  check( object ):
     print  object ,
 
     if  type ( object ) is  types.IntType:
         print  "INTEGER" ,
     if  type ( object ) is  types.FloatType:
         print  "FLOAT" ,
     if  type ( object ) is  types.StringType:
         print  "STRING" ,
     if  type ( object ) is  types.ClassType:
         print  "CLASS" ,
     if  type ( object ) is  types.InstanceType:
         print  "INSTANCE" ,
     print
 
check( 0 )
check( 0.0 )
check( "0" )
 
class  A:
     pass
 
class  B:
     pass
 
check(A)
check(B)
 
a =  A()
b =  B()
 
check(a)
check(b)
 
0  INTEGER
0.0  FLOAT
0  STRING
A CLASS
B CLASS
<A instance at 796960 > INSTANCE
<B instance at 796990 > INSTANCE

  

使用 gc 模块收集循环引用垃圾

import  gc
 
# create a simple object that links to itself
class  Node:
 
     def  _ _init_ _( self , name):
         self .name =  name
         self .parent =  None
         self .children =  []
 
     def  addchild( self , node):
         node.parent =  self
         self .children.append(node)
 
     def  _ _repr_ _( self ):
         return  "<Node %s at %x>"  %  ( repr ( self .name), id ( self ))
 
# set up a self-referencing structure
root =  Node( "monty" )
 
root.addchild(Node( "eric" ))
root.addchild(Node( "john" ))
root.addchild(Node( "michael" ))
 
# remove our only reference
del  root
 
print  gc.collect(), "unreachable objects"
print  gc.collect(), "unreachable objects"
 
12  unreachable objects
0  unreachable objects

  


==============================================================================
本文转自被遗忘的博客园博客,原文链接:http://www.cnblogs.com/rollenholt/archive/2011/11/27/2264909.html,如需转载请自行联系原作者
相关文章
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
709 2
|
存储 Java 数据处理
(numpy)Python做数据处理必备框架!(一):认识numpy;从概念层面开始学习ndarray数组:形状、数组转置、数值范围、矩阵...
Numpy是什么? numpy是Python中科学计算的基础包。 它是一个Python库,提供多维数组对象、各种派生对象(例如掩码数组和矩阵)以及用于对数组进行快速操作的各种方法,包括数学、逻辑、形状操作、排序、选择、I/0 、离散傅里叶变换、基本线性代数、基本统计运算、随机模拟等等。 Numpy能做什么? numpy的部分功能如下: ndarray,一个具有矢量算术运算和复杂广播能力的快速且节省空间的多维数组 用于对整组数据进行快速运算的标准数学函数(无需编写循环)。 用于读写磁盘数据的工具以及用于操作内存映射文件的工具。 线性代数、随机数生成以及傅里叶变换功能。 用于集成由C、C++
897 1
|
算法 Java Docker
(Python基础)新时代语言!一起学习Python吧!(三):IF条件判断和match匹配;Python中的循环:for...in、while循环;循环操作关键字;Python函数使用方法
IF 条件判断 使用if语句,对条件进行判断 true则执行代码块缩进语句 false则不执行代码块缩进语句,如果有else 或 elif 则进入相应的规则中执行
1875 1
|
存储 人工智能 测试技术
如何使用LangChain的Python库结合DeepSeek进行多轮次对话?
本文介绍如何使用LangChain结合DeepSeek实现多轮对话,测开人员可借此自动生成测试用例,提升自动化测试效率。
2442 125
如何使用LangChain的Python库结合DeepSeek进行多轮次对话?
|
监控 数据可视化 数据挖掘
Python Rich库使用指南:打造更美观的命令行应用
Rich库是Python的终端美化利器,支持彩色文本、智能表格、动态进度条和语法高亮,大幅提升命令行应用的可视化效果与用户体验。
1190 0
|
传感器 运维 前端开发
Python离群值检测实战:使用distfit库实现基于分布拟合的异常检测
本文解析异常(anomaly)与新颖性(novelty)检测的本质差异,结合distfit库演示基于概率密度拟合的单变量无监督异常检测方法,涵盖全局、上下文与集体离群值识别,助力构建高可解释性模型。
835 10
Python离群值检测实战:使用distfit库实现基于分布拟合的异常检测
|
数据可视化 关系型数据库 MySQL
【可视化大屏】全流程讲解用python的pyecharts库实现拖拽可视化大屏的背后原理,简单粗暴!
本文详解基于Python的电影TOP250数据可视化大屏开发全流程,涵盖爬虫、数据存储、分析及可视化。使用requests+BeautifulSoup爬取数据,pandas存入MySQL,pyecharts实现柱状图、饼图、词云图、散点图等多种图表,并通过Page组件拖拽布局组合成大屏,支持多种主题切换,附完整源码与视频讲解。
1152 4
【可视化大屏】全流程讲解用python的pyecharts库实现拖拽可视化大屏的背后原理,简单粗暴!
|
存储 Java 索引
(Python基础)新时代语言!一起学习Python吧!(二):字符编码由来;Python字符串、字符串格式化;list集合和tuple元组区别
字符编码 我们要清楚,计算机最开始的表达都是由二进制而来 我们要想通过二进制来表示我们熟知的字符看看以下的变化 例如: 1 的二进制编码为 0000 0001 我们通过A这个字符,让其在计算机内部存储(现如今,A 字符在地址通常表示为65) 现在拿A举例: 在计算机内部 A字符,它本身表示为 65这个数,在计算机底层会转为二进制码 也意味着A字符在底层表示为 1000001 通过这样的字符表示进行转换,逐步发展为拥有127个字符的编码存储到计算机中,这个编码表也被称为ASCII编码。 但随时代变迁,ASCII编码逐渐暴露短板,全球有上百种语言,光是ASCII编码并不能够满足需求
520 4
|
运维 Linux 开发者
Linux系统中使用Python的ping3库进行网络连通性测试
以上步骤展示了如何利用 Python 的 `ping3` 库来检测网络连通性,并且提供了基本错误处理方法以确保程序能够优雅地处理各种意外情形。通过简洁明快、易读易懂、实操性强等特点使得该方法非常适合开发者或系统管理员快速集成至自动化工具链之内进行日常运维任务之需求满足。
861 18

推荐镜像

更多