如何解析Python中调用shell命令的代码示例?

2026-05-21 23:183阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计272个文字,预计阅读时间需要2分钟。

如何解析Python中调用shell命令的代码示例?

1. 通过`os.system()`调用命令,但只能返回执行状态,无法获取shell cmd执行结果。

1.使用os.system()去调用,但是只能返回执行状态,不能获取shell cmd执行结果

#!/usr/bin/python # -*- coding: utf-8 import os status = os.system("ps aux |grep Xcode |grep -v grep") print status

2.使用os.popen执行并获取结果

如何解析Python中调用shell命令的代码示例?

​ 如果返回是str,直接通过read拿结果使用,如果是多行,选择readlines转list获取每行内容

#整份字符串处理 p=os.popen('ps aux |grep Xcode |grep -v grep') res=p.read() print res,type(res) p.close() #多行处理 p=os.popen('ps aux |grep Xcode |grep -v grep') res1=p.readlines() for line in res1: print 'line :'+line p.close()

3.使用commands 模块commands.getstatusoutput()

​ 如果返回是str,直接拿结果使用,如果是多行,选择用splitline转list获取

import commands status, output = commands.getstatusoutput('ps aux |grep Xcode |grep -v grep') print output output_list = output.splitlines() print output_list

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

本文共计272个文字,预计阅读时间需要2分钟。

如何解析Python中调用shell命令的代码示例?

1. 通过`os.system()`调用命令,但只能返回执行状态,无法获取shell cmd执行结果。

1.使用os.system()去调用,但是只能返回执行状态,不能获取shell cmd执行结果

#!/usr/bin/python # -*- coding: utf-8 import os status = os.system("ps aux |grep Xcode |grep -v grep") print status

2.使用os.popen执行并获取结果

如何解析Python中调用shell命令的代码示例?

​ 如果返回是str,直接通过read拿结果使用,如果是多行,选择readlines转list获取每行内容

#整份字符串处理 p=os.popen('ps aux |grep Xcode |grep -v grep') res=p.read() print res,type(res) p.close() #多行处理 p=os.popen('ps aux |grep Xcode |grep -v grep') res1=p.readlines() for line in res1: print 'line :'+line p.close()

3.使用commands 模块commands.getstatusoutput()

​ 如果返回是str,直接拿结果使用,如果是多行,选择用splitline转list获取

import commands status, output = commands.getstatusoutput('ps aux |grep Xcode |grep -v grep') print output output_list = output.splitlines() print output_list

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。