python学习整理

 

  1. how to know python run in 32bit or 64bit machine
    import ctypes
    print ctypes.sizeof(ctypes.c_voidp)

    It'll be 4 for 32 bit or 8 for 64 bit.

  2. urllib库里面有个urlencode函数,可以把key-value这样的键值对转换成我们想要的格式,返回的是a=1&b=2这样的字符串
  3. download python package 
    https://pypi.org/simple/lxml/

  4. __getattr__(self, name) 你可以定义当用户试图获取一个不存在的属性时的行为。

  5. module1 = __import__('module1')

    如果你仅仅输入”__import__(‘module1’)”而不赋给任何变量,模块是找不到的。

  6. getattr() 函数用于返回一个对象属性值. 例如获取一个类的属性值。
  7.  

    1. 如果某个类定义了 __getattribute__() 方法,在 每次引用属性或方法名称时 Python 都调用它(特殊方法名称除外,因为那样将会导致讨厌的无限循环)。
    2. 如果某个类定义了 __getattr__() 方法,Python 将只在正常的位置查询属性时才会调用它。如果实例 x 定义了属性 color, x.color 将 不会 调用x.__getattr__('color');而只会返回 x.color 已定义好的值。
  8. you can use DNSPython to do a reverse lookup.

    Pip install it

    $ pip install dnspython

    Then do your reverse query:

    >>> from dns import resolver
    >>> from dns import reversename
    >>> addr = reversename.from_address("74.125.227.114")
    >>> resolver.query(addr, "PTR")[0]
    <DNS IN PTR rdata: dfw06s16-in-f18.1e100.net.>
  9. python类里会出现这三个单词,self和cls都可以用别的单词代替,类的方法有三种,

    一是通过def定义的 普通的一般的,需要至少传递一个参数,一般用self,这样的方法必须通过一个类的实例去访问,类似于c++中通过对象去访问;

    二是在def前面加上@classmethod,这种类方法的一个特点就是可以通过类名去调用,但是也必须传递一个参数,一般用cls表示class,表示可以通过类直接调用;

    三是在def前面加上@staticmethod,这种类方法是静态的类方法,类似于c++的静态函数,他的一个特点是参数可以为空,同样支持类名和对象两种调用方式;

  10. from collections import deque //deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈
  11. datetime对象可以用来表示精确的日期和时间
  12. fnmatch.fnmatch(filename, pattern) #Test whether the filename string matches the pattern string
  13. OS模块提供了一种可移植的方法使用操作系统的功能
  14. filter(function,sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)返回:
  15. 之前了解过装饰器函数,装饰器会有一个副作用,会把原函数的名字覆盖掉。
    from functools import wraps 解决这个问题

  16. print time.strftime("%x", time.localtime())
    03/10/18
    time.strftime("%X", time.localtime())
    '03:47:28'
  17. __all__定义了当你使用 from <module> import * 导入某个模块的时候能导出的符号(这里代表变量,函数,类等)。需要注意的是 __all__ 只影响到了 from <module> import * 这种导入方式,对于 from <module> import <member> 导入方式并没有影响,仍然可以从外部导入。
  18. yaml 文件
    urls: 
        - {name: chen,age: 22}  #短横杠加空格,冒号后面紧跟一个空格,将生成类似:urls:[ xxx,yyy] 
        - [1,2,3,4]
    在YAML里面,结构通过缩进来表示,连续的项目通过减号"-"来表示,map结构里面的key/value对用冒号":"来分隔。
       YAML也有用来描述好几行相同结构的数据的缩写语法,数组用'[]'包括起来,hash用'{}'来包括
    import yaml 
    f = open('test.yaml') 
    x = yaml.load(f)

  19. sudo apt-get install python-dev libxml2-dev libxslt1-dev zlib1g-dev, pip install lxml
  20. 获取路径方法:不要通过sys.argv[0]获得当前路径,那是不正确的。sys.argv[0] 是当前执行的Python脚本的文件名,不一定是当前的路径。
  21. THIS_DIR = os.path.dirname(os.path.abspath("__file__")) //获取当前文件路径
  22. CWD ('current working directory')
    os.getcwd() 方法用于返回当前工作目录。
  23. print glob.glob(os.path.abspath('./*.py')) 获取当前目录的所有py文件绝对路径
  24. F(**arg1)
    形参名前加俩个*表示,参数在函数内部将被存放在以形式名为标识符的dictionary中,这时调用函数的方法则需要采用arg1=value1,arg2=value2这样的形式。

     
  25. 回调函数
    def callmethod(cls, mtd_name):    
        method = getattr(cls, mtd_name)
        method()
  26.  How to handle spaces in the argument
       parser = argparse.ArgumentParser(description = 'Demonstration of Argparse.')
        parser.add_argument('-e', '--executable', nargs = '+', help = 'List of executables')
        args = parser.parse_args(sys.argv[1:])
        print args.executable
  27. os.walk这个某块是遍历一个目录常用的模块,它返回一个包含3个元素的元祖:dirpath,dirnames,filenames.
  28. import os; os.system("ls -l") //调用shell 命令
  29. _xxx     不能用'from module import *'导入
    __xxx__ 系统定义名字
    __xxx   类中的私有变量名,
    the goal here is to avoid your method to be overridden by a subclass.

    class Test:
        def __func1(self):
            print "Go"
    
        def method(self):
            self.__func1()
    
    
    class B(Test):
        def __func1(self):
            print "job"
    
    b = B()
    b.method()

    output :Go
  30. 以单下划线开头(_foo)的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用"from xxx import *"而导入;
    1. 以双下划线开头的(__foo)代表类的私有成员;以双下划线开头和结尾的(__foo__)代表python里特殊方法专用的标识,如__init__()代表类的构造函数。
  31. "assert" will be ignored in optimization (i.e. python -O). Please raise an Exception instead.
  32.  if you’re just wrapping or filling one or two text strings, the convenience functions should be good enough; otherwise, you should use an instance of TextWrapper for efficiency
  33. # -*- coding: utf-8 -*-   //设置编辑器,默认保存为 utf-8 格式。允许python脚本中出现中文字符
  34. 类名单词首字母大写,不使用下划线连接单词,也不加入 C、T 等前缀
  35. http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=12014716&id=4326013
  36. json的标准格式:要求必须 只能使用双引号作为键 或者 值的边界符号,不能使用单引号,而且“键”必须使用边界符(双引号)
  37. "{0:<9}".format(id) 格式化输出id的长度不超过9
  38. print list(set(b).difference(set(a))) # b中有而a中没有的
    或set(b) - set(a)
  39. print list(set(a).union(set(b)))  #获取两个list 的并集
    或set(a)|set(b)
  40. set(a)&set(b) 交集
  41. ret = list(set(a) ^ set(b)) #获取两个list 的差集
  42. os.chdir("/path") //改变工作路径
  43. 获取1.txt和2.txt的差值
    with open("/home/shaoxinw/1.txt", 'r') as f1:
    ...     with open("/home/shaoxinw/2.txt", 'r') as f2:
    ...         diff_info = set(f1) - set(f2)
  44. f = e[:] //list e值深度拷贝到list f
  45. ret = []
    for i in a:
        if i not in b:
            ret.append(i)
  46. Template
  47. >>> from string import Template
    >>> s = Template('$who likes $what')
    >>> s.substitute(who='tim', what='kung pao')
    'tim likes kung pao'
  48. 在python中 None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False 
  49. dict.copy() 浅拷贝
  50. help(dict) 
  51. dict.setdefault('a', '1') 如果dict没有设置过值,设置为a: 1
  52. 两个辞典不同的关键字相加>>> a = {"1": "a"}
    >>> b = {"2": "b", "3": "c"}
    >>> c = a.copy()
    >>> c.update(b)
  53. dict.get(key, default=None) //The method get() returns a value for the given key. If key is not available then returns default value None.
  54. diff = set(dictb.keys()) - set(dicta.keys()) //两个辞典的差集
  55. 把字典的key转换成列表,使用dict.keys()就可以了
  56. my_dict.keys()[0]     -> key of "first" element
    my_dict.values()[0]   -> value of "first" element
    my_dict.items()[0]    -> (key, value) tuple of "first" element
  57. __call__可以让对象直接像函数一样使用,类似于重载圆括号
  58.  
    回调函数:直接把函数名作为参数传给调用函数
  59. pass //空语句
  60. import subprocess
  61. subprocess.Popen(["mount", "nfs:/point", mount_point])  挂载NFS挂载点
  62. subprocess.Popen(["umount", mount_point])
  63. mkdir //only creates a single sub-directory,
  64. makedirs // creates all the intermediate directories if they don't exist (just like mkdir -p in bash)
  65. os.remove() will remove a file.

    os.rmdir() will remove an empty directory.

    shutil.rmtree() will delete a directory and all its contents.

  66. print self.__doc__  //打印class 下面的描述信息
  67. 如果对应参数没有出现,则是默认store_true/store_false的相反值,如果对应的参数出现,就是存储在里面的值。所以一般情况下action用store_true就对了,参数不存在就返回false,参数存在就返回true。
  68. 设置 add_option 方法中的 metavar 参数,有助于提醒用户,该命令行参数所期待的参数,如 metavar=“mode”:
  69. print "Let's talk about %s." % my_name //print 打印参数值
  70. str_split=str.split('.',1) //按str字符.分割1次
  71. re.findall('\d+', str1) //查找str1中的数字
  72.  "".join(s.split()) #去掉s字符串中的空格
  73. b,c=a.split("-", 1) //b,c分别为分隔前后的值
  74. sys.path.insert(0,'/usr/src')    //把搜索路径放到第一位
  75. sys.path.append('/usr/src/CamProject') //把搜索路径放到最后一位
  76. 如果我们需要导入的模块是放在文件夹里面,那么,文件夹里面必须要添加__init__.py文件,以使得python能够找到模块的位置。__init__.py可以为空,只要它存在,就表明此目录应被作为一个package处理。
  77. argparse参数意义:type(指定存储类型)和dest(指定存储变量)
  78. base64 – Encode binary data into ASCII characters
  79. >>> import commands
    >>> commands.getstatusoutput('ls /bin/ls')
    (0, '/bin/ls') //获取命令执行返回值
  80. os.path.isfile(path) //This function returns true if the given path is an existing, regular file.
  81. 以单下划线开头(_foo)的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用"from xxx import *"而导入;
  82. 以双下划线开头的(__foo)代表类的私有成员;以双下划线开头和结尾的(__foo__)代表python里特殊方法专用的标识,如__init__()代表类的构造函数。
  83. python -mrequests.certs 
  84. os.rename("/tmp/1", "/tmp/2")
  85. 当你导入一个模块,Python解析器对模块位置的搜索顺序是:

    • 当前目录
    • 如果不在当前目录,Python 则搜索在 shell 变量 PYTHONPATH 下的每个目录。
    • 如果都找不到,Python会察看默认路径。UNIX下,默认路径一般为/usr/local/lib/python/。

    模块搜索路径存储在system模块的sys.path变量中。变量里包含当前目录,PYTHONPATH和由安装过程决定的默认目录。

  86.  using airspeed to generate txt    

  87.  loader = airspeed.CachingFileLoader("clients/gentxt")

  88.  install_template = loader.load_template("install.template")

  89.  install_template_txt = install_template.merge(self.install_template_dict, loader=loader)

  90. sudo pip install requests --upgrade #升级requests版本

  91. 建立自己的virtualenv

    apt-get -y install python-pip //安装pip
    apt-get install pip --upgrade
    pip install --upgrade virtualenv
    mkdir /local/pythonenv
    cd /local/pythonenv
    virtualenv --no-site-packages your_env
    source activate #激活virtualenv
    deactivate #退出virtualenv

  92. pip freeze #查看当前安装包版本
    pip show show  #查询requests版本

  93.   with open(toDo_file, 'a+') as f:
             start_info = f.read(12) //读12个字符
             ut_info = f.readline() //读1行
             start_info = f.read() //读整个文件

  94. import linecache; cf_info = linecache.getline(self.test_conf, 1) //指定读文件的第一行

  95. import ast; cf_obj = ast.literal_eval(cf_info) //把字符串转换成字典

  96. 使用python自带日志
     import logging
     log = logging.getLogger()
     logging.basicConfig(level=logging.INFO)
     logging.debug("good luck")
     logging.getLevelName(log.getEffectiveLevel()) 获取日志的级别,这里输出应该是INFO

    只显示ciritical log, 其它的日志都不显示

    log.setLevel(logging.CRITICAL)
    logging.critical('This is a critical error message')

    设置urllib3日志不显示
    logging.getLogger("urllib3").setLevel(logging.WARNING)
     

     

  97.  

    Like in any other programming languages you can open a file in r+,w+ anda+ modes.

    • r+ opens for reading and writing (no truncating, file pointer at the beginning)
    • w+ opens for writing (and thus truncates the file) and reading
    • a+ opens for appending (writing without truncating, only at the end of the file, and the file pointer is at the end of the file) and reading
     

     

 

 

wget  https://pypi.python.org/packages/source/p/pykerberos/pykerberos-1.1.7-1.tar.gz

tar zxf pykerberos-1.1.7-1.tar.gz
cd pykerberos-1.1.7
# edit setup.py like vi setup.py
python setup.py build

python setup.py install

 

 

To record list of installed files, you can use:

python setup.py install --record files.txt.py install --record files.txt

Once you want to uninstall you can use xargs to do the removal:

cat files.txt | xargs rm -rf.txt | xargs rm -rf

python -V  or python --version//查看python版本

 

install pycharm

 

sudo add-apt-repository ppa:mystic-mirage/pycharm
sudo apt-get update

 

sudo apt-get install pycharm-community

 

>>> import sys
>>> print sys.path

 


session = requests.Session()session.post('http://xlzd.me/login', 

data={'user':'xlzd','pass':'mypassword'})# 登录成功则可以发布文章了

session.put('http://xlzd.me/new',data={'title':'title of article', 'data':'content'})

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值