2018年4月24日笔记

  • 内置模块:commands (python2中使用)

commands.getoutput("cmd") --> 获取shell命令的返回结果,是string类型

commands.getstatusoutput("cmd") --> 返回一个元组(status,output), status代表的shell命令的返回状态(int类型),如果成功的话是0;output是shell的返回的结果(string类型)

  • 内置模块:subprocess (python3中使用,替代python2中的commands)

subprocess.getoutput("cmd") --> 获取shell命令的返回结果,是string类型

subprocess.getstatusoutput("cmd") --> 返回一个元组(status,output), status代表的shell命令的返回状态(int类型),如果成功的话是0;output是shell的返回的结果(string类型)

subprocess.call(list, shell=False) --> 执行命令并返回执行结果,其中shell参数为False时,命令需要通过list形式传入

subprocess.call(str, shell=True) --> 执行命令并返回执行结果,其中shell参数为True时,命令可通过str形式直接传入

subprocess.check_call(str, shell=True) --> 用法与上面两个方法类似,区别是,若返回值为0,直接返回输出结果;若返回值不为0,直接抛出异常

  • 内置模块:logging  (日志记录模块)

日志一般分成如下5个level (从低到高),默认显示warning及更高level的日志

  debug  <  info  <  warning  <  error  <  critical

使用logging模块来生成日志文件,一般用法如下所示:

生成的日志文件 test.log 如下:

  • 内置模块:os 

os.name  判断系统类型,nt表示Windows,posix表示Unix

os.system("cmd")  纯粹执行系统命令,返回命令执行状态码(若成功则返回0,否则返回一个非0的int)

os.popen("cmd")  也是去执行一个命令,不过相比system(cmd),os.popen(command [, mode='r' [, bufsize]]),参数更多,而且是开启一个管道去执行。

  参数说明:

    cmd - 执行的命令

    mode - 模式权限可以是'r'(默认)或'w'

    buffering - 0意味着无缓冲;1意味着行缓冲;其它正值表示使用参数大小的缓冲(大概值,以字节为单位)。负的bufsize意味着使用系统的默认值,一般来说,对于tty设备,它是行缓冲;对于其它文件,它是全缓冲。如果没有改参数,使用系统的默认值。

os模块的其他常见用法如下:

  • 内置模块:sys

sys.argv  实现从程序外部向程序传递参数

  • 内置模块:random

random.random()  返回 [0, 1) 范围内的随机数

random.randint(m, n)  返回 [m, n] 内的随机整数,包含m和n   <---> 区别于range(m, n)

random.randrange(m, n, step)  返回值不可能为n

random.sample(tuple, n)  从tuple中随机抽取n个元素,生成一个新的tuple

例题:掷骰子100次,统计各点数出现次数 (要求:不能使用if语句,且尽量缩短代码量)

  • 内置模块:string

string模块常见用法如下:

 例题:生成一个6位的随机验证码

print(random.sample(string.ascii_letters + string.digits , 6))

 

猜你喜欢

转载自www.cnblogs.com/karl-python/p/8948595.html