欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python中shell执行知识点

程序员文章站 2022-05-07 10:13:05
os.systemsystem方法会创建子进程运行外部程序,方法只返回外部程序的运行结果。这个方法比较适用于外部程序没有输出结果的情况。import osos.system('ls')commands...

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 执行内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!