經常寫python,但很多小的點都記不住,每用必查,總結下來,下次查自己的吧。
1.時間獲取:
import time
print time.strftime("%y-%m-%d %h:%m:%s", time.localtime(time.time()))
結果:2016-10-10 22:25:26
2.http傳送post請求
for key in result://根據返回的結果進行解析
if "version" in key.keys():
versions = key["version"]
version = versions.split("|")
return version[0][-9:]
except exception, e:
print e
return 1
3.獲取當前檔案所在目錄:
work_home = os.path.realpath(sys.path[0])
4.在python中獲取執行命令的輸出和執行結果:
import commands
(status, output) = commands.getstatusoutput(cmd)
弊端:output只有在cmd命令執行完才能輸出
另一種方式:
import os
ret=os.system(cmd)
這種方式可以立即輸出cmd的執行輸出,但這個輸出會輸出到終端,無法獲取,ret為名利執行的返回值
5.python中訪問mysql:
conn = mysqldb.connect(host= port=3336, user=, passwd=)
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
conn.close()
print 'execute sql[%r] successed!'%sql
return cursor.fetchall() 返回值為tuple,如果只有一條記錄,會返回形如(("",""),)
6.zookeeper操作:
class :
def __init__(self,host):
self.host = host
self.connected = false
self.handle = -1
self.callback_flag = false
self.cv = threading.condition()
self.connected = false
def connection_watcher(handle, type, state, path):
self.cv.acquire()
self.connected = true
self.cv.notify()
self.cv.release()
self.cv.acquire()
self.handle = zookeeper.init(self.host, connection_watcher)
self.cv.wait(15.0)
self.cv.release()
if not self.connected:
raise exception("couldn't connect to host -", self.host)
def __del__(self):
if self.connected:
zookeeper.close(self.handle)
def getzkvalue(zk_host, path)://獲取zk路徑對應的value
zku = if(zookeeper.exists(zku.handle,path) !=none):
(data,stat) = zookeeper.get(zku.handle, path, none)
return data
else:
return ""
7.更新json格式的檔案:
def updateconf(conf, key, value): //conf為json格式的檔名,key為要更新的key,value為更新後的值
conf_file = file(conf)
conf_value = json.load(conf_file)
conf_value[key] = value
new_file = open(conf,'w')
new_file.write(json.dumps(conf_value,ensure_ascii=false, indent = 4, separators = (',',':')))
new_file.close()
python 常用功能
sintance和type class foo object pass class bar foo pass obj bar isinstance用於判斷,物件是否是指定類的例項 錯誤的 isinstance用於判斷,物件是否是指定類或其派生類的例項 isinstance不精準 print isin...
Jquery常用功能總結
id css display block function input id online click function 設定不可以使用 id attr disabled disabled 可以使用 id removeattr disabled id1,id2 click function 使用pr...
Tmux常用功能總結
tmux常用功能總結 在 ubuntu 中安裝tmux 在終端輸入如下命令 sudo apt get install tmux tmux 的快捷鍵字首 prefix 為了使自身的快捷鍵和其他軟體的快捷鍵互不干擾,tmux 提供了乙個快捷鍵字首。當想要使用快捷鍵時,需要先按下快捷鍵字首,然後再按下快捷...