技术标签: 不属于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
阿里云数据风控全新启航2016年8月1日,阿里云云盾下反欺诈服务正式更名为数据风控,新的名称,新的思考,新的征程。随着互联网企业的蓬勃发展,除了老牌的电商,其他各种行业也开始不断互联网化:金融、保险、医疗、O2O等,而业务的兴起,也带来了意想不到的安全问题:大量的垃圾账号、虚假注册,扰乱了平台正常的秩序;时不时的刷库撞库、暴力破解,让平台防不胜防...
尽微薄之力,为你提供点点帮助。一名Java开发多年的老程序猿,喜欢研究代码,有不懂的地方可以咨询。源码、定制化开发、代码讲解、文档撰写、ppt制作都行。技术选型:springboot、mybatis、thymeleaf、layui、maven、mysql 、jdk1.8开发工具:idea、navicat数据库表结构:9张项目主要功能:前端:登录、注册、购物车、下单、首页展示商品、商品详情、个人中心、我的订单后端:首页 首页 商品信息 首页配置 轮播图配...
KiCad 是一种开源电子设计自动化 (EDA) 工具,提供几乎满足任何项目所需的功能。因其高层次的功能且无需许可费,而迅速流行起来。KiCad 是一种全功能电子开发应用程序,用于电子器件设计和制造,可在 Windows、OSX 和 Linux 上自行运行。应用套件包括:原理图获取、印刷电路板布局、Gerber 文件查看器、实体模型查看器等等。Python 脚本支持电路板和封装库自动化。包括大量符号、封装和模型库。应用和文档已翻译成多种语言。Digi-Key 认识到这一趋势,并推出自己的由符号和
STM32F4的DAC是一个12位,电压输出的DAC。可被配置为12位或者8位,也能和DMA联合使用。DAC具有两个独立转换通道。在双DAC模式下,DA抓换可被配置成独立模式或者同步工作模式。两路DAC参考电压以及ADC都是VREF。 【主要特性】 1、两路 2、12bit时数据可被配置成左对齐或右对齐 3、具有同步更新能力 4、噪声产生 5、三角波产生 6、两个通道独立转换或同步转换 ...
方式1,使用加号(+)连接,使用加号连接各个变量或者元素必须是字符串类型()例如:str_name1 = 'To'str_name2 = 'ny'str_name = str_name1 + str_name2print(str_name)方式2:使用.joiin(iterable) 拼接print('-----------method3-----------')# method2 使用join拼...
简单介绍1、emplace_back 解决了 push_back 在需要进行一次拷贝构造的问题,直接在对应的内存进行构造,避免了拷贝构造。2、placement new直接截取最后一段构造的代码,大家可以看到一种语法::new(_p) _T(),这就是 placement new 。在指定的位置进行new。这样就可以在已经申请好的内存上构造。减少了拷贝。static _Require<__and_<__not_<__has_construct<_Tp, _Args...&g
我们经常在浏览网页时会看到遮罩的效果,比如在点击登录后常常会弹出登录框,它的背景就是常用一种半透明的遮罩来禁止登录框这外的操作。现在我们来看看这种半透明遮罩效果应该怎么实现。大致的思路是在body上面放置2个层,一个是半透明的,遮盖整个屏幕;另一个是显示你要显示的内容的。需要注意的是:这两个层的position都要设为absolute;,因为只有设为absolute时, z-index:属性才会生...
【滤波与目标跟踪-公开代码1】面向假设的多假设目标跟踪算法-Python3.X实现前言1. tracker.py1.1 _normalize_log_sum(items)1.2 LocalHypothesis类1.2.1 id()1.2.2target()1.2.3 density()1.2.4 predict(t_now)1.2.5 log_likelihood1.2.6 is_dead1.2.7 is_confirmed1.2.8 new_from_hit(cls, self, z, hit_llhoo
spark读写hbase,先写一下hbase的常用操作方式.hbase建表:create 'hbase_test_table', 'info', {NAME=&gt;'info', SPLITALGO =&gt; 'HexStringSplit', REPLICATION_SCOPE =&gt;0}, SPLITS =&gt; ['S0','S1','S2', 'S3', 'S4'...
最在使用ARCH的时候使用命令:sudo pacman -S Ruby终端报错:error: could not open file /var/lib/pacman/sync/apricity-core.db: Unrecognized archive format这让我折腾好长时间,最后求助大神得出总结,他将pacman.conf里面的官方源注释掉,然后...
导入数据方式:方式一:使用load加载数据加载本地数据LOAD DATA LOCAL INPATH '/opt/datas/sw17-top11-dl-sh.anon.csv'加载hdfs:将文件移动(mv)到了表对应的目录下面LOAD DATA INPATH '/opt/datas/sw17-top11-dl-sh.anon.csv' 方式二:使用PUT直接使用...
a=imread('moon.tif');figure,imshow(a)count=imhist(a);[m,n]=size(a);N=m*n;L=256;count=count/N;%%每一个像素的分布概率countfor i=1:Lif count(i)~=0st=i-1;break;endendstfor i=L:-1:1if count(i)~=0nd=i-1;break;endendn...