举例讲解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()

相关文章

Python3 全自动更新已安装的模块实现

Python3 全自动更新已安装的模块实现

1. 手动操作 1.1. 显示模块 pip list 1.2. 显示过期模块 pip list --outdated 1.3. 安装模块 pip install...

举例讲解Python设计模式编程的代理模式与抽象工厂模式

代理模式 Proxy模式是一种常用的设计模式,它主要用来通过一个对象(比如B)给一个对象(比如A) 提供'代理'的方式方式访问。比如一个对象不方便直接引用,代理就在这个对象和访问者之间做...

Python实现的银行系统模拟程序完整案例

本文实例讲述了Python实现的银行系统模拟程序。分享给大家供大家参考,具体如下: 银行系统模拟程序 1、概述 ​ 使用面向对象思想模拟一个简单的银行系统,具备的功能:管理员...

python实现输入数字的连续加减方法

不用库,写了很久,一直出bug,到网上一搜,可以直接输入之后,eval(str)即可得到结果! eval程序如下: s=input("请输入要运算的数字") print("The r...

selenium+python自动化测试之多窗口切换

selenium+python自动化测试之多窗口切换

在很多页面上都有可点击的链接,点击这些链接会打开一个新的窗口,这时如果要在新打开的窗口中操作页面,就需要先切换到新窗口中,如果不进行切换操作,还是操作的上一个页面窗口 浏览器窗口的切换通...