python commands 执行命令详解

简介: python commands 执行命令详解

python 模块 commands 执行命令

文章目录

1. 介绍

commands模块是python的内置模块,他共有三个函数,使用help(commands)可以查看到

2. 方法

FUNCTIONS
    getoutput(cmd)
        Return output (stdout or stderr) of executing cmd in a shell.
    getstatus(file)
        Return output of "ls -ld <file>" in a string.
    getstatusoutput(cmd)
        Return (status, output) of executing cmd in a shell.

2.1 commands.getstatusoutput(cmd)

返回一个元组(status,output)

status代表的shell命令的返回状态,如果成功的话是0;output是shell的返回的结果

用os.popen()执行命令cmd, 然后返回两个元素的元组(status, result),其中 status为int类型,result为string类型。cmd执行的方式是{ cmd ; } 2>&1, 这样返回结果里面就会包含标准输出和标准错误.

>>> import commands
>>> status, output = commands.getstatusoutput("ls")
>>> print status
0
>>> print output
atom:
bookstore
cookie.py~

2.2 commands.getstatus(file)

只返回执行的结果, 忽略返回值.返回ls -ld file执行的结果.

commands.getstatus(file)

注意:该函数已被python丢弃,不建议使用

2.3 commands.getoutput(cmd)

只返回执行的结果, 忽略返回值.

>>> print commands.getoutput("ls")
atom:
bookstore
cookie.py~

3 练习

#!/usr/bin/python
#coding:utf-8
import os,sys,commands
def openfile():
    grains = {}
    _open_file=65533
    try:
        getulimit=commands.getstatusoutput('source /etc/profile;ulimit -n')
    except Exception,e:
        pass
    if getulimit[0]==0:
       _open_file=int(getulimit[1])
    grains['max_open_file'] = _open_file
    print grains
    return grains
openfile()

输出:

$ python com1.py 
{'max_open_file': 1024}

参考:

相关文章
|
安全 网络安全 文件存储
思科设备巡检命令Python脚本大集合
【10月更文挑战第18天】
1139 1
思科设备巡检命令Python脚本大集合
|
运维 Shell 数据库
Python执行Shell命令并获取结果:深入解析与实战
通过以上内容,开发者可以在实际项目中灵活应用Python执行Shell命令,实现各种自动化任务,提高开发和运维效率。
738 20
|
分布式计算 MaxCompute 对象存储
|
安全 Shell 数据处理
使用Python执行Shell命令并获取结果
在实际应用中,可以根据需要选择适当的参数和方法来执行Shell命令,并处理可能出现的各种情况。无论是系统管理、自动化任务还是数据处理,掌握这些技巧都将极大地提高工作效率。
972 12
|
机器学习/深度学习 缓存 PyTorch
pytorch学习一(扩展篇):miniconda下载、安装、配置环境变量。miniconda创建多版本python环境。整理常用命令(亲测ok)
这篇文章是关于如何下载、安装和配置Miniconda,以及如何使用Miniconda创建和管理Python环境的详细指南。
11060 0
pytorch学习一(扩展篇):miniconda下载、安装、配置环境变量。miniconda创建多版本python环境。整理常用命令(亲测ok)
|
Python
Python PDB命令介绍
【10月更文挑战第15天】 使用PDB的方式有两种,其中一种是在脚本中添加代码,不觉得这种方式比print好在哪里,所以这种方式此文不表。这里我们只学习PDB的命令行使用方式
611 4
|
Linux iOS开发 MacOS
python的virtualenv虚拟环境常见问题和命令
`venv`是Python的内置模块,用于创建隔离的虚拟环境。创建虚拟环境如`python3 -m venv myenv`,激活环境在Windows上是`./venv/Scripts/activate`,在Unix-like系统是`source myenv/bin/activate`。退出环境用`deactivate`。`pip list`查看已安装包,`pip install`安装包,`pip freeze &gt; requirements.txt`保存依赖。PyCharm中红色`venv`表示项目使用了虚拟环境。
1963 2
 python的virtualenv虚拟环境常见问题和命令
|
机器学习/深度学习 Shell 开发工具
Python使用管道执行git命令报错|4-7
Python使用管道执行git命令报错|4-7
|
Python Windows
Python:执行py命令,提示: Can‘t find a default Python.
Python:执行py命令,提示: Can‘t find a default Python.
|
Shell Linux Python
python执行linux系统命令的几种方法(python3经典编程案例)
文章介绍了多种使用Python执行Linux系统命令的方法,包括使用os模块的不同函数以及subprocess模块来调用shell命令并处理其输出。
1359 0

推荐镜像

更多