Python与shell交互方式
来源:互联网 发布:映射网络驱动器 密码 编辑:程序博客网 时间:2024/06/09 22:44
问题概述
考虑这样一个问题,有hello.py脚本,输出”hello, world!”;有TestInput.py脚本,等待用户输入,然后打印用户输入的数据。那么,怎么样把hello.py输出内容发送给TestInput.py,最后TestInput.py打印接收到的”hello, world!”。下面我来逐步讲解一下shell的交互方式。
hello.py代码如下:
TestInput.py代码如下:
str = raw_input()
print("input string is: %s" % str)
1.os.system(cmd)
这种方式只是执行shell命令,返回一个返回码(0表示执行成功,否则表示失败)
print("retcode is: %s" % retcode);
retcode is: 0
执行命令 并 返回该执行命令程序的 输入流或输出流. 该命令只能操作单向流,与shell命令单向交互,不能双向交互.
1)返回程序输出流,用fouput变量连接到输出流
result = fouput.readlines()
print("result is: %s" % result);
输出:
2)返回输入流,用finput变量连接到输出流
finput.write("how are you\n")
3.利用subprocess模块
1) subprocess.call()
类似os.system(),注意这里的”shell=True”表示用shell执行命令,而不是用默认的os.execvp()执行。
print f
输出:
2) subprocess.Popen()
利用Popen可以是实现双向流的通信,可以将一个程序的输出流发送到另外一个程序的输入流.
Popen()是Popen类的构造函数,communicate()返回元组(stdoutdata, stderrdata).
p2 = Popen("python TestInput.py", stdin =p1.stdout, stdout = PIPE, shell=True)
#其他方式
#print p2.stdout.readlines()
输出:
整合代码如下:
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与shell交互方式
- Python与shell的交互方式
- [Python]与shell交互
- Python与shell的3种交互方式介绍
- awk 与 shell 交互方式
- Shell 与Python的交互
- python 与ADB shell交互
- shell脚本与Oracle交互方式
- shell脚本与Oracle交互方式
- shell 与 sqlplus 交互
- PHP与Shell交互
- shell 与 sqlplus 交互
- shell 与 sqlplus 交互
- shell 与 sqlplus 交互
- PHP与Shell交互
- Python 与 C/C++ 交互的几种方式
- Python 与 C/C++ 交互的几种方式
- AWK----awk与shell交互
- 分区表--分裂分区
- 学习java基础之关键字static
- Hessian
- hdu5113 Black And White--DFS & 剪枝
- socket()
- Python与shell交互方式
- 04.2#R基础(系统2)-R的构建子集
- CentOS 7 64位操作系统,自建加密聊天环境Openfire XMPP服务
- jQuery选择器对select框选中值的写法!
- MySQL的慢查询设置
- 实现iOS中发起异步网络请求,需要等待其返回的数据才能执行下一步操作
- PHP安全编程之跨站请求伪造CSRF的防御
- IP地址、子网掩码、网关
- (十八)maven实践-使用profile实现多环境可移植构建