日常整理python执行系统命令的常见方法(全)
作者:mrr 发布时间:2022-07-30 10:39:45
具体内容如下:
1 os.system
例如 ipython中运行如下命令,返回运行状态status
os.system('cat /etc/passwdqc.conf')
min=disabled,24,11,8,7
max=40
passphrase=3
match=4
similar=deny
random=47
enforce=everyone
retry=3
Out[6]: 0
2 os.popen()
popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.
运行返回结果
In [20]: output = os.popen('cat /proc/cpuinfo')
In [21]: lineLen = []
In [22]: for line in output.readlines():
lineLen.append(len(line))
....:
In [23]: line
line lineLen
In [23]: lineLen
Out[23]:
[14,
25,
...
3 如何同时返回结果和运行状态,commands模块:
#String form: <module 'commands' from '/usr/lib64/python2.7/commands.pyc'>
File: /usr/lib64/python2.7/commands.py
Docstring:
Execute shell commands via os.popen() and return status, output.
Interface summary:
import commands
outtext = commands.getoutput(cmd)
(exitstatus, outtext) = commands.getstatusoutput(cmd)
outtext = commands.getstatus(file) # returns output of "ls -ld file"
A trailing newline is removed from the output string.
Encapsulates the basic operation:
pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
commands示例如下:
In [24]: (status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
In [25]: status
Out[25]: 0
In [26]: len(output)
Out[26]: 3859
4 使用模块subprocess
ipython 中运行"?subprocess"可以发现subprocess是python用来替换os.popen()等管道操作命令的新模块
A more real-world example would look like this:
try:
retcode = call("mycmd" + " myarg", shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", e
相对于上面几种方式,subprocess便于控制和监控进程运行结果,subprocess提供多种函数便于应对父进程对子进程不同要求:
4.1.1 subprocess.call()
父进程父进程等待子进程完成,返回exit code
4.1.2 subprocess.check_call()
父进程等待子进程完成,返回0,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性,可用try...except...来检查
4.1.3 subprocess.check_output()
父进程等待子进程完成
返回子进程向标准输出的输出结果
检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性和output属性,output属性为标准输出的输出结果,可用try...except...来检查
例如:
In [32]: out = subprocess.call("ls -l", shell=True)
total 42244
-rw-rw-r--. 1 *** *** 366 May 26 09:10 ChangeLog
4.2.1
上面三个函数都是源于Popen()函数的wapper(封装),如果需要更加个性化应用,那么就需要使用popen()函数
Popen对象创建后,主程序不会自动等待子进程完成。我们必须调用对象的wait()方法,父进程才会等待 (也就是阻塞block)
[wenwt@localhost syntax]$ rm subprocess.pyc
[wenwt@localhost syntax]$ python process.py
parent process
[wenwt@localhost syntax]$ PING www.google.com (173.194.219.99) 56(84) bytes of data.
^C
[wenwt@localhost syntax]$
--- www.google.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 3999ms
加上wait方法:
[wenwt@localhost syntax]$ python process.py
PING www.google.com (173.194.219.103) 56(84) bytes of data.
--- www.google.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 3999ms
parent process
补充介绍:Python 执行终端命令的方法
import os
import subprocess
'''
os.system模块
os.system("ls -hl") 执行命令并返回状态码,当返回0表示成功;返回256表示失败,痛点是无法返回output
os.popen模块
os.popen("ls -hl") 执行命令,之后通过.read()方法获取output返回值
subprocess模块
subprocess.getstatusoutput("ls -hl") 执行命令,并返回状态status、输出output
subprocess.getoutput("ls -hl") 执行命令,只返回输出结果output
subprocess.call("ls -hl") 执行命令并返回状态码 和os.system("ls -hl")类似
'''
def test_system(cmd):
status = os.system(cmd) # 会自动输出output到控制台 但是无法接收,status为0表示成功、status为256表示失败
print(status)
def test_popen(cmd):
output = os.popen(cmd).read() # 只会获取到命令的output,如果是有output的错误命令 会输出output,否则输出空白
print(output)
def test_getoutput(cmd):
output = subprocess.getoutput(cmd) # 和os.popen(cmd)类似
print(output)
def test_getstatusoutput(cmd):
status, output = subprocess.getstatusoutput(cmd) # 执行命令,并返回状态status、输出output
print(status)
print(output)
def test_call(cmd):
status = subprocess.call(cmd) # 和os.system(cmd)类似
print(status)
if __name__ == '__main__':
# test_system('ls -lh') # test_system('test')
# test_popen('pwd') # test_popen('test')
# test_getoutput('pwd')
# test_getstatusoutput('pwd')
test_call('pwd')
以上内容就是本文的全部叙述,希望大家喜欢。
猜你喜欢
- 细心的人都会发现GitHub个人主页有一个记录每天贡献次数的面板,我暂且称之为贡献面板。就像下图那个样子。只要当天在GitHub有提交记录,
- 说明相应的学习视频见链接,本文只对重点进行总结。多进程重点(只要看下面代码的main函数即可)1.创建2.如何开守护进程3.多进程,开销大,
- 今天在学习的时候,发现scipy.misc中的imread提取图片的方法被弃用了。太生气了!只好使用了matplotlib.pyplot中的
- 一、CNN简介1. 神经网络基础输入层(Input layer),众多神经元(Neuron)接受大量非线形输入讯息。输入的讯息称为输入向量。
- 说明Python语言中列表(List)与其他语言的数组(Array)类似,是一种有序的集合数据结构,Python List可支持各种数据类型
- 最近因为项目原因需要编写数据库设计文档,但是由于数据表太多,手动编写耗费的时间太久,所以搞了一个简单的脚本快速生成数据库结构,保存到word
- Object 类型的对象虽然有 toString 方法,但结果却是 [Object Object] 让人没法理解的字符。比如简单的对象:{n
- show内容展示尝试用微信小程序的template组件实现。同时,尝试页面间转跳时传参,在目标页面引入模板文件实现 写的更少,做的更多 篇幅
- 在MySQL4中,是已经开始支持全文检索(索引)的了。但是只是对英文支持全文检索。由于英文在书写上的特殊性,使得分词算法相对中文来说,简单得
- 前言:record类型,这是一种新引用类型,而不是类或结构。record与类不同,区别在于record类型使用基于值的相等性。例如:publ
- 结果然后直接放源码:import cv2 as cvsource = cv.imread("zhaopian.jpg")
- 先给出一个四人团对Decorator mode的定义:动态地给一个对象添加一些额外的职责。再来说说这个模式的好处:认证,权限检查,记日志,检
- socket接口是实际上是操作系统提供的系统调用。socket的使用并不局限于Python语言,你可以用C或者Java来写出同样的socke
- 最近一直在研究 Javascript 相关的技术。在《Javascript 高级程序设计》有篇章节着重阐述了优化 Javascri
- python的数据类型可变不可变1、什么是可变不可变首先说一下什么是Python数据的可变不可变。我们都知道定义变量的时候,是先创建一块内存
- 内容摘要:本文介绍了对数据库的基本操作:数据记录筛选(select),更新数据库(update),删除记录(delete),添加数据记录(i
- 1.安装pyinstaller https://www.jb51.net/article/177160.htm2.安装pywin32 htt
- 记得之前learn python一书里面,因为当时没有官方支持,只能通过hack的方式实现抽象方法,具体如下 最简单的写法class MyC
- 本文实例讲述了Python实现监控Nginx配置文件的不同并发送邮件报警功能。分享给大家供大家参考,具体如下:因为项目中经常涉及到多个Ngi
- 本文转自微信公众号:"算法与编程之美"1、问题描述使用HBuilder做一个简单的社区浏览界面。2、解决方案这是对HBu