Category: Python

  • python encode decode编码

    utf8编码的涵义

    UTF-8 is one of the most commonly used encodings. UTF stands for “Unicode Transformation Format”, and the ‘8’ means that 8-bit numbers are used in the encoding.

    早在1968年,ASCII代码发表了,代表了0到127的字母数字,但仍表示不了其他国家的字母,1980s之后,处理器变为8-bit,变为了0-255,后来为为了16-bit,说明2^16 = 65,536。之后utf-8出现了。

    可以用type或isinstance来判断变量是什么类型

    >>> s = '杨'
    >>> type(s)
    <type 'str'>
    >>> isinstance(s, str)
    True
    >>> isinstance(s, unicode)
    False
    

    如果前面加一个u符号指定用unicode编码

    >>> a = u'杨'
    >>> type(a)
    <type 'unicode'>
    >>> isinstance(a, str)
    False
    >>> isinstance(a, unicode)
    True
    

    python encode unicode编码

    >>> str = "上海"
     >>> print str
     上海
     >>> print data.encode("unicode_escape")
     \\u4ea4\\u6362\\u673a
     >>> print data.encode("raw_unicode_escape")
     \u4ea4\u6362\u673a

    python decode unicode编码

    >>> data = "\u4ea4\u6362\u673a"
    >>> type(data)
    <type 'str'>
     >>> print data.decode('unicode_escape')
     交换机
     当字符串本身有\时,使用
     >>> print data.decode('raw_unicode_escape')
     交换机

    参考文档:

    https://docs.python.org/2/howto/unicode.html

  • python str字符串处理

    几个实际的例子

    string = “abc”

    字符串的长度
    len(string)

    转换为小写
    string.lower()

    转换为大写
    string.upper()

    统计字符串里一个字母a出现的次数

    string.count(‘a’)

    查找子串在一个字符串出现的位置,从0开始算,如果没找到返回-1

    >>> string = ‘i love you’
    >>> string.find(‘love’)
    2

    转换int to str

    >>> a = 2

    >>> type(a)

    <type ‘int’>

    >>> str(a)

    ‘2’

    将字符串中的替换

    .replace(‘:’,’’)

    sum([bin(int(x)).count(‘1’) for x in ‘255.255.255.224’.split(‘.’)])

    strip和split

    strip() #removes from both ends

    lstrip() #removes leading characters (Left-strip)

    rstrip() #removes trailing characters (Right-strip)

    >>> s = ‘ i love you ‘
    >>> print s.strip()
    i love you
    >>> print s.lstrip()
    i love you
    >>> print s.rstrip()
    i love you
    >>> help(” abc”.strip)
    >>> help(“abc”.split)

  • 通过python netsnmp读取cisco交换机信息

    首先使用snmpwalk跑一遍看一下有没有问题

    snmpwalk -v 2c -c public 10.103.33.1

    这里测试用交换机是 WS-C2960G-24TC-L,以下脚本用于读取管理ip,序列号,型号,主机名。思科的交换机snmp oid信息都可通过如下网址查询http://tools.cisco.com/Support/SNMP/do/BrowseOID.do

    首先安装python的snmp依赖包

    yum install net-snmp-python

    获取信息的脚本

    #!/usr/bin/env python
    # by yangyang89
    # using snmp get switch serial, model, manage ip ..
    import netsnmp
    import sys
    import urllib
    import urllib2
    
    # reference python for linux and unix administration page 209
    class Snmp(object):
        """A basic SNMP session"""
        def __init__(self,oid="sysDescr", Version=2):
            self.oid = oid
            self.version = Version
            self.destHost = sys.argv[1]
            self.community = sys.argv[2]
    
        def query(self):
            """Creates SNMP query session"""
            try:
                result = netsnmp.snmpwalk(self.oid, Version = self.version, DestHost = self.destHost, Community = self.community)
            except Exception, err:
                print err
                result = None
            return result
    
    print sys.argv[1] + sys.argv[2]
    if sys.argv[1] and sys.argv[2]:
        s = Snmp()
        #print s.query()
        #s.oid = "2.47.1.1.1.1.11.1001"
        #http://tools.cisco.com/Support/SNMP/do/BrowseOID.do
        s.oid = ".1.3.6.1.2.1.4.20.1.1" # manage ip ipAdEntAddr
        ip = s.query()
        telnet = ip[0]
        print "ip: " + telnet
        
        s.oid = ".1.3.6.1.4.1.9.3.6.3" # serial numbers chassisId
        serial = s.query()
        serial = serial[0]
        print "serial: " + serial
        
        s.oid = ".1.3.6.1.2.1.47.1.1.1.1" # product_model entPhysicalEntry
        product_model = s.query()
        product_model = product_model[1].split(' ')[0]
        print "product_model: " + product_model
        #print s.query()
        
        s.oid = ".1.3.6.1.4.1.9.2.1.3" # hostname hostName
        hostname = s.query()
        hostname = hostname[0]
        print "hostname: " + hostname
    
    
  • python操作json

    首先操作一下python中的字典,首先是空字典eth,在其中添加数据eth0,eth1并对应两个ip

    >>> eth = {}
    >>> eth['eth0'] = '192.168.2.12'
    >>> print eth
    {'eth0': '192.168.2.12'}
    >>> eth['eth1'] = '223.5.5.5'
    >>> print eth
    {'eth1': '223.5.5.5', 'eth0': '192.168.2.12'}

    json与python中dict互相转换,把dict转换成json-使用json.dumps(),将json转换为dict-使用json.loads(),json.loads()返回的是一个dictionary.

    >>> import json
    >>> ethjson = json.dumps(eth)
    >>> type(ethjson)
    <type 'str'>
    >>> print ethjson
    {"eth1": "223.5.5.5", "eth0": "192.168.2.12"}
    >>> ethdict = json.loads(ethjson)
    >>> type(ethdict)
    <type 'dict'>
    >>> print ethdict
    {u'eth1': u'223.5.5.5', u'eth0': u'192.168.2.12'}
    >>> print ethdict['eth0'], ethdict['eth1']
    192.168.2.12 223.5.5.5
    

    判断json里是否有某个key

    if 'text' in post['caption'].keys():      #在keys中是否有text
    if 'text' in post['caption']:    # 在caption下是否有text
    if 'ipv4' in output['ansible_facts']['ansible_int']:  # 在ansible_facts下的ansible_int下是否有ipv4

    有时候需要临时生成一个格式化过的json,可以使用json.tool模块来格式化

    echo '{"json":"obj"}' | python -m json.tool
    
    {
    
        "json": "obj"
    
    }
    
  • python分割字符串split,filter

    现有字符串,需要取出用空格分隔的第一段,操作如下

    >>> product_model = 'WS-C2960G-24TC-L - Fixed Module 0'
    >>> product_model.split(' ')[0]
     'WS-C2960G-24TC-L'

    不带参数的split(),会把所有空格(空格符、制表符、换行符)当作分隔符,如果有这些“空格”,则可这样写

    >>> product_model = 'WS-C2960G-24TC-L - Fixed Module 0'
    >>> product_model.split()[0]
    截取 1 到 最后
    >>> product_model.split()[1:]

    使用filter更多的是过滤,根据

    >>> product_model = 'WS-C2960G-24TC-L - Fixed Module 0'
    >>> filter(None, product_model.split('-'))
     ['WS', 'C2960G', '24TC', 'L ', ' Fixed Module 0']
  • python安装simplejson

    没有安装simplejson时报错

    >>> import simplejson

    Traceback (most recent call last):

      File “<stdin>”, line 1, in <module>

    ImportError: No module named simplejson

    simplejson是ansible一个很重要的依赖,经测试在python 2.4.3及以上版本都可以用python setup.py install 安装成功。

    方法一:

    yum install python-simplejson -y

    方法二:

    wget https://pypi.python.org/packages/source/s/simplejson/simplejson-3.5.2.tar.gz#md5=10ff73aa857b01472a51acb4848fcf8b --no-check-certificate
    tar vxzf simplejson-3.5.2.tar.gz
    cd simplejson-3.5.2
    python setup.py install

    方法三:

    pip install simplejson

    方法四:

    easy_install simplejson