温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python中如何使用shell

发布时间:2020-07-29 09:05:41 来源:亿速云 阅读:214 作者:小猪 栏目:开发技术

这篇文章主要为大家展示了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的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI