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

yipeiwu_com5年前Python基础

概述

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

相关文章

Django后台管理系统的图文使用教学

Django后台管理系统的图文使用教学

django后台管理系统的使用检查配置文件 检查根urls.py文件 启动项目,浏览器输入ip端口/admin 如: 127.0.0.1/8000/admin 回车 注册后台管理...

python中selenium操作下拉滚动条的几种方法汇总

python中selenium操作下拉滚动条的几种方法汇总

UI自动化中经常会遇到元素识别不到,找不到的问题,原因有很多,比如不在iframe里,xpath或id写错了等等;但有一种是在当前显示的页面元素不可见,拖动下拉条后元素就出来了。 比如下...

Python使用装饰器模拟用户登陆验证功能示例

Python使用装饰器模拟用户登陆验证功能示例

本文实例讲述了Python使用装饰器模拟用户登陆验证功能。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #!python3 user_list =...

在Python中利用Into包整洁地进行数据迁移的教程

在Python中利用Into包整洁地进行数据迁移的教程

动机 我们花费大量的时间将数据从普通的交换格式(比如CSV),迁移到像数组、数据库或者二进制存储等高效的计算格式。更糟糕的是,许多人没有将数据迁移到高效的格式,因为他们不知道怎么(或者不...

Python的Django框架中自定义模版标签的示例

为了自定义一个模板标签,你需要告诉Django当遇到你的标签时怎样进行这个过程。 当Django编译一个模板时,它将原始模板分成一个个 节点 。每个节点都是 django.templat...