标签存档: python

Python time模块

下面是几个python中常用的利用time模块对时间处理:

#!/usr/bin/python
# -*- coding=utf-8 -*-
# time

import time

# 当前时间戳
nowtime = time.time()
print nowtime

# 当前时间
print time.strftime("%Y-%m-%d %X", time.localtime())

# 将一个时间戳转换为当前时区的struct_time
nowtime = time.localtime(time.time())

# 取当前周的周一和下周一
start_tm_mday = nowtime.tm_mday - nowtime.tm_wday
starttime = str(nowtime.tm_year) + "-" + str(nowtime.tm_mon) + "-" + str(start_tm_mday) + " 00:00:00"
print starttime
end_tm_mday = start_tm_mday + 7
endtime = str(nowtime.tm_year) + "-" + str(nowtime.tm_mon) + "-" + str(end_tm_mday) + " 00:00:00"
print endtime

# 把一个格式化时间字符串转化为struct_time。和strftime()逆操作
starttime = time.strptime(starttime, "%Y-%m-%d %X")
print starttime
endtime = time.strptime(endtime, "%Y-%m-%d %X")
print endtime

# 将一个struct_time转化成时间戳
print time.mktime(starttime)
print time.mktime(endtime)

#得到当前时间前一天的时间Date型
import datetime
dt_obj = time.localtime()
datetime_obj = datetime.datetime(*dt_obj[:3])  #在参数名之前使用一个星号,就是让函数接受任意多的位置参数
yesterday = datetime_obj + datetime.timedelta(days=-1)
print yesterday

Python Mako 模板引擎

安装:

$ wget http://www.makotemplates.org/download.html
$ tar -zxvf Mako-0.7.0.tar.gz
$ cd Mako-0.7.0/
$ python setup.py build
$ python setup.py install

使用:
1.表达式替换:

from mak.template import Template
print Template("hello ${data}!").render(data="world")

2.基于文件的模板、数组循环
脚本文件

from mak.template import Template
name = 'super'
testlist = [(123,'abc',1),(456,'def',1)]
mytemplate = Template(filename='home/python/tpl/mytmpl.tpl')
# 如果模板编码是utf-8
# mytemplate = Template(filename='home/python/tpl/mytmpl.tpl',default_filters=['decode.utf8'],input_encoding='utf-8',output_encoding='utf-8')
print mytemplate.render(name=name,testlist=testlist)

模板文件

% if name != ''
Hi ${name},
% endif
<table>
% for item in testlist:
    <tr>
        <td>id:${item[0]}</td>
        <td>id:${item[0]}</td>
        <td>id:${item[0]}</td>
    </tr>
% endfor
</table>

Python Mysql 操作

首先需要安装Python的MySQLdb库,下载链接:http://sourceforge.net/projects/mysql-python

#!/usr/bin/env python
# -*- coding=utf-8 -*-

import MySQLdb  #需要安装python的Mysql扩展

conn = MySQLdb.connect(user='root', passwd='123456', host='127.0.0.1', port=3306)
conn.select_db('shop')
cursor = conn.cursor(MySQLdb.cursors.DictCursor)  #MySQLdb.cursors.DictCursor用数据库字段名为key
cursor.execute("SET NAMES 'utf8'")

cursor.execute('SELECT * FROM cate')
res = cursor.fetchall()  #返回所有结果集
for row in res:
    print "%s" % (unicode(row["name"], 'utf-8'))

cursor.execute('SELECT * FROM cate LIMIT 1')
res = cursor.fetchone()  #返回一条记录
print "%s" % (unicode(res["ca_Name"], 'utf-8'))

cursor.execute('SELECT * FROM cate')
res = cursor.fetchmany(5)  #接收5条返回结果行.如果5的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
for row in res:
    print "%s" % (unicode(row["ca_Name"], 'utf-8'))

cursor.execute("UPDATE cate SET flag = '0' WHERE id = '1' LIMIT 1")
#如果Mysql表的存储引擎是InnoDB的话,需要执行以下操作才能操作成功
conn.commit()

cursor.close()

Python SocketServer

这几天在搞2台服务器同步文件的问题,由于公司文件传送限制用户权限,导致写好的传送脚本scp.exp用apache用户无法执行脚本同步。所以另外想办法,参照相关文档用python写了一个SocketServer,在后台跑然后接受php的命令去执行脚本($ nohup python server.py > nohup.out &或者$ python server.py &,然后#exit,再ssh登陆,查看后台进程#ps -ef | grep py,能查到server.py的进程就OK了。)
server端:server.py

import os
import SocketServer
class MyHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        while 1:
            dataReceived = self.request.recv(1024)
            if not dataReceived: break
            #self.request.send(dataReceived)
            #print dataReceived
            if dataReceived == 'cmd=1':
                os.system('/home/cgi/scp.exp')
                self.request.send(dataReceived+'&result=1\n')
            else:
                self.request.send(dataReceived+'&result=0\n')
myServer = SocketServer.ThreadingTCPServer(('localhost',6000), MyHandler)
myServer.serve_forever()

client端:client.py

import socket
remote_host = '127.0.0.1'
remote_port = 6000
send_buf = raw_input()
#send_buf = open('test.txt', 'rb').read()
#send_buf = send_buf.replace('\x0D\x0A', '')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((remote_host, remote_port))
sock.send(send_buf)
response_data = sock.recv(1024)
print response_data
sock.close()

或者用PHP写client端:client.php

$fp = fsockopen("127.0.0.1", 6000, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";exit;
} else {
    $out = "cmd=1";
    fwrite($fp, $out);
    while (!feof($fp)) {
        $str .= fgets($fp, 4096);
    if(strpos($str, "\n") !== FALSE){
        if(strpos($str, "&result=1") != FALSE){
            break;
        }else{
    }
    }
}
fclose($fp);
第 1 页,共 1 页1