文章出處

Python第十五天 

 

 

 

 

datetime模塊 time模塊

now = datetime.datetime.now() # 獲取當前時間
delta = datetime.timedelta(minutes=5) # 獲取前5分鐘時間
fiveminago = now – delta # 時間差
now > fiveminago # 時間比較
GMT_FORMAT = '%b %d %H:%M:%S GMT'
now.strftime(GMT_FORMAT) # 格式化時間
now.strftime('%s') //返回時間戳
time.time() //同上
time.ctime()  #相當于datetime.datetime.now()

 


import datetime
import time
def parseLogTime(line):
now = datetime.datetime.now()
month,day,time = line.split()[:3]
hour,minute,second = [int(i) for i in time.split(':')]
logtime = datetime.datetime(now.year,MONTH[month],int(day),hour,minute,second)
return logtime

 



pymssql模塊

 

--------------------------------------------------------------

示例
# coding=utf-8
import pymssql


class MSSQLServer(object):
def __init__(self):
self.server_ip = '.'
self.port = 1433
self.user_name = ''
self.user_psw = ''
self.database_name = ''
self.charset = 'utf8'



def get_connection(self):
conn = pymssql.connect(host=self.server_ip,
user=self.user_name,
password=self.user_psw,
database=self.database_name,
port=self.port,
charset=self.charset)
return conn



def mssql_query(self, sql_script, sql_param=None):
try:
conn = self.get_connection()
cursor = conn.cursor(as_dict=True)
if sql_param != '':
cursor.execute(sql_script, sql_param)
else:
cursor.execute(sql_script)
exec_result = cursor.fetchall()
cursor.close()
conn.close()
return exec_result
except Exception as ex:
cursor.close()
conn.close()
raise Exception(str(ex))



def mssql_exec(self, sql_script, sql_param=None):
try:
conn = self.get_connection()
cursor = conn.cursor(as_dict=True)
if sql_param is not None:
cursor.execute(sql_script, sql_param)
else:
cursor.execute(sql_script)
affect_rows = cursor.rowcount
conn.commit()
cursor.close()
conn.close()
return affect_rows
except Exception as ex:
cursor.close()
conn.rollback()
raise Exception(str(ex))


def mssql_test():
mssql_server = MSSQLServer()
mssql_server.server_ip = "."
mssql_server.port = 1433
mssql_server.charset = "utf8"
mssql_server.user_name = "gaowenjia"
mssql_server.user_psw = "ABC"
mssql_server.database_name = "Test_Sub"
sql_script = u"INSERT INTO [dbo].[TB_Lock]([C2]) VALUES('Test你好N')".encode("utf8")
exec_result = mssql_server.mssql_exec(sql_script=sql_script)
print("影響行數:{0}".format(exec_result))
sql_script = u"SELECT [ID],[C1],[C2] FROM [dbo].[TB_Lock]".encode("utf8")
query_result = mssql_server.mssql_query(sql_script=sql_script)
for row in query_result:
print("*" * 50)
id, c1, c2 = row["ID"], row["C1"], row["C2"]
print("id:{0}".format(id))
if c1 is None:
print("c1:{0}".format(c1))
else:
print("c1:{0}".format(c1.encode("utf8")))
if c2 is None:
print("c2:{0}".format(c2))
else:
print("c2:{0}".format(c2.encode("utf8")))


if __name__ == '__main__':
mssql_test()

--------------------------------------------------------------


Windows上安裝pymssql

Setp1:安裝python 2.7,
Setp2:安裝pymssql-2.0.0b1.win-amd64-py2.7
Setp3:將_mssql.pyd 復制粘貼到C:\Python27\Lib\site-packages 和 C:\Python27\DLLs\
Setp1:運行import pymssql;進行測試

參考鏈接:
http://blog.sina.com.cn/s/blog_83dc494d0101g8u5.html
https://pypi.python.org/pypi/pymssql/2.1.0
http://pymssql.org/en/latest/pymssql_examples.html

 

--------------------------------------------------------------


Linux上安裝pymssql


Linux上安裝pymssql需要的包:
freetds(http://www.filewatcher.com/m/freetds-0.82.tar.gz.1596755-0.html)
setuptools(https://pypi.python.org/pypi/setuptools)
pymssql(https://pypi.python.org/pypi/pymssql/)

 

安裝步驟:
1. 安裝freetds0.82

yum install -y gcc  gcc-c++
yum install -y freetds*
yum install -y python-devel

tar zxvf freetds-0.82.tar.gz
cd freetds-0.82
./configure --prefix=/usr/local/freetds --with-tdsver=8.0 --enable-msdblib --enable-dbmfix --with-gnu-ld --enable-shared --enable-static
make && make install
echo "/usr/local/freetds/lib" >> /etc/ld.so.conf.d/freetds.conf
ldconfig -v


2. 安裝python包 setuptools3.5.1
pip install setuptools==3.5.1

tar zxvf setuptools-3.5.1.tar.gz
cd setuptools-3.5.1
python setup.py install


3. 安裝pymssql2.1.0

下載地址:https://pypi.python.org/pypi/pymssql/2.1.3#downloads
pip install pymssql==2.1.0

tar zxvf pymssql-2.1.0.tar.gz
cd pymssql-2.1.0
python setup.py install


=======================================
未安裝freetds會提示:
setup.py: Not using bundled FreeTDS

如果安裝freetds并配置/etc/ld.so.conf.d/freetds.conf,但未執行ldconfig -v,會報錯:
import pymssql
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: libsybdb.so.5: cannot open shared object file: No such file or directory

 


線程 thread
thread模塊
threading模塊

thread模塊是低級模塊
threading模塊是高級模塊
生產中要用threading模塊而不用thread模塊


GIL:Python無法高效的實現多線程的原因


線程的特點:多功能衣:1631114712
- 線程的生命周期
- 開始
- 運行
- 結束

線程的退出:
- 進程執行完成
- 線程的退出方法
- python系統退出


我們通常把當前進程叫做主線程或者主進程。
函數是通過thread.start_new_thread來調用的,說明它是在線程中運行的。



模塊函數
import thread,threading
start_new_thread(func, args)
func:函數名
args:元組
allocate_lock()
exit()


#!/usr/bin/env python
#encoding:utf8
import thread
import time
def func(name,i):
    for n in xrange(i):
        print name,n
        #time.sleep(1)
thread.start_new_thread(func, ('聲音',3))
thread.start_new_thread(func, ('畫面',3))
time.sleep(1)




LockType對象方法
acquire()
locked()
release()  //釋放鎖,使用前線程必須已獲得鎖定,否則將拋出異常




thread鎖使用
lock = thread.allocate_lock():生成全局鎖對象
lock.acquire():加鎖
線程使用鎖對象
lock.release():線程調度釋放鎖
查看locked()狀態






示例1
#!/usr/bin/env python
#encoding:utf8

import thread
import time

def func(name, i, l):
    for n in xrange(i):
        print name, n
        time.sleep(1)
    l.release()
    
lock = thread.allocate_lock()
lock.acquire()
thread.start_new_thread(func, ('聲音', 3, lock))
thread.start_new_thread(func, ('畫面', 3, lock))

while lock.locked():
    pass
print lock.locked()
print "Exit main process"




示例2
#!/usr/bin/env python

import thread
import time

def world():
    for i in range(5):
        if w_lock.acquire():
            print 'world', time.ctime()
            h_lock.release()

h_lock = thread.allocate_lock()
w_lock = thread.allocate_lock()
thread.start_new_thread(world, ())
w_lock.acquire()
for i in range(5):
    if h_lock.acquire():
        print 'hello',
        w_lock.release()
while h_lock.locked():
    pass



示例3
#!/usr/bin/env python

import thread
import time

def hello():
    for i in xrange(5):
        h_lock.acquire()
        print 'hello',
        w_lock.release()

def world():
    for i in xrange(5):
        w_lock.acquire()
        print 'world', time.ctime()
        h_lock.release()
    lock.release()

lock = thread.allocate_lock()  分配鎖
lock.acquire() 獲得鎖
h_lock = thread.allocate_lock()
w_lock = thread.allocate_lock()
w_lock.acquire()
thread.start_new_thread(hello, ())
thread.start_new_thread(world, ())

while lock.locked():  是否獲得鎖
    pass





threading模塊

threading不需要進程來控制線程,主進程會等待線程執行完畢才退出
threading.Thread:類
成員方法:
    - start()  //啟動線程 非阻塞
    - run()   //可以重寫
    - join()  //阻塞當前線程的執行
    - getName()
    - setName()
    - isDaemon()  //判斷線程是否隨主線程一起結束
    - setDaemon()  //設置線程與主線程一起結束



import time
import threading

def t1(name, x):
    for i in xrange(x):
        print i, name
        time.sleep(1)

th1 = threading.Thread(target=t1, args=('聲音', 3))
th2 = threading.Thread(target=t1, args=('畫面', 3))
target:函數名
args:函數的參數

th1.setDaemon(True)   //隨著主線程的退出而退出,一定要寫在th1.start()前面

th1.start()     //運行一個線程
#th1.run()     //一直運行這個線程,直到運行完才會運行下一個線程
#th1.join()    //等待線程終止
th2.start()



Lock對象
lock = threading.Lock()
lock. acquire()   //獲取鎖
lock.release()     //釋放鎖
lock.locked()     //查看鎖狀態

f






文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 AutoPoster 的頭像
    AutoPoster

    互聯網 - 大數據

    AutoPoster 發表在 痞客邦 留言(0) 人氣()