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