美文网首页
python调用Shell脚本

python调用Shell脚本

作者: simplehu | 来源:发表于2017-09-08 10:06 被阅读0次

Python执行系统命令,os.system && os.popen && subprocess.Popen

python调用Shell脚本,有两种方法:os.system(cmd)os.popen(cmd),前者返回值是脚本的退出状态码,后者的返回值是脚本执行过程中的输出内容。实际使用时视需求情况而选择。

os.system(cmd):

该方法在调用完shell脚本后,返回一个16位的二进制数,低位为杀死所调用脚本的信号号码,高位为脚本的退出状态码,即脚本中“exit 1”的代码执行后,os.system函数返回值的高位数则是1,如果低位数是0的情况下,则函数的返回值是0×100,换算为10进制得到256。

os.popen(cmd):

这种调用方式是通过管道的方式来实现,函数返回一个file-like的对象,里面的内容是脚本输出的内容(可简单理解为echo输出的内容)。使用os.popen调用test.sh的情况:
明显地,像调用”ls”这样的shell命令,应该使用popen的方法来获得内容

os.popen()可以实现一个“管道”,从这个命令获取的值可以继续被调用。而os.system不同,它只是调用,调用完后自身退出,可能返回个0吧
eg:

os.popen('ps -C ntpd | grep -v CMD |awk '{ print $1 }').readlines()[0]
files=os.popen("cd /usr/local/apache2/cgi-bin/perflog/ ;ls -l  |awk '{print $9}'").readlines()
for file in files:
  if file=='\n':#linux系统中回车换行符为\n
    continue
  else:
    pass
subprocess.Popen(cmd,shell=True)

相关文章

  • 2021-09-09

    shell脚本调用python 传参数 2、接受python运行结果

  • Python 入门

    Python 调用 Shell 脚本 准备 shell 脚本 hello.sh 使用os.system方法 输出结...

  • python调用shell 三种方法和 解决权限问题

    一) 调用并且解决权限问题 python脚本: python.sh shell 脚本test1.sh 执行 py...

  • 优化方向

    1.python调shell脚本:这个相当于是脚本调用脚本,完全可以改成只用python脚本,集成度更高

  • Gradle调用shell脚本和python脚本并传参

    Gradle调用shell脚本和python脚本并传参 最近由于项目自动化构建的需要,研究了下gradle调用脚本...

  • Python调用Shell命令

    前言:在python程序里面难免会用到shell命令,在python调用shell脚本也不是很难,记录了一下!**...

  • shell向python传参数

    shell向python传参数 1 直接从命令框中获取参数 想要在shell中调用python脚本时实现 利用 s...

  • Java 调用Shell命令

    我在网上看见Java调用python的大部分方案是Java调用Shell命令执行python脚本。 关于使用Run...

  • python调用Shell脚本

    Python执行系统命令,os.system && os.popen && subprocess.Popen py...

  • Python调用shell脚本

    比较简便的方式,不用第三方包 首先import os os.system ret = so.system('pwd...

网友评论

      本文标题:python调用Shell脚本

      本文链接:https://www.haomeiwen.com/subject/relgjxtx.html