举例讲解Python程序与系统shell交互的方式

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

相关文章

Python运算符重载用法实例分析

本文实例讲述了Python运算符重载用法。分享给大家供大家参考。具体如下: 在Python语言中提供了类似于C++的运算符重在功能: 一下为Python运算符重在调用的方法如下: Met...

Python中的列表知识点汇总

Python list 在介绍 Python tuple 时,我使用了类比的方法,将其比做一个袋子,您可以在袋子中存放不同的东西。Python list 与此非常类似,因此,它的功能与袋...

Python中字符串与编码示例代码

在最新的Python 3版本中,字符串是以Unicode编码的,即Python的字符串支持多语言 编码和解码    字符串在内存中以Unicode表示,在操作字符串时,经常需要...

Python中类型检查的详细介绍

Python中类型检查的详细介绍

前言 大家都知道Python 是一门强类型、动态类型检查的语言。所谓动态类型,是指在定义变量时,我们无需指定变量的类型,Python 解释器会在运行时自动检查。 与静态类型语言(如 C...

python+opencv打开摄像头,保存视频、拍照功能的实现方法

以下代码是保存视频 # coding:utf-8 import cv2 import sys reload(sys) sys.setdefaultencoding('utf8') c...