+++++++++++++++++++++++++++++

python执行shell命令
1 os.system  (只有这个方法是边执行边输出,其他方法是最后一次性输出)

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

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

os.system('python -V')
os.system('tree')

遇到乱码问题可以采用一次性输出来解决。https://www.cnblogs.com/andy9468/p/8418649.html

或者pycharm的乱码问题:https://www.cnblogs.com/andy9468/p/12766382.html

2 os.popen()

可以返回运行结果

import os

r = os.popen('python -V').read()
print(type(r))
print(r)

  

或者

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.getstatusoutput('cat /proc/cpuinfo')

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

import commands
(status, output) = commands.getstatusoutput('cat /proc/cpuinfo') In [25]: status
Out[25]: 0 In [26]: len(output)
Out[26]: 3859

  

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

使用模块subprocess

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

import subprocess
child1 = subprocess.Popen("tree",shell=True, stdout=subprocess.PIPE)
out = child1.stdout.read()
print(out.decode('gbk'))

  

import subprocess
child1 = subprocess.Popen("tree /F".split(),shell=True, stdout=subprocess.PIPE)
out = child1.stdout.read()
print(out.decode('gbk'))

  

import subprocess
child1 = subprocess.Popen(['tree','/F'].split(),shell=True, stdout=subprocess.PIPE)
out = child1.stdout.read()
print(out.decode('gbk'))

  

退出进程

size_str = os.popen('adb shell wm size').read()
if not size_str:
  print('请安装 ADB 及驱动并配置环境变量')
  sys.exit()

  

封装好的函数:Python执行shell命令

from subprocess import Popen, PIPE

def run_cmd(cmd):
# Popen call wrapper.return (code, stdout, stderr)
child = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
out, err = child.communicate()
ret = child.wait()
return (ret, out, err) if __name__ == '__main__':
r=run_cmd("dir") print(r[0])
print(r[1].decode("gbk"))
print(r[2])

最新文章

  1. MIT 6.824 : Spring 2015 lab3 训练笔记
  2. 处理 input 上传图片,浏览器读取图片大小过程中遇到到的坑(兼容IE8\9)
  3. Java(一)
  4. python 3 学习笔记 (三)
  5. nil、Nil、NULL和NSNull的理解
  6. stm32 加入 USE_STDPERIPH_DRIVER、STM32F10X_HD的原因
  7. Myeclipse8.5 svn插件安装两种方式
  8. Firefly是什么?有什么特点?
  9. MVC中给TextBoxFor设置默认值和属性
  10. ASP.NET -- repeater控件的使用
  11. Redis阻塞诊断基础
  12. C++的IO处理中的头文件以及类理解(1)
  13. oracle表查询优化
  14. Ubuntu18.04 安装tomcat9
  15. 查看最新的Google地址
  16. python -u 启动python文件的作用,PYTHONUNBUFFERED环境变量的作用
  17. 3-idiots hdu4609 母函数+FFT 组合数学题
  18. [LeetCode&Python] Problem 892. Surface Area of 3D Shapes
  19. 通过SSH克隆远程仓库(GitLab)到本地
  20. Maven存储库

热门文章

  1. [转]logging使用
  2. Spring Mvc 页面传递数组到后台接收
  3. IOS设计模式第三篇之外观设计模式
  4. Qt编写带频谱的音乐播放器
  5. PV&UV&IP之间的区别和联系
  6. JS笔记 - JQ事件委托( 适用于给动态生成的脚本元素添加事件)
  7. 题目1008:最短路径问题(最短路径问题dijkstra算法)
  8. myisam innodb 次级 索引的区别
  9. X-Requested-With导致CSRF失败
  10. Java中的一些性能监控和故障分析工具