python中执行shell命令行read结果

时间:2023-03-08 17:28:23
python中执行shell命令行read结果

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

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)

  python中执行shell命令行read结果

或者

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])