-
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.
- urllib库里面有个urlencode函数,可以把key-value这样的键值对转换成我们想要的格式,返回的是a=1&b=2这样的字符串
-
download python package
https://pypi.org/simple/lxml/ -
__getattr__(self, name)
你可以定义当用户试图获取一个不存在的属性时的行为。 -
module1 = __import__('module1')
如果你仅仅输入”__import__(‘module1’)”而不赋给任何变量,模块是找不到的。
- getattr() 函数用于返回一个对象属性值. 例如获取一个类的属性值。
-
- 如果某个类定义了
__getattribute__()
方法,在 每次引用属性或方法名称时 Python 都调用它(特殊方法名称除外,因为那样将会导致讨厌的无限循环)。 - 如果某个类定义了
__getattr__()
方法,Python 将只在正常的位置查询属性时才会调用它。如果实例 x 定义了属性 color,x.color
将 不会 调用x.__getattr__('color')
;而只会返回 x.color 已定义好的值。
- 如果某个类定义了
- 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.>
-
python类里会出现这三个单词,self和cls都可以用别的单词代替,类的方法有三种,
一是通过def定义的 普通的一般的,需要至少传递一个参数,一般用self,这样的方法必须通过一个类的实例去访问,类似于c++中通过对象去访问;
二是在def前面加上@classmethod,这种类方法的一个特点就是可以通过类名去调用,但是也必须传递一个参数,一般用cls表示class,表示可以通过类直接调用;
三是在def前面加上@staticmethod,这种类方法是静态的类方法,类似于c++的静态函数,他的一个特点是参数可以为空,同样支持类名和对象两种调用方式;
-
from collections import deque //deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈
- datetime对象可以用来表示精确的日期和时间
fnmatch.
fnmatch
(filename, pattern) #Test whether the filename string matches the pattern string- OS模块提供了一种可移植的方法使用操作系统的功能
- filter(function,sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)返回:
-
之前了解过装饰器函数,装饰器会有一个副作用,会把原函数的名字覆盖掉。
from functools import wraps 解决这个问题 - print time.strftime("%x", time.localtime())
03/10/18
time.strftime("%X", time.localtime())
'03:47:28' - __all__定义了当你使用
from <module> import *
导入某个模块的时候能导出的符号(这里代表变量,函数,类等)。需要注意的是__all__
只影响到了from <module> import *
这种导入方式,对于from <module> import <member>
导入方式并没有影响,仍然可以从外部导入。 -
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) - sudo apt-get install python-dev libxml2-dev libxslt1-dev zlib1g-dev, pip install lxml
- 获取路径方法:不要通过sys.argv[0]获得当前路径,那是不正确的。sys.argv[0] 是当前执行的Python脚本的文件名,不一定是当前的路径。
- THIS_DIR = os.path.dirname(os.path.abspath("__file__")) //获取当前文件路径
- CWD ('current working directory')
os.getcwd() 方法用于返回当前工作目录。 - print glob.glob(os.path.abspath('./*.py')) 获取当前目录的所有py文件绝对路径
- F(**arg1)
形参名前加俩个*表示,参数在函数内部将被存放在以形式名为标识符的dictionary中,这时调用函数的方法则需要采用arg1=value1,arg2=value2这样的形式。
-
回调函数 def callmethod(cls, mtd_name): method = getattr(cls, mtd_name) method()
-
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
- os.walk这个某块是遍历一个目录常用的模块,它返回一个包含3个元素的元祖:dirpath,dirnames,filenames.
- import os; os.system("ls -l") //调用shell 命令
- _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 - 以单下划线开头(_foo)的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用"from xxx import *"而导入;
- 以双下划线开头的(__foo)代表类的私有成员;以双下划线开头和结尾的(__foo__)代表python里特殊方法专用的标识,如__init__()代表类的构造函数。
- "assert" will be ignored in optimization (i.e. python -O). Please raise an Exception instead.
- 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 - # -*- coding: utf-8 -*- //设置编辑器,默认保存为 utf-8 格式。允许python脚本中出现中文字符
- 类名单词首字母大写,不使用下划线连接单词,也不加入 C、T 等前缀
- http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=12014716&id=4326013
- json的标准格式:要求必须 只能使用双引号作为键 或者 值的边界符号,不能使用单引号,而且“键”必须使用边界符(双引号)
- "{0:<9}".format(id) 格式化输出id的长度不超过9
- print list(set(b).difference(set(a))) # b中有而a中没有的
或set(b) - set(a) - print list(set(a).union(set(b))) #获取两个list 的并集
或set(a)|set(b) - set(a)&set(b) 交集
- ret = list(set(a) ^ set(b)) #获取两个list 的差集
- os.chdir("/path") //改变工作路径
- 获取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) - f = e[:] //list e值深度拷贝到list f
- ret = []
for i in a:
if i not in b:
ret.append(i) - Template
-
>>> from string import Template >>> s = Template('$who likes $what') >>> s.substitute(who='tim', what='kung pao') 'tim likes kung pao'
- 在python中 None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False
- dict.copy() 浅拷贝
- help(dict)
- dict.setdefault('a', '1') 如果dict没有设置过值,设置为a: 1
- 两个辞典不同的关键字相加>>> a = {"1": "a"}
>>> b = {"2": "b", "3": "c"}
>>> c = a.copy()
>>> c.update(b) - 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.
- diff = set(dictb.keys()) - set(dicta.keys()) //两个辞典的差集
- 把字典的key转换成列表,使用dict.keys()就可以了
-
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
-
__call__可以让对象直接像函数一样使用,类似于重载圆括号
-
回调函数:直接把函数名作为参数传给调用函数
- pass //空语句
- import subprocess
- subprocess.Popen(["mount", "nfs:/point", mount_point]) 挂载NFS挂载点
- subprocess.Popen(["umount", mount_point])
- mkdir //only creates a single sub-directory,
- makedirs // creates all the intermediate directories if they don't exist (just like
mkdir -p
in bash) -
os.remove()
will remove a file.os.rmdir()
will remove an empty directory.shutil.rmtree()
will delete a directory and all its contents. - print self.__doc__ //打印class 下面的描述信息
- 如果对应参数没有出现,则是默认store_true/store_false的相反值,如果对应的参数出现,就是存储在里面的值。所以一般情况下action用store_true就对了,参数不存在就返回false,参数存在就返回true。
- 设置 add_option 方法中的 metavar 参数,有助于提醒用户,该命令行参数所期待的参数,如 metavar=“mode”:
print "Let's talk about %s." % my_name //print 打印参数值
- str_split=str.split('.',1) //按str字符.分割1次
- re.findall('\d+', str1) //查找str1中的数字
- "".join(s.split()) #去掉s字符串中的空格
b,c=a.split("-", 1) //b,c分别为分隔前后的值
- sys.path.insert(0,'/usr/src') //把搜索路径放到第一位
- sys.path.append('/usr/src/CamProject') //把搜索路径放到最后一位
- 如果我们需要导入的模块是放在文件夹里面,那么,文件夹里面必须要添加__init__.py文件,以使得python能够找到模块的位置。__init__.py可以为空,只要它存在,就表明此目录应被作为一个package处理。
- argparse参数意义:type(指定存储类型)和dest(指定存储变量)
- base64 – Encode binary data into ASCII characters
- >>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls') //获取命令执行返回值 - os.path.isfile(path) //This function returns true if the given path is an existing, regular file.
- 以单下划线开头(_foo)的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用"from xxx import *"而导入;
- 以双下划线开头的(__foo)代表类的私有成员;以双下划线开头和结尾的(__foo__)代表python里特殊方法专用的标识,如__init__()代表类的构造函数。
python -mrequests.certs
- os.rename("/tmp/1", "/tmp/2")
-
当你导入一个模块,Python解析器对模块位置的搜索顺序是:
- 当前目录
- 如果不在当前目录,Python 则搜索在 shell 变量 PYTHONPATH 下的每个目录。
- 如果都找不到,Python会察看默认路径。UNIX下,默认路径一般为/usr/local/lib/python/。
模块搜索路径存储在system模块的sys.path变量中。变量里包含当前目录,PYTHONPATH和由安装过程决定的默认目录。
-
using airspeed to generate txt
-
loader = airspeed.CachingFileLoader("clients/gentxt")
-
install_template = loader.load_template("install.template")
-
install_template_txt = install_template.merge(self.install_template_dict, loader=loader)
-
sudo pip install requests --upgrade #升级requests版本
- 建立自己的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 -
pip freeze #查看当前安装包版本
pip show show #查询requests版本 -
with open(toDo_file, 'a+') as f:
start_info = f.read(12) //读12个字符
ut_info = f.readline() //读1行
start_info = f.read() //读整个文件 -
import linecache; cf_info = linecache.getline(self.test_conf, 1) //指定读文件的第一行
-
import ast; cf_obj = ast.literal_eval(cf_info) //把字符串转换成字典
-
使用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)
-
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 readinga+
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'})