Python與shell的互動方式

來源:互聯網
上載者:User

標籤:python   shell命令   shell   

hello.py代碼如下:

#!/usr/bin/pythonprint "hello, world!"

TestInput.py代碼如下:

#!/usr/bin/pythonstr = raw_input()print("input string is: %s" % str)
1.os.system(cmd)

這種方式只是執行shell命令,返回一個返回碼(0表示執行成功,否則表示失敗)

retcode = os.system("python hello.py")print("retcode is: %s" % retcode);

輸出:

hello, world!retcode is: 0
2.os.popen(cmd)

執行命令並返回該執行命令程式的輸入資料流或輸出資料流.該命令只能操作單向流,與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執行命令,而不是用預設的os.execvp()執行.

f = call("python hello.py", shell=True)print f

輸出:

hello, world!0
subprocess.Popen()

利用Popen可以是實現雙向流的通訊,可以將一個程式的輸出資料流發送到另外一個程式的輸入資料流.
Popen()是Popen類的建構函式,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/pythonimport osfrom subprocess import Popen, PIPE, callretcode = 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 fp1 = 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()

Python與shell的互動方式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.