日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > linux >内容正文

linux

python echo和linux交互_Python与shell的3种交互方式介绍

發布時間:2024/9/19 linux 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python echo和linux交互_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 echo和linux交互_Python与shell的3种交互方式介绍的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。