日常整理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')
以上内容就是本文的全部叙述,希望大家喜欢。


猜你喜欢
- 一, 创建用户: 命令:CREATE USER 'usern
- 这篇文章主要介绍了Python代码块及缓存机制原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋
- 本文实例讲述了Go语言生成随机数的方法。分享给大家供大家参考。具体实现方法如下:golang生成随机数可以使用math/rand包packa
- 目录一、索引类型1.B+树2.MyISAM和InnoDB的B+树索引实现方式的区别(聚簇索引和非聚簇索引)?3.非聚簇索引4.聚簇索引的优缺
- microtime() 函数返回当前 Unix 时间戳的微秒数。用于检测程序执行时间的函数,也是PHP内置的时间函数之一,在PHP中可以用于
- 获取图片宽度和高度的类,支持JPG,GIF,PNG,BMP我们可以使用这个类来处理图片的显示。<% Class
- 视频对象提取与其说是视频对象提取,不如说是视频颜色提取,因为其本质还是使用了OpenCV的HSV颜色物体检测。下面话不多说了,来一起看看详细
- 案例一 导入图片思路: 1.导入库 2.加载图片 3.创建窗口 4.显示图片 5.暂停窗口 6.关闭窗口# 1.导入库import cv2#
- PHP 向它运行的任何脚本提供了大量的预定义常量。魔术常量准确来说并不能算是常量,常量我们在之前的文章中我们介绍到,常量被定义之后是不能被改
- 目的在刷算法题中经常遇到关于链表的操作,在使用go语言去操作链表时不熟悉其实现原理,目的是为了重温链表这一基础且关键的数据结构。1、链表的特
- 目录题目描述示例 1:示例 2:示例 3:单向构造(哈希表计数)双向构造(双指针)最后题目描述这是 LeetCode 上的 1743. 从相
- asp中我们可以利用ERR对象来判断sql语句执行是否成功:SQL="Insert INTO TABLE(F1,F2) value
- 1.图像读取使用cv2.imread(filepath,flags)读入图像filepath: 读入图像完整路径(绝对路径,相对路径)fla
- 前几天要写一个东西里面有用到读文件的。 可是我不想用FSO,我怕有的空间不支持。 &nbs
- 装饰器的基础使用(装饰带参函数)def decorator(func): def inner(info): &nb
- 前言前段时间做项目的时候,需要一个Markdown编辑器,在网上找了一些开源的实现,但是都不满足需求说实话,这些开源项目也很难满足需求公司项
- 1、查询语句的执行顺序select[distinct] from join(如left 
- 网络技术,无论是php还是java ,无论是pc时代,还是移动时代,无论是黑客技术,还是程序新人,it技术,无疑是当前最火的行业,无论是个人
- 关于opencvOpenCV 是 Intel 开源计算机视觉库 (Computer Version) 。它由一系列 C 函数和少量 C++
- Windows环境下一、开启 Imagick 扩展1、安装PHP扩展:Imagick,下载地址 https://pecl.php.net/p