python与Shell脚本的交互
考虑这样一个问题,有hello.py脚本,输出”hello, world!”;有TestInput.py脚本,等待用户输入,然后打印用户输入的数据。那么,怎么样把hello.py输出内容发送给TestInput.py,最后TestInput.py打印接收到的”hello, world!”。下面来逐步讲解一下shell的交互方式。
python与Shell脚本的交互" alt="python与Shell脚本的交互" src="//www.dapan.cc/wp-content/uploads/2022/11/1668480339-c934454fb1b330b.jpg">
hello.py代码如下:
#!/usr/bin/python print"hello,world!"
TestInput.py代码如下:
#!/usr/bin/python str=raw_input() print("inputstringis:%s"%str)
1.os.system(cmd)
这种方式只是执行shell命令,返回一个返回码(0表示执行成功,否则表示失败)
retcode=os.system("pythonhello.py") print("retcodeis:%s"%retcode);
输出:
hello,world! retcodeis:0
2.os.popen(cmd)
执行命令并返回该执行命令程序的输入流或输出流.该命令只能操作单向流,与shell命令单向交互,不能双向交互.
返回程序输出流,用fouput变量连接到输出流
fouput=os.popen("pythonhello.py") result=fouput.readlines() print("resultis:%s"%result);
输出:
resultis:['hello,world!\n']
返回输入流,用finput变量连接到输出流
finput=os.popen("pythonTestInput.py","w") finput.write("howareyou\n")
输出:
inputstringis:howareyou
3.利用subprocess模块
subprocess.call()
类似os.system(),注意这里的”shell=True”表示用shell执行命令,而不是用默认的os.execvp()执行.
f=call("pythonhello.py",shell=True) printf
输出:
hello,world! subprocess.Popen()
利用Popen可以是实现双向流的通信,可以将一个程序的输出流发送到另外一个程序的输入流.
Popen()是Popen类的构造函数,communicate()返回元组(stdoutdata, stderrdata).
p1=Popen("pythonhello.py",stdin=None,stdout=PIPE,shell=True) p2=Popen("pythonTestInput.py",stdin=p1.stdout,stdout=PIPE,shell=True) printp2.communicate()[0] #otherway #printp2.stdout.readlines()
输出:
inputstringis:hello,world!
#!/usr/bin/python importos fromsubprocessimportPopen,PIPE,call retcode=os.system("pythonhello.py") print("retcodeis:%s"%retcode); fouput=os.popen("pythonhello.py") result=fouput.readlines() print("resultis:%s"%result); finput=os.popen("pythonTestInput.py","w") finput.write("howareyou\n") f=call("pythonhello.py",shell=True) printf p1=Popen("pythonhello.py",stdin=None,stdout=PIPE,shell=True) p2=Popen("pythonTestInput.py",stdin=p1.stdout,stdout=PIPE,shell=True) printp2.communicate()[0] #otherway #printp2.stdout.readlines()
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。