python 常用记录

all()

>>> a = [11,22,33]
>>> all(a)
>>> ture
对序列进行判断,如果全为真,则返回Ture
>>> a = [11,22,0]
>>> all(a)
>>> false
一旦有一个为空,返回false

datetime

>>> from datetime import datetime
>>> print datetime.now()
2016-08-18 10:33:21.218000
指定日期和时间
>>> dt = datetime(2015, 4, 19, 12, 20) # 用指定日期时间创建datetime
>>> print(dt)2015-04-19 12:20:00
datetime 转换为timestamp
>>> from datetime import datetime
>>> import time
>>> dt = datetime(2016, 8, 16, 10, 40)
>>> print time.mktime(dt.timetuple())
timestamp的值与时区毫无关系,因为timestamp一旦确定,其UTC时间就确定了,转换到任意时区的时间也是完全确定的,这就是为什么计算机存储的当前时间是以timestamp表示的,
因为全球各地的计算机在任意时刻的timestamp都是完全相同的(假定时间已校准)。
timestamp 转换为datetime
>>> from datetime import datetime
>>> t = 1429417200.0
>>> print(datetime.fromtimestamp(t))
字符串转换为datetime
>>> from datetime import datetime
>>> t = '2016-8-16 10:40:38'
>>> day = datetime.strptime(t,'%Y-%m-%d %H:%M:%S')
>>> print day
>>> 2016-08-16 10:40:38

datetime 转换为str
>>> from datetime import datetime
>>> now = datetime.now()
>>> print(now.strftime('%a, %b %d %H:%M'))
Mon, May 05 16:28

python 跨进程锁的实现-fcntl

首先先介绍fileObject.fileno(); 这个方法
此方法返回整数的底层实现使用请求从操作系统的I / O操作的文件描述符.
#!/usr/bin/python
#coding:utf-8

f = open('lock.txt','a+')
print f.fileno()
print f.name
f.close()
3
lock.txt

fcntl这次应用于对pid file的书写

flock() : flock(f, operation)
  operation : 包括:
    fcntl.LOCK_UN 解锁
    fcntl.LOCK_EX  排他锁
    fcntl.LOCK_SH  共享锁
    fcntl.LOCK_NB  非阻塞锁
LOCK_SH 共享锁:所有进程没有写访问权限,即使是加锁进程也没有。所有进程有读访问权限。
LOCK_EX 排他锁:除加锁进程外其他进程没有对已加锁文件读写访问权限。
LOCK_NB 非阻塞锁:
fcntl.LOCK_EX | fcntl.LOCK_NB这种应用是,当获取到文件有锁的信息,程序直接except
def write_pid()
    f = open(pidfile, "a+")
    try:
        fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        print "Can not write pid into: ", pidfile
        return False
    f.truncate()   #将文件内容清除
    f.write(str(os.getpid()))
    f.flush()
    f.seek(0)
    f.close()
    return True

logging 日志输出

模块提供 filter, logger, hanlder, formatter
可以通过logging.getLogger(name)获取logger对象
handler:将日志记录(log record)发送到合适的目的地(destination),比如文件,socket等。一个logger对象可以通过addHandler方法添加0到多个handler,
每个handler又可以定义不同日志级别,以实现日志分级过滤显示。
filter:提供一种优雅的方式决定一个日志记录是否发送到handler。
        formatter:指定日志记录输出的具体格式。formatter的构造方法需要两个参数:消息的格式字符串和日期字符串,这两个参数都是可选的。


import logging
from logging.handlers import TimedRotatingFileHandler
import datetime
file = "ogent_" + datetime.datetime.now().strftime('%b-%d-%y') + ".log"
path_to_file = 'C:\\Users\\ma\\PycharmProjects\\ma\\modle\\'
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.propagate = False   #这是一个布尔标志,用于指示消息是否传播给父记录器
logFormatter = logging.Formatter('%(asctime)s %(filename)12s:%(lineno)4d %(levelname)-6s %(message)s')  #规定日志格式
logHandler = TimedRotatingFileHandler(path_to_file + file,when='midnight')   #规定时间重新创建log,“midnight”: Roll over at midnight
logHandler.setLevel(logging.DEBUG)
logHandler.setFormatter(logFormatter)
logger.addHandler(logHandler)
keep_fds = [logHandler.stream.fileno()]

TimedRotatingFileHandler(filename [,when [,interval [,backupCount]]])
when 是一个字符串的定义如下:
“S”: Seconds
“M”: Minutes
“H”: Hours
“D”: Days
“W”: Week day (0=Monday)
“midnight”: Roll over at midnight
interval 是指等待多少个单位when的时间后,Logger会自动重建文件,当然,这个文件的创建
取决于filename+suffix,若这个文件跟之前的文件有重名,则会自动覆盖掉以前的文件,所以
有些情况suffix要定义的不能因为when而重复。
backupCount 是保留日志个数。默认的0是不会自动删除掉日志。若设10,则在文件的创建过程中
库会判断是否有超过这个10,若超过,则会从最先创建的开始删除。

format格式化字符串

通过位置
print '{0},{1}:{0}'.format('ma','test')
ma,test:ma
通过关键字
print '{name},{id}'.format(name='ma',id='test')
ma,test
通过对象属性
class Format(object):
   def __init__(self,name,age):
      self.Name = name
      self.Age = age
   def __str__(self):
      return 'The guy is {self.Name} , is {self.Age} years old'.format(self=self)
      
The guy is kzc , is 18 years old

原创文章,作者:心肝坏了,如若转载,请注明出处:http://www.178linux.com/37154

(0)
心肝坏了心肝坏了
上一篇 2016-09-19 13:48
下一篇 2016-09-19 13:48

相关推荐

  • N25-第二周做业

    一.Linux上的文件管理类命令都有哪些,其常用的使用方法和演示        1.目录管理的命令    mkdir rmdir              1)…

    Linux干货 2016-12-11
  • Linux下的网络配置方法(二)

    Linux下配置网络的方法还可以通过修改配置文件和使用nmcli命令来完成:     1. 修改配置文件:         网络接口的配置文件为:/etc/sysconfig/network-scripts/ifcfg-INTERFACE_…

    Linux干货 2015-12-15
  • samba服务部署WordPress

    简介 Samba是一个能让Linux系统应用Microsoft网络通讯协议的软件,而SMB是Server Message Block的缩写,即为服务器消息块 ,SMB主要是作为Microsoft的网络通讯协议,后来Samba将SMB通信协议应用到了Linux系统上,就形成了现在的Samba软件。后来微软又把 SMB 改名为 CIFS(Common Inter…

    Linux干货 2017-04-28
  • 第五周作业

    1、显示/boot/grub/grub.conf中以至少一个空白字符开头的行; [root@centos6 ~]# grep "^[[:space:]]\+" /boot/grub/grub.conf         &…

    Linux干货 2017-01-16
  • Linux第四周总结

    1、复制/etc/skel目录为/home/tuser1, 要求/home/tuser1及其内部文件的属组和其它用户均没有任何访问权限。 2、编辑/etc/group文件,添加组hadoop。 3、手动编辑/etc/passwd文件新增一行,添加用户hadoop, 其基本组ID为hadoop组的id号;其家目录为/home/hadoop。 4、复制/etc/…

    2017-07-24
  • ​源码编译安装LNMP

    源码编译安装LNMP 环境:CentOS6.6 IP: 172.16.10.10/16 GW:172.16.0.2 主机名称: lnmp.test.net 一、常规设置: 网卡: 临时 ifconfig eth0 172.16.10.10/16 up 永久 [root@www ~]# vim /etc/sysconfig/network-scripts/if…

    Linux干货 2016-11-14