前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python--command模块

Python--command模块

作者头像
py3study
发布2020-01-09 15:35:15
4980
发布2020-01-09 15:35:15
举报
文章被收录于专栏:python3

command模块只使用与linux的shell模式下

在我们平时码字时,经常需要调用系统脚本或者系统命令来解决很多问题,接下来我们就介绍给大家一个很好用的模块command,可以通过python调用系统命令,调用系统命令command模块提供了三种方法:cmd代表系统命令

1.commands.getoutput(cmd)

只返回执行shell命令的结果:

举个例子:

[root@localhost ~]# cat a.py

#!/usr/bin/env python

#-*- coding:utf-8 -*-

import commands

cmd = 'ls /home/admin'

a = commands.getoutput(cmd)

print(type(a))

print(a)

结果:

[root@localhost ~]# python a.py

<type 'str'>

nginx.conf

nginx_upstream_check_module-master.zip

test.py

commands是提供linux系统环境下支持使用shell命令的一个模块,在企业中,我们很多的脚本和环境都是在linux系统中跑起来的,

2.commands.getstatusoutput(cmd)

在上面我们在执行shell命令的时候,我们的shell命令可能执行报错,或者异常退出,我们就要有一个条件来判断shell最终执行的结果是什么,commands.getstatusoutput(cmd)的返回结果有两个值,

[root@localhost ~]# cat c.py

#!/usr/bin/env python

#-*- coding:utf-8 -*-

import commands

cmd = 'ls /home/admin'

c = commands.getstatusoutput(cmd)

print(type(c))

status, output =commands.getstatusoutput(cmd)

print(status)

print(output)

print(type(output))

结果:

[root@localhost ~]# python c.py

<type 'tuple'>

0

nginx.conf

nginx_upstream_check_module-master.zip

test.py

<type 'str'>

解释:

Commands.getstatusoutput(cmd)的返回结果是一个tuple,第一个值是shell执行的结果,如果shell执行成功,返回0,否则,为非0,第二个是一个字符串,就是我们shell命令的执行结果,python通过一一对应的方式复制给status和output,这个就是python语言的巧妙之处。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/08/28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
命令行工具
腾讯云命令行工具 TCCLI 是管理腾讯云资源的统一工具。使用腾讯云命令行工具,您可以快速调用腾讯云 API 来管理您的腾讯云资源。此外,您还可以基于腾讯云的命令行工具来做自动化和脚本处理,以更多样的方式进行组合和重用。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档