国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

舉例講解Python程序與系統shell交互的方式

2020-02-23 00:38:24
字體:
來源:轉載
供稿:網友

概述

考慮這樣一個問題,有hello.py腳本,輸出”hello, world!”;有TestInput.py腳本,等待用戶輸入,然后打印用戶輸入的數據。那么,怎么樣把hello.py輸出內容發送給TestInput.py,最后TestInput.py打印接收到的”hello, world!”。下面我來逐步講解一下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()            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 绥江县| 贵南县| 青海省| 历史| 南乐县| 石屏县| 永丰县| 久治县| 巨鹿县| 独山县| 华亭县| 临夏市| 五原县| 侯马市| 阳泉市| 格尔木市| 华阴市| 定陶县| 南通市| 牙克石市| 东城区| 西峡县| 民勤县| 凤山市| 通许县| 商洛市| 油尖旺区| 浦东新区| 公安县| 吉林市| 泰州市| 五河县| 逊克县| 镶黄旗| 怀柔区| 永丰县| 封开县| 沁源县| 乌兰浩特市| 英吉沙县| 昌宁县|