前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 入门

Python 入门

作者头像
音视频_李超
发布2020-04-02 18:29:15
4500
发布2020-04-02 18:29:15
举报
文章被收录于专栏:音视频直播技术专家

Python 调用 Shell 脚本

准备 shell 脚本 hello.sh

代码语言:javascript
复制
#! /usr/bin/ssh
echo "hello world!"
echo "succeed"

使用os.system方法

代码语言:javascript
复制
#! /usr/local/bin/python
import os
v_return_status=os.system( 'sh hello.sh')
print "v_return_status=" +str(v_return_status)

输出结果:

代码语言:javascript
复制
hello world!
succeed
v_return_status=0

使用os.popen方法

无返回终端,只打印输出内容

  • 获取shell print 语句内容一次性打印
代码语言:javascript
复制
p=os.popen('sh  hello.sh') 
x=p.read()
print x 
p.close()

输出结果: hello world! succeed

  • 获取shell print 语句内容,按照行读取打印
代码语言:javascript
复制
p=os.popen('sh  hello.sh') 
x=p.readlines()
for line in x:
    print 'ssss='+line

输出结果: ssss=hello world! ssss=succeed

使用commands.getstatusoutput() 方法

该方法可以获得到返回值和输出,非常好用。

-使用 commands.getstatusoutput() 方法获得到返回值和输出

代码语言:javascript
复制
(status, output) = commands.getstatusoutput('sh hello.sh')
print status, output

输出结果: 0 hello world! succeed

Python for 循环

代码语言:javascript
复制
for line in x:
    print line

特别需要注意的地方:

  • for 语句的后面一定要有 ':'
  • for 循环里的执行语句前面一定要缩进。
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Python 调用 Shell 脚本
    • 准备 shell 脚本 hello.sh
      • 使用os.system方法
        • 使用os.popen方法
          • 使用commands.getstatusoutput() 方法
          • Python for 循环
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档