1 os.system

可以返回运行shell命令状态,同时会在终端输出运行结果

例如 ipython中运行如下命令,返回运行状态status

os.system('cat /etc/passwdqc.conf')

min=disabled,24,11,8,7max=40passphrase=3match=4similar=deny

random=47enforce=everyone

retry=3Out[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 inoutput.readlines():

lineLen.append(len(line))

....:

In [23]: line

line lineLen

In [23]: lineLen

Out[23]:

[14,25,

...

3 如何同时返回结果和运行状态,commands模块:

#String form:

File: /usr/lib64/python2.7/commands.py

Docstring:

Execute shell commands via os.popen()and returnstatus, output.

Interface summary:importcommands

outtext=commands.getoutput(cmd)

(exitstatus, outtext)=commands.getstatusoutput(cmd)

outtext= commands.getstatus(file) #returns output of "ls -ld file"

A trailing newlineis removed fromthe 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

通常项目中经常使用方法为subporcess.Popen, 我们可以在Popen()建立子进程的时候改变标准输入、标准输出和标准错误,并可以利用subprocess.PIPE将多个子进程的输入和输出连接在一起,构成管道(pipe):

importsubprocess

child1= subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE)

child2= subprocess.Popen(["wc"], stdin=child1.stdout,stdout=subprocess.PIPE)

out=child2.communicate()print(out)

在例如使用lsblk查看swap分区的uuid:

importsubprocess

child= subprocess.Popen(["lsblk", "-f"], stdout=subprocess.PIPE)

out=child.stdout.readlines()

swap_uuid=Nonefor item inout:

line=item.strip().split()if len(line) == 4:if(line[1] == 'swap'):

swap_uuid= line[2]print(swap_uuid)

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", -retcodeelse:print >>sys.stderr, "Child returned", retcodeexceptOSError, 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)

total42244

-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 shell常用命令_python执行shell命令相关推荐

  1. 不是内部或外部命令 windows10 执行 linux命令

    不是内部或外部命令 windows10 执行 linux命令 打开 PowerShell 输入linux命令

  2. java cd命令_java执行cd命令

    如果要在java程序里执行一条linux可以用下面的写法 Process process = Runtime.getRuntime().exec(cmd);process.waitFor(); 但是当 ...

  3. Linux命令行执行sqlite3命令创建表格,插入数据,获取数据

    Linux命令行执行sqlite3命令创建表格,插入数据,获取数据 文章目录 Linux命令行执行sqlite3命令创建表格,插入数据,获取数据 1-进入sqlite3 2-创建数据库 3-创建表 4 ...

  4. python shell常用命令_python 之 shell命令执行

    python中有几种常用的执行shell命令的模块 1,os.system() 2, os.popen() 3,pexpect.run() 下面介绍3个模块的差别 1,os.system() 直接执行 ...

  5. python使用shell命令_python 调用shell命令的方法

    在python程序中调用shell命令,是件很酷且常用的事情-- 1. os.system(command) 此函数会启动子进程,在子进程中执行command,并返回command命令执行完毕后的退出 ...

  6. python执行linux命令返回结果_python执行linux命令的简单示例

    对python执行linux命令的两种方法感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧! python执行linux命令有两种方法: 在此以Linux常用的ls命令为例: ...

  7. lua执行shell命令6_Vim执行shell命令及使用Vim批量更改文件名

    写在前面:我"胡汉三"又回来了~上周顺利通过了试用期答辩,现在俺是一名正式的鹅厂人啦.哈哈哈~感谢各位可爱又热心的好伙伴对我的"不离不弃". 话休絮烦,今天分享 ...

  8. python调用scp上传目录_python执行scp命令拷贝文件及文件夹到远程主机的目录方法...

    系统环境centos7 python2.7 先在操作系统安装expect [root@V71 python]# vi 3s.py #!/usr/bin/python #coding:utf-8 imp ...

  9. python运行命令_Python执行系统命令教程

    一.背景说明 以前就感觉进步的速度和博客的数量成正比,所以很长一段时间内想不通为什么很多博客为什么到最后很少甚至不在更新了,直到最近自己也快成为断更的一员. 这段时间其实碰到和解决了挺多典型的问题,但 ...

最新文章

  1. R语言画形状—直线、矩形、多边形等
  2. leetcode 目录
  3. SQL Server--用户自定义函数
  4. 64位 linux 32位连接器,意法半导体为 32 位微控制器发布了一款自由的 Linux 集成开发环境...
  5. 操作XML 报错:根级别上的数据无效 和 给定编码中的字符无效 解决办法
  6. 阿里的26款大神级的Java开源项目
  7. python3.7安装keras教程_Python3.7安装keras和TensorFlow的教程图解
  8. mysql-5.5密码是多少_关于mysql-5.5数据库密码的设置和重置
  9. linux C 学习 简单字符串逆序输出
  10. IOC操作Bean管理注解方式(完全注解开发)
  11. Linux系统编程:验证kernel内核缓存区大小-4096字节
  12. 我遇见的网络故障分析报告
  13. [求助]谁能给我讲解一下,iOS编程要如何实时显示采集到的图像???
  14. 会说话的代码——书写自表达代码之道
  15. 多媒体个人计算机硬件,A.对个人计算机增加多媒体功能所需软硬件进行最低标准.PDF...
  16. [转]HashMap,LinkedHashMap,TreeMap的区别
  17. 数学建模——指派问题
  18. 【24】基于java的宠物医院管理系统
  19. 金晨想在无人车上劈叉,撒贝宁与数字祝融号对话…这届百度世界大会,有被惊艳到...
  20. FFT算法讲解——麻麻我终于会FFT了!

热门文章

  1. C语言不带头结点的单链表
  2. 管理类联考计算机,【2018管理类联考逻辑公式汇总】- 环球网校
  3. shell教程一 :介绍
  4. html文件的编写方法,1.2HTML文件的编写方法
  5. Oracle表字段check语句,sql语句大全之SQL CHECK 约束
  6. 接口文档swapper2和knife4j
  7. >adb: error: failed to copy ‘xx.apk‘ to ‘/system/app/test1.apk‘:remote Permission denied
  8. Linux多线程矩阵,操作系统实验(进程)多线程实现矩阵乘法
  9. 怎么打印飞书的审批单?
  10. obj模型文件的格式