python常用内置模块

Subprocess模块

python3.5将使用Subprocess模块跟操作系统进行交互,比如系统命令,他将替换

os.system

os.spawn*

subprocess.run()方法封装的subprocess.Popen()

subprocess.run()方法只在3.5中才有2.7中有一个subprocess.call()方法

>>> subprocess.call([‘df‘,‘-lh‘])

Filesystem     Size   Used  Avail Capacity  iused    ifree %iused  Mounted on

/dev/disk1    465Gi  209Gi  256Gi    45% 54730457 67109157   45%   /

/dev/disk2s1  741Mi  557Mi  184Mi    76%   142675    47036   75%   /Volumes/Parallels Desktop 11

/dev/disk3s2  786Mi  669Mi  117Mi    86%   171353    29853   85%   /Volumes/ParallelsDesktop 11.1.3-32521

0

这里给call方法,传“df -lh”这种多个参数时,用的是传入列表的形式[‘df‘,‘-lh’],python解释器在处理subprocess.call()方法时,将传进来的列表参数经过处理,最终转换成shell中的df -lh,那么如果我就不想传列表,怎么办呢。2.7中也可以实现,如下方法

>>> subprocess.call(‘df -lh‘,shell=True)

Filesystem     Size   Used  Avail Capacity  iused    ifree %iused  Mounted on

/dev/disk1    465Gi  209Gi  256Gi    45% 54730303 67109311   45%   /

/dev/disk2s1  741Mi  557Mi  184Mi    76%   142675    47036   75%   /Volumes/Parallels Desktop 11

/dev/disk3s2  786Mi  669Mi  117Mi    86%   171353    29853   85%   /Volumes/ParallelsDesktop 11.1.3-32521

0

这里 subprocess.call(‘df -lh‘,shell=True)就明确告诉python解释器,你不用给我转了,就使用shell来进行执行。

很多时候,我门都想通过python里的模块方法获得执行结果。

怎么实现呢。

>>> a = subprocess.call("df -lh",shell=True)

Filesystem     Size   Used  Avail Capacity  iused    ifree %iused  Mounted on

/dev/disk1    465Gi  209Gi  256Gi    45% 54730696 67108918   45%   /

/dev/disk2s1  741Mi  557Mi  184Mi    76%   142675    47036   75%   /Volumes/Parallels Desktop 11

/dev/disk3s2  786Mi  669Mi  117Mi    86%   171353    29853   85%   /Volumes/ParallelsDesktop 11.1.3-32521

>>> a

0

这里我们看到0为执行命令的返回状态。

那么怎么得到结果呢。通过管道。将结果通过管道返回。

>>> a = subprocess.call("df -lh",shell=True,stdout=subprocess.PIPE)

>>> a

0

我们得到依然是0,为毛。因为call方法只返回执行状态。不返回命令执行结果。

如果想存下来,不能用call,要用Popen方法。

>>> a = subprocess.Popen(‘df -lh‘,shell=True)

>>> Filesystem     Size   Used  Avail Capacity  iused    ifree %iused  Mounted on

/dev/disk1    465Gi  209Gi  256Gi    45% 54852887 66986727   45%   /

/dev/disk2s1  741Mi  557Mi  184Mi    76%   142675    47036   75%   /Volumes/Parallels Desktop 11

/dev/disk3s2  786Mi  669Mi  117Mi    86%   171353    29853   85%   /Volumes/ParallelsDesktop 11.1.3-32521

>>> a

<subprocess.Popen object at 0x10881cb50>

看到这个和os模块的Popen方法得到的一样。那么我们试下a.read()

发现没有read()方法。在试下a.stdout.read()

同样没有a.stdout.read()方法。

那么分析下python运行Popen方法的执行过程。

Popen()方法执行里面的shell命令,其实是python又开启了一个子进程,子进程运行的结果要想返回给Popen()方法,需要使用管道,写法如下:

>> a = subprocess.Popen(‘df -lh‘,shell=True,stdout=subprocess.PIPE)

>>> a.returncode

a.returncode

>>> a.std

a.stderr a.stdin  a.stdout

>>> a.stdout.read()

‘Filesystem     Size   Used  Avail Capacity  iused    ifree %iused  Mounted on\n/dev/disk1    465Gi  209Gi  255Gi    46% 54971946 66867668   45%   /\n/dev/disk2s1  741Mi  557Mi  184Mi    76%   142675    47036   75%   /Volumes/Parallels Desktop 11\n/dev/disk3s2  786Mi  669Mi  117Mi    86%   171353    29853   85%   /Volumes/ParallelsDesktop 11.1.3-32521\n’

总结:

使用subprocess模块,想获得命令执行结果。1.使用Popen方法 2.使用管道3.使用a.stdout.read()方法记住下面的例子即可:

a = subprocess.Popen(‘df -lh‘,shell=True,stdout=subprocess.PIPE)

subprocess 另外几个方法

subprocess.check_call()检查执行结果,如果返回0说明执行正常,如果不返回0,返回报错

>>> subprocess.call(‘sssdf‘,shell=True)

/bin/sh: sssdf: command not found

127

>>> subprocess.check_call(‘sssdf‘,shell=True)

/bin/sh: sssdf: command not found

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 540, in check_call

raise CalledProcessError(retcode, cmd)

subprocess.CalledProcessError: Command ‘sssdf‘ returned non-zero exit status 127

>>>

subprocess.check_stdout()

subprocess.Popen()的其他参数,记住下面三个即可。其他用的少

stdin,stdout,stderr:分别表示程序的标准输入、输出、错误句柄

举例:

>>> obj = subprocess.Popen(["python"],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

>>> obj.stdin.write(‘print 1 \n‘)

>>> obj.stdin.write(‘print 2 \n‘)

>>> obj.stdin.write(‘print 3 \n‘)

>>> obj.stdin.write(‘print 4 \n’)

执行到这里,我想执行前面的输入内容了,那么就要用communicate() 方法

>>> out_error_list = obj.communicate()

>>> print out_error_list

(‘1\n2\n3\n4\n‘, ‘‘)

python2.7是这样写,python3.5就不用Popen,想得到命令的执行结果用subporcess.run()方法即可,run方法在2.7中是没有的

>>> b = subprocess.run(‘df -lh‘,shell=True,stdout=subprocess.PIPE)

>>> b

CompletedProcess(args=‘df -lh‘, returncode=0, stdout=b‘Filesystem     Size   Used  Avail Capacity  iused    ifree %iused  Mounted on\n/dev/disk1    465Gi  210Gi  255Gi    46% 54985500 66854114   45%   /\n/dev/disk2s1  741Mi  557Mi  184Mi    76%   142675    47036   75%   /Volumes/Parallels Desktop 11\n/dev/disk3s2  786Mi  669Mi  117Mi    86%   171353    29853   85%   /Volumes/ParallelsDesktop 11.1.3-32521\n‘)

>>>

时间: 2024-08-08 23:54:19

python常用内置模块的相关文章

python 常用内置模块使用

python模块分类:1,标准库2,开源模块3,自定义模块 python 常用内置模块使用1,time与datetime获取时间戳: time.time()  时间元组:  time.localtime()获取格式化字符串: time.strftime("%Y-%m-%d %H:%M:%S")时间格式转换:时间戳-> 时间元组: time.localtime(时间戳),time.gmtime(时间戳)时间戳-> 字符串格式:  time.strftime("%Y-

学习笔记(11月10日)--python常用内置模块的使用(logging, os, command)

四周五次课(11月10日) 一. logging 日志是我们排查问题的关键利器,写好日志记录,当我们发生问题时,可以快速定位代码范围进行修改.Python给我们开发者们提供了好的日志模块,下面我们就来介绍一下logging模块: 首先,我们先来看一个例子: import logging logging.debug('This is debug message') logging.info('This is info message') logging.warning('This is warni

python常用内置模块-random模块

random模块:用于生成随机数 '''关于数据类型序列相关,参照https://www.cnblogs.com/yyds/p/6123692.html''' random() 随机获取0 到1 之间的浮点数,即 0.0 <= num < 1.0 import random # 使用random模块,必须导入 num = random.random() print(num) # 0.0 <= num < 1.0 randint(m, n) 随机获取m 到n 之间的整数,即m <

python笔记--内置模块

python常用内置模块 类似于函数式编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来说,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个.py文件组成的代码集合就称为模块. 模块分为三种:自定义模块.内置模块.开源模块http://pypi.python.org 一.导入模块 方法: import module from module.xx.xx import xx from module.xx.xx import 

python——常用模块

time.asctime(time.localtime(1234324422)) python--常用模块 1 什么是模块: 模块就是py文件 2 import time #导入时间模块 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的时间字符串: (1)时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们运行"type(time.time())",返回的是float类型.

python常用数据类型内置方法介绍

熟练掌握python常用数据类型内置方法是每个初学者必须具备的内功. 一.整型 a = 100 a.xxx() class int(object): def bit_length(self): ##如果将某个整数用2进制表示,返回这个2进制所占bit位数. return 0 def conjugate(self, *args, **kwargs): ##共轭复数 @classmethod # known case def from_bytes(cls, bytes, byteorder, *ar

Python 常用的异常类型

Python中的异常类型 转自 http://blog.csdn.net/fcoolx/archive/2009/05/20/4202872.aspx 1.NameError:尝试访问一个未申明的变量>>>  vNameError: name 'v' is not defined 2.ZeroDivisionError:除数为0>>> v = 1/0ZeroDivisionError: int division or modulo by zero 3.SyntaxErr

一些Python常用库的整理收藏

一些Python常用库的整理收藏 转载自:https://zhuanlan.zhihu.com/p/21563130 另外 https://awesome-python.com/#data-analysis 网站上也分类好了很多常用的库. GUI 图形界面 Tkinter : Tkinter wxPython: wxPython PyGTK: PyGTK PyQt: PyQt PySide: PySide Web框架 django: django web2py:web2py flask: fla

python常用基本函数

python常用基本函数,布布扣,bubuko.com