首页 > 代码库 > python常用功能总结

python常用功能总结

经常写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请求
import urllib
import urllib2

  try:

        post_map = {}

        tags_map = {}

        sql_map = {}

        sql_map["host"] = "10.218.145.123"

        sql_map["user"] = "root"

        sql_map["passwd"] = "123456"

        sql_map["db"] = "hdploy"

        sql_map["port"] = 3306

        tags_map["product"] = "search.offline.maindump"

        tags_map["sql_connetc"] = sql_map

        post_map["metric"] = "deploy.offline.et2main.maindump"

        post_map["tags"] = tags_map

        new_map = JSONEncoder().encode(post_map)

        url = ‘http://10.97.212.17:9991‘

        post_data = http://www.mamicode.com/urllib.urlencode(post_map)

        req = urllib2.Request(url)

        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())

        response = opener.open(req, new_map)

        result = json.loads(response.read())

        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 = http://www.mamicode.com/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常用功能总结