最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

舉例講解Python程序與系統(tǒng)shell交互的方式

 更新時間:2015年04月09日 09:50:51   投稿:goldensun  
這篇文章主要介紹了Python程序與系統(tǒng)shell交互的方式,舉了一個非常簡單的hello world的例子,需要的朋友可以參考下

概述

考慮這樣一個問題,有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í)行命令,而不是用默認的os.execvp()執(zhí)行.

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

輸出:

hello, world!
0

subprocess.Popen()

利用Popen可以是實現(xiàn)雙向流的通信,可以將一個程序的輸出流發(fā)送到另外一個程序的輸入流.
Popen()是Popen類的構造函數(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()

相關文章

最新評論

伊吾县| 浦县| 长海县| 梧州市| 呼图壁县| 西平县| 蓬溪县| 青浦区| 辰溪县| 平凉市| 乌拉特中旗| 泸州市| 三原县| 务川| 本溪市| 繁峙县| 时尚| 拉萨市| 固原市| 西昌市| 黔江区| 琼海市| 南昌县| 葫芦岛市| 德安县| 光泽县| 广昌县| 东海县| 巴里| 九寨沟县| 乐山市| 宿迁市| 周口市| 博客| 应城市| 垣曲县| 岐山县| 双峰县| 油尖旺区| 保靖县| 青神县|