国产成人AV无码一二三区,少女1到100集,国产精品久久久久精品综合紧,巜公妇之诱感肉欲HD在线播放

文章 > 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()
关注

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

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

不堪入耳的黄话怎么说| 《酒店激战》动漫1-5集免费观..| 小峡子边喂奶边和我做爰| 雨后的小故事闪图| 叔嫂发生过关系后的心理变化| 坤坤寒进桃子里在线看歌词| 做爰高潮A片(毛片)| 人犬兽人在线观看免费完整一| 在线观看免费观看在线NBA | 尼姑小寡妇免费播放电视剧| 榴莲APP官网下载1.0.3| 真人老太太实战镖客视频| 同学的母亲中字ID| 真人刺激战场40分钟电视剧| 《交换做爰》在线观看| 坤坤寒入桃子里电视剧免费看| 人OR猪OR狗的DNA播放| 妈妈出轨了免费观看电视剧全集| 风月片美乳色诱| 麻花传剧原创MV在线看完整版高. 麻花天美星空无限免费观看电视剧 | 成色18K1.220.38软件| 泡妞网站| 砂浆强度等级| 美女和帅哥一起努力生产豆浆的视..| 一天日八个B| 少女初恋吃小头头视频免费 | 台湾《洞门为君开》演员表| 18岁的少女与狗高清电视剧| 摸摸大扔子是讽刺人还是夸人| 老师穿裙子没有穿内裤| 温柔女教师在线观看电视剧大全| 边添小流边狠狠躁69集| 妈妈叫我戴上避孕套是什么歌| 共享女儿小诗1~10章的背景资..| 蜜桃成熟时| 保姆的特殊待遇5| 边添小流边狠狠躁69集| 麻花星空MV高清在线播放 | 公主很忙(N)笔趣阁免费阅读 | 《高压监狱2》完整版| 爆乳