韩漫免费漫画在线观看方法,《好好疼爱里面》免费看,年轻漂亮的女士护士内衣,妈妈醉酒后把我当爸爸电视剧

文章 > Python高级 > Python与Shell脚本的交互

Python与Shell脚本的交互

头像

Python

2019-06-25 09:58:154045浏览 · 0收藏 · 0评论

考虑这样一个问题,有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!
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/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()
关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

《厨房激战5》完整版在线观看| 年轻的女学生| 《好好疼爱里面》免费看| 《酒店激战》动漫1-5集免费观.| 《囚禁空姐》电影免费观看| 扌桑小孩的辶鬲的历史背景| 《魅魔之耻》1~4集免费看| 录像狗配女人| 抵达花心乖叫老公是第几集 | 蜜桃成熟2| 妈妈的朋友2| 妈妈出轨了免费观看电视剧全集| 两个男生做酿酿酱酱酱视频| 不堪入耳的黄话怎么说| 教授和他的女大学生| 美国伦理〈欲奴3)| 性与艺术| 韩国 朋友家的麦子| 女教练房的呻吟| 《玉薄圃》| 《丰满人妻的滋味2HD| 人野兽马狗猪大全| 妻子在厨房被三个男人欺负的后果| 妈妈がだけの心に漂う| 国外成品网站1688入口在哪 | 小饰品| 麻花MV在线看免费观看电视剧 | 我的小后妈中字ID| 水仙二嫂| 宝宝扶着水池乖乖让爸爸洗头文| 麻花星空天美MV免费观看电视剧 | 苏软软汆肉的日常三鲜小馄饨| 边摸边脱吃奶边高潮视频免费| 小静被门卫大爷灌满JNG液视... | 120分钟做爰A片免费| 免费观看60分钟高清电视剧| 韩国电影火热的邻居高清完整版免. | 法国急救宝贝2| 爱的释放| 熟悉的味道3| 我把刘姨俩腿扛在肩上是哪一集的