Python與shell的3種互動方式介紹

2022-06-17 04:54:10 字數 2668 閱讀 8010

概述

考慮這樣乙個問題,有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()

3種shell自動互動的方法

一 背景 shell指令碼在處理自動迴圈或大的任務方面可節省大量的時間,通過建立乙個處理任務的命令清單,使用變數 條件 算術和迴圈等方法快速建立指令碼以完成相應工作,這比在命令列下乙個個敲入命令要省時省力得多。但是有時候我們可能會需要實現和互動程式如ftp,telnet伺服器等進行互動的功能,這時候...

shell 執行指令碼的 3 種方式

首先把工作目錄切換到指令碼所在的目錄 該指令碼所在的目錄為 home user cd home user 指令碼為 hello shell.sh 指令碼的內容為 usr bin env bash echo hello shell sh hello shell.sh 或者 bash hello she...

Shell逐行讀取檔案的3種方法

方法1 while迴圈中執行效率最高,最常用的方法。while read line doecho line done filename 注釋 這種方式在結束的時候需要執行檔案,就好像是執行完的時候再把檔案讀進去一樣。方法2 管道法 cat filename while read line cat f...