python在shell中运行_python中shell执行知识点

os.system

system方法会创建子进程运行外部程序,方法只返回外部程序的运行结果。这个方法比较适用于外部程序没有输出结果的情况。

import os

os.system('ls')

commands.getstatusoutput

使用commands模块的getoutput方法,这种方法同popend的区别在于popen返回的是一个文件句柄,而本方法将外部程序的输出结果当作字符串返回,很多情况下用起来要更方便些。

主要方法:

commands.getstatusoutput(cmd) 返回(status, output)

commands.getoutput(cmd) 只返回输出结果

commands.getstatus(file) 返回ls -ld file的执行结果字符串,调用了getoutput,不建议使用此方法

当需要得到外部程序的输出结果时,本方法非常有用。比如使用urllib调用Web API时,需要对得到的数据进行处理。os.popen(cmd) 要得到命令的输出内容,只需再调用下read()或readlines()等 如a=os.popen(cmd).read()

import os

ls = os.popen('ls')

print ls.read()

commands.getstatusoutput

使用commands模块的getoutput方法,这种方法同popend的区别在于popen返回的是一个文件句柄,而本方法将外部程序的输出结果当作字符串返回,很多情况下用起来要更方便些。

主要方法:

commands.getstatusoutput(cmd) 返回(status, output)

commands.getoutput(cmd) 只返回输出结果

commands.getstatus(file) 返回ls -ld file的执行结果字符串,调用了getoutput,不建议使用此方法

import commands

commands.getstatusoutput('ls -lt') # 返回(status, output)

subprocess.call

根据Python官方文档说明,subprocess模块用于取代上面这些模块。有一个用Python实现的并行ssh工具—mssh,代码很简短,不过很有意思,它在线程中调用subprocess启动子进程来干活。

from subprocess import call

call(["ls", "-l"])

import shlex, subprocess

def shell_command(cmd, timeout) :

data = {"rc":False, "timeout":False, "stdout":"", "stderr":""}

try :

process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

try:

outs, errs = process.communicate(timeout=timeout)

data["stdout"] = outs.decode("utf-8")

data["stderr"] = errs.decode("utf-8")

data["rc"] = True

except subprocess.TimeoutExpired :

process.kill()

outs, errs = process.communicate()

data["rc"] = False

data["stdout"] = outs.decode("utf-8")

data["stderr"] = "timeout"

data["timeout"] = True

except Exception as e :

data["rc"] = False

data["stderr"] = e

finally :

return data

到此这篇关于python中shell执行知识点的文章就介绍到这了,更多相关python shell 执行内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值