Python与shell的3种交互方式介绍

php中文网
发布: 2016-06-06 11:24:51
原创
1413人浏览过

概述

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

商易多用户商城
商易多用户商城

功能介绍:1. 商品出售包含拍卖模式,一口价模式。2. 全套系统采用淘宝网风格,成熟,简洁大方3. 每个商品支持多张图片上传,可自由设定,满足广大网民的迫切要求4. 商品信息支持 ubb,图文并茂5. 注册用户可参与竞拍,或者拍卖自己的商品6. 拥有会员注册,交易提醒,成交商品确认等邮件发送功能7. 拥有交易双方信用评价的功能,使得交易安全可*,可信度高8. 拥有安全稳定的用户虚拟币平台,可实现商

商易多用户商城 0
查看详情 商易多用户商城

立即学习Python免费学习笔记(深入)”;

类似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速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号