python

2019.0419

1.  获取shell 命令的结果和状态码,3 种

os.system()  调用系统命令,完成后退出,返回结果是命令执行状态,一般是0

os.popen()   返命令后的结果,多用read 读出来

(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')    返状态和结果 ,多用

 

2. 按行读文件

read        读取整个文件

readline    读取下一行

readlines   读取整个文件到一个迭代器以供我们遍历(读取到一个list中,以供使用,比较方便)、

 

打开文件 open('file','r')

 

3 。re 正则

>>> re.findall("w",a)
['m', 'y', 'n', 'a', 'm', 'e', 'i', 's', 'b', 'r', 'u', 'c', 'e', 'i', 's', 'a', 'w', 'h', 'i', 't', 'f', 'u', 'c', 'k']
>>> re.split("is",a)
['my name ', ' bruce ', ' a whit fuck']
>>> print a
my name is bruce is a whit fuck
>>>

 

4. strip 

os.popen("hostname").readlines()[0].strip(" ")   删除头尾的 空格和换行

>>> str2 = '1a2b12c21'
>>> str2.strip('12') #删除头尾的1和2
'a2b12c'
>>> str2.lstrip('12') #删除开头的1和2
'a2b12c21'
>>> str2.rstrip('12') #删除结尾的1和2
'1a2b12c'

5. os.path.exits

if os.path.exists("/etc/redhat-release"):
return os.popen("cat /etc/redhat-release").readlines()[0].strip(" ")

os.path.dirname(__file__)  执行脚本的目录 

os.path.basename(__file__)    执行脚本的文件名字

 6.urllib  

urllib.urlopen('http://www.runoob.com/python/file-methods.html').getcode()

使用import urllib

参数:

    read(),readline(),readlines(), fileno(), close():这些方法的使用方式与文件对象完全一样;
    info():返回一个httplib.HTTPMessage对象,表示远程服务器返回的头信息;
    getcode():返回Http状态码。如果是http请求,200表示请求成功完成;404表示网址未找到;
    geturl():返回请求的url;

参考:https://blog.csdn.net/dolphin_h/article/details/23618187

http 请求3中模块,urllib  urllib2 httplib

参考:https://www.cnblogs.com/zhming26/p/6230124.html

7 . 数据类型

字符串,数字,列表,字典,数组

列表,可变, 用a[0] 取值, 字典是key 和value 的 组合, 数组时不表的列表

引号引起的赋值时字符串,数字不用引号是数字,加了是字符串

列表  []    字典 {}   数字 ()

8  python -m SimpleHTTPServer 80

用python 起http 服务,监听80 口, 目录为起服务所在的目录

端口 可随便更改,目录也可自定义转换。

9 .random 模块 随机数选择 ,help 方法

import random   help(random)

参考 http://www.cnblogs.com/yd1227/archive/2011/03/18/1988015.html

10 . 列表i和元组操作

count(item) 表示统计列表 / 元组中 item ...

极客时间版权所有: https://time.geekbang.org/column/article/94972

11, python  正则匹配 

re.seatch ,re.sub

匹配字符  d  数字  D 非数字  s  空白  S 非空白  w  word+数字+下划线  W  非    [a-z]  [^a-z]

   $    结尾   ^ 开始 

原文地址:https://www.cnblogs.com/brucewhite/p/10733609.html