知行编程网知行编程网  2022-11-24 15:00 知行编程网 隐藏边栏  67 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于Python与Shell脚本的交互的相关知识,包括Python图形界面,以及python shell脚本这些编程知识,希望对大家有参考作用。

考虑这样一个问题,有hello.py脚本,输出”hello, world!”;有TestInput.py脚本,等待用户输入,然后打印用户输入的数据。那么,怎么样把hello.py输出内容发送给TestInput.py,最后TestInput.py打印接收到的”hello, world!”。下面来逐步讲解一下shell的交互方式。

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

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享