搜索
Hi~登录注册
查看: 831|回复: 0

python中shell执行知识点

[复制链接]

0

主题

0

帖子

10

积分

新手上路

Rank: 1

积分
10
发表于 2020-5-15 09:57:42 来自手机 | 显示全部楼层 |阅读模式
os.system
system方法会创建子进程运行外部程序,方法只返回外部程序的运行结果。这个方法比较适用于外部程序没有输出结果的情况。
  1. import osos.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()
  1. import osls = 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,不建议使用此方法
  1. import commandscommands.getstatusoutput('ls -lt')   # 返回(status, output)
复制代码
subprocess.call

根据Python官方文档说明,subprocess模块用于取代上面这些模块。有一个用Python实现的并行ssh工具—mssh,代码很简短,不过很有意思,它在线程中调用subprocess启动子进程来干活。
  1. from subprocess import callcall(["ls", "-l"])
复制代码
  1. import shlex, subprocessdef 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 执行内容请搜索脚本之家从前的文章或继续欣赏下面的相关文章希望各人以后多多支持脚本之家!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

游客
回复
您需要登录后才可以回帖 登录 | 点我注册

快速回复 返回顶部 返回列表