温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么理解Python与Shell脚本的交互

发布时间:2020-08-25 10:12:22 来源:亿速云 阅读:165 作者:Leah 栏目:编程语言

怎么理解Python与Shell脚本的交互?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

考虑这样一个问题,有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()

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI