python调用cmd执行命令_python执行命令行:python中执行shell命令行read结果

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

python执行shell命令

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

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

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

os.system('python -V')

os.system('tree')

2 os.popen()

可以返回运行结果

import os

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

print(type(r))

print(r)

552284-20180109171919160-2133127759.png

或者

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值