中文字幕免费精品_亚洲视频自拍_亚洲综合国产激情另类一区_色综合咪咪久久

python與shell的3種交互方式介紹
來源:易賢網 閱讀:1005 次 日期:2016-06-14 10:20:25
溫馨提示:易賢網小編為您整理了“python與shell的3種交互方式介紹”,方便廣大網友查閱!

概述

考慮這樣一個問題,有hello.py腳本,輸出”hello, world!”;有testinput.py腳本,等待用戶輸入,然后打印用戶輸入的數據。那么,怎么樣把hello.py輸出內容發送給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)

這種方式只是執行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!

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/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()

更多信息請查看腳本欄目
易賢網手機網站地址:python與shell的3種交互方式介紹
由于各方面情況的不斷調整與變化,易賢網提供的所有考試信息和咨詢回復僅供參考,敬請考生以權威部門公布的正式信息和咨詢為準!

2026國考·省考課程試聽報名

  • 報班類型
  • 姓名
  • 手機號
  • 驗證碼
關于我們 | 聯系我們 | 人才招聘 | 網站聲明 | 網站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點 | 投訴建議
工業和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網安備53010202001879號 人力資源服務許可證:(云)人服證字(2023)第0102001523號
云南網警備案專用圖標
聯系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關注公眾號:hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權所有:易賢網
云南網警報警專用圖標
主站蜘蛛池模板: 望都县| 吴桥县| 乌拉特后旗| 大关县| 长葛市| 大悟县| 莱芜市| 东安县| 三穗县| 嘉义县| 屏东市| 昌吉市| 冕宁县| 枞阳县| 永胜县| 蓬安县| 法库县| 遵义县| 武宁县| 正安县| 定结县| 苍南县| 犍为县| 内乡县| 永清县| 白朗县| 大连市| 新平| 武清区| 姚安县| 玛多县| 诸暨市| 东乡| 延吉市| 阿拉善左旗| 平利县| 九龙县| 鄂温| 新巴尔虎右旗| 连云港市| 潜江市|