zoukankan      html  css  js  c++  java
  • python调用其它脚本:pig,python,shell等等 (如何获取pig脚本执行的返回值)

    Python中调用pig语句:

    通过三个shell核命令可以

    os.system(‘执行的文件,可以是’)
    os.popen()
    os.startfile()

      

    具体步骤:

    1.      输入python,进入解释器模式。

    2.      Import os

    3.      执行os.system(‘test.sh’)

    其中test.sh的内容为 pig –xlocal e.pig,其直接执行pig命令。

    同样,可以直接执行os.system’ pig –xlocal e.pig’

     

    那么要是想获得e.pig执行后的返回值呢?

    就要用os.popen()函数:

    os.popen(camd[,mode[,bufsize]])

    os.popen() 可以返回回显的内容,以文件描述符返回。

    例如:

    f = os.popen ("test.sh",r)

    print f.read()

    或者:

    for line inos.popen("dir"):

    print line

     

    by the way,简单讲一下os.system和os.popen的区别:

    使用os.popen调用test.sh的情况:python调用Shell脚本,有两种方法:os.system(cmd)os.popen(cmd),前者返回值是脚本的退出状态码(默认返回值为0时,代表着运行成功。不成功,返回值根据执行的命令而不同),后者的返回值是脚本执行过程中的输出内容。实际使用时视需求情况而选择os.popen(cmd)这种调用方式是通过管道的方式来实现,返回一个file-like的对象,所以使用一个对象存储其返回内容,x=os.popen(cmd)。里面的内容是脚本输出的内容(可简单理解为echo输出的内容)。

    假定有一个shell脚本test.sh:

    #!/bin/bash

    1. echo "hello world!"

    2. exit 3

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

    如果我们需要获得os.system的正确返回值,那使用位移运算可以还原返回值:

    1. >>>  n = os.system(test.sh)

    2. >>> n >> 8

    3. >>> 3

    这就是在python脚本中调用shell核命令的功能,而pig这种脚本语言就是核命令的集合。

     

    我写的一个python脚本的例子,在云上调用pig脚本,返回值为一个字符串,你可以用t=type(file.read())去测试一下,然后print t看一下。

    import time
     
    #where is your pig
    PIG_PATH = '/opt/pig/current/bin/pig'
    PIG_SCRIPT= '/home/zhoujie/count/countlog2.pig'
    blank=' '
    file1='/mso/1/2013-04-08'
    file2='/mso/1/2013-04-08'

    if __name__ == "__main__":
            pig_cmd = PIG_PATH + blank +  '-f' + blank + PIG_SCRIPT + blank + '-param input=' + file1
            print "pid_cmd1: " + pig_cmd
            #print os.system(pig_cmd)
            file = os.popen(pig_cmd)
            result1= file.read()
            pig_cmd = PIG_PATH + blank +  '-f' + blank + PIG_SCRIPT + blank + '-param input='+file2
            print "pid_cmd2: " + pig_cmd
            file = os.popen(pig_cmd)
            result2= file.read()

            #change the string  into integer
            print result1 + " and "+result2
            result1=result1[1:-2]
            result2=result2[1:-2]

     

     

     

  • 相关阅读:
    Jenkins安装以及邮件配置
    day12_框架一tools.py代码
    codeforces 1428F
    codeforces 1428G Lucky Numbers (贪心+dp)
    单调队列优化多重背包
    bzoj1190 梦幻岛宝珠
    codeforces 1421 D
    bzoj 2287消失之物 (退背包)
    codeforces 553A
    组合计数小结
  • 原文地址:https://www.cnblogs.com/cl1024cl/p/6205757.html
Copyright © 2011-2022 走看看