python與shell的3種交互方式介紹

字號:


    概述
    考慮這樣一個問題,有hello.py腳本,輸出”hello, world!”;有testinput.py腳本,等待用戶輸入,然后打印用戶輸入的數(shù)據(jù)。那么,怎么樣把hello.py輸出內(nèi)容發(fā)送給testinput.py,最后testinput.py打印接收到的”hello, world!”。下面我來逐步講解一下shell的交互方式。
    hello.py代碼如下:
    代碼如下:
    #!/usr/bin/python
    print hello, world!
    testinput.py代碼如下:
    代碼如下:
    #!/usr/bin/python
    str = raw_input()
    print(input string is: %s % str)
    1.os.system(cmd)
    這種方式只是執(zhí)行shell命令,返回一個返回碼(0表示執(zhí)行成功,否則表示失敗)
    代碼如下:
    retcode = os.system(python hello.py)
    print(retcode is: %s % retcode);
    輸出:
    代碼如下:
    hello, world!
    retcode is: 0
    2.os.popen(cmd)
    執(zhí)行命令并返回該執(zhí)行命令程序的輸入流或輸出流.該命令只能操作單向流,與shell命令單向交互,不能雙向交互.
    返回程序輸出流,用fouput變量連接到輸出流
    代碼如下:
    fouput = os.popen(python hello.py)
    result = fouput.readlines()
    print(result is: %s % result);
    輸出:
    代碼如下:
    result is: ['hello, world!\n']
    返回輸入流,用finput變量連接到輸出流
    代碼如下:
    finput = os.popen(python testinput.py, w)
    finput.write(how are you\n)
    輸出:
    代碼如下:
    input string is: how are you
    3.利用subprocess模塊
    subprocess.call()
    類似os.system(),注意這里的”shell=true”表示用shell執(zhí)行命令,而不是用默認(rèn)的os.execvp()執(zhí)行.
    代碼如下:
    f = call(python hello.py, shell=true)
    print f
    輸出:
    代碼如下:
    hello, world!
    subprocess.popen()
    利用popen可以是實現(xiàn)雙向流的通信,可以將一個程序的輸出流發(fā)送到另外一個程序的輸入流.
    popen()是popen類的構(gòu)造函數(shù),communicate()返回元組(stdoutdata, stderrdata).
    代碼如下:
    p1 = popen(python hello.py, stdin = none, stdout = pipe, shell=true)
    p2 = popen(python testinput.py, stdin = p1.stdout, stdout = pipe, shell=true)
    print p2.communicate()[0]
    #other way
    #print p2.stdout.readlines()
    輸出:
    代碼如下:
    input string is: hello, world!
    整合代碼如下:
    代碼如下:
    #!/usr/bin/python
    import os
    from subprocess import popen, pipe, call
    retcode = os.system(python hello.py)
    print(retcode is: %s % retcode);
    fouput = os.popen(python hello.py)
    result = fouput.readlines()
    print(result is: %s % result);
    finput = os.popen(python testinput.py, w)
    finput.write(how are you\n)
    f = call(python hello.py, shell=true)
    print f
    p1 = popen(python hello.py, stdin = none, stdout = pipe, shell=true)
    p2 = popen(python testinput.py, stdin = p1.stdout, stdout = pipe, shell=true)
    print p2.communicate()[0]
    #other way
    #print p2.stdout.readlines()