技术标签: 不属于python标准库的是
使用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 "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[a-z]+)",
"%A": "(?P[a-z]+)",
"%b": "(?P[a-z]+)",
"%B": "(?P[a-z]+)",
"%C": "(?P\d\d?)",
"%d": "(?P\d\d?)",
"%D": "(?P\d\d?)/(?P\d\d?)/(?P\d\d)",
"%e": "(?P\d\d?)",
"%h": "(?P[a-z]+)",
"%H": "(?P\d\d?)",
"%I": "(?P\d\d?)",
"%j": "(?P\d\d?\d?)",
"%m": "(?P\d\d?)",
"%M": "(?P\d\d?)",
"%p": "(?Pam|pm)",
"%R": "(?P\d\d?):(?P\d\d?)",
"%S": "(?P\d\d?)",
"%T": "(?P\d\d?):(?P\d\d?):(?P\d\d?)",
"%U": "(?P\d\d)",
"%w": "(?P\d)",
"%W": "(?P\d\d)",
"%y": "(?P\d\d)",
"%Y": "(?P\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",
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
INSTANCE
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 "" % (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
原理说明如下,.h264文件只需要写入sps,pps以及后面的视频裸流(nalu)就可以播放了,播放器可以选择VLC或者迅雷看看播放器,其它的没有测试过。MP4文件是由一个一个box组成的文件,每个box的开头是box的length(4 byte),紧接着是4 byte的box type,如果length是0x01的话,那么在box type后面接着的就是8 byte的box length
原文链接:http://java-lyvee.iteye.com/blog/1328856我用的是myeclipse6.5和Maven3.0.3,与其他版本的有点出入,其实所谓的出入基本算大同小异。 下载Maven3.0.3到本地,解压后配置Maven环境变量,在用户变量中新建变量名:maven_home,变量值:C:\Program Files\apache-maven-3.0
optimizer.param_groups:是长度为2的list,其中的元素是2个字典;optimizer.param_groups[0]:长度为6的字典,包括[‘amsgrad’, ‘params’, ‘lr’, ‘betas’, ‘weight_decay’, ‘eps’]这6个参数optimizer.param_groups[1]:好像是表示优化器的状态的一个字典...
在未来,我们享受良好的服务的同时,也会为别人提供更良好的服务,需要在技能上还是服务质量上的要求会更高更严格。平时要注意提高自己,不要被时代淘汰掉。在程序界流行着一种默认的说法叫“黄金5年”,也就是一个程序员从入职的时候算起,前五年的选择直接影响着整个职业生涯中的职业发展方向和薪资走向,如何走好这5年,彻底从一个刚入行的菜鸟蜕变成可以以不变应万变的职业大牛,这是一个涉及到自身专业知识储备和选择的大难...
今天我们继续来学习每天一个命令,今天我们进入了新的章节内容:安装程序包类命令(INSTALLING PACKAGES),今天学习的是什么命令呢,那就是yum(软件包管理命令)yum --help-t 忽略错误-C 完全从系统缓存运行,不更新缓存-c 配置文件位置-R 最大的命令等待时间-d 设置调试等级(0-10)-e 设置错误等级-q 按键模式操作-v 详细操作模式-y ...
**前情提要:已经建立了odom与base_footprint的关系,并可使用按键检验 **《教程 Re:Zero ROS (六)—— 获取&编写&检验 -> odom坐标系》https://blog.csdn.net/Lovely_him/article/details/107948765教程 Re:Zero ROS (七)——1. slam_gmapping 建图0)本篇大部分内容都是中科院教程中讲到过的,建议先看完中科院最后两课——第九、十课的9个视频,.
卸载已brute_engine为开始的所有rpm包。将未安装的 xxx.rpm 包,释放到本地目录。查询已安装的软件包的相关文件的安装路径。
css样式: table tr:last-child td:first-child { border-bottom-left-radius: 12px; } table tr:last-child td:last-child { border-bottom-right-radius: 12px;...
USE CXHDJGOdeclare @p5 intset @p5=97exec CXHDJ.dbo.SP_Page @SQL=N'SELECT tp.Id,tp.Name,tp.Code ,tp.Price ,tp.CostPrice,tp.Color ,tp.Number,tpc.Name AS catname,tp.CreateTime ,tp.CreateBy FROM CXHDJ.dbo.Test_Product tpINNER JOIN CXHDJ.dbo.Test_Produ.
本节书摘来自异步社区《Adobe InDesign CS6中文版经典教程》一书中的第1课复习,作者【美】Adobe公司,更多章节内容可以访问云栖社区“异步社区”公众号查看。复习Adobe InDesign CS6中文版经典教程复习题有哪些修改文档缩放比例的方式?在InDesign中如何选择工具?有哪三种显示面板的方法?如何创建面板组?复习...
在做前后端开发时,经常会遇到json数据,C++对于json的解析,方法比较多,常用的有jsoncpp、boost json库等等,大家可以灵活选择。Qt也提供了json的解析方法,本篇博客介绍Qt对json数据的解析。Qt解析简单的json数据 先来一个简单的例子,例如下面的json文件update.json{ "version":"1.31", "platform":"macOS", "env":"dev"} Qt的解析方法如下:#include <QtCore/QCo
介绍 (Introduction)Two months ago, ApiBoilerPlate was first released and it’s incredible to see that the template garnered hundreds of installs within a short period of time. I’m very glad that it som...