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()

相关文章

python中的实例方法、静态方法、类方法、类变量和实例变量浅析

注:使用的是Python2.7。 一、实例方法 实例方法就是类的实例能够使用的方法。如下:复制代码 代码如下:class Foo:    def __ini...

Python通过poll实现异步IO的方法

本文实例讲述了Python通过poll实现异步IO的方法。分享给大家供大家参考。具体分析如下: 在使用poll()后返回轮询对象,该对象支持以下方法: pollObj.register(...

Python中的异常处理相关语句基础学习笔记

异常是指因为程序出现了错误而在正常控制流以外采取的行动,其分为两个阶段,第一阶段是引发异常的错误,当系统检测到错误并且意识到异常条件,解释器(也可以是程序员引发异常)会引发一个异常通知...

简单介绍Python下自己编写web框架的一些要点

在正式开始Web开发前,我们需要编写一个Web框架。 为什么不选择一个现成的Web框架而是自己从头开发呢?我们来考察一下现有的流行的Web框架: Django:一站式开发框架,但不...

在Python中使用判断语句和循环的教程

条件判断 计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。 比如,输入用户年龄,根据年龄打印不同的内容,在Python程序中,用if语句实现: age = 20 if a...