日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:Python與Shell腳本的交互

考慮這樣一個(gè)問題,有hello.py腳本,輸出”hello, world!”;有TestInput.py腳本,等待用戶輸入,然后打印用戶輸入的數(shù)據(jù)。那么,怎么樣把hello.py輸出內(nèi)容發(fā)送給TestInput.py,最后TestInput.py打印接收到的”hello, world!”。下面來逐步講解一下shell的交互方式。

成都創(chuàng)新互聯(lián)公司專注于網(wǎng)站建設(shè),為客戶提供做網(wǎng)站、網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)開發(fā)服務(wù),多年建網(wǎng)站服務(wù)經(jīng)驗(yàn),各類網(wǎng)站都可以開發(fā),成都品牌網(wǎng)站建設(shè),公司官網(wǎng),公司展示網(wǎng)站,網(wǎng)站設(shè)計(jì),建網(wǎng)站費(fèi)用,建網(wǎng)站多少錢,價(jià)格優(yōu)惠,收費(fèi)合理。

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命令,返回一個(gè)返回碼(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!
0
subprocess.Popen()

利用Popen可以是實(shí)現(xiàn)雙向流的通信,可以將一個(gè)程序的輸出流發(fā)送到另外一個(gè)程序的輸入流.

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

分享名稱:創(chuàng)新互聯(lián)Python教程:Python與Shell腳本的交互
路徑分享:http://www.dlmjj.cn/article/dpidosh.html