用os.popen重定向输入或者输出python
[root@TrackerServer chapter3]# cat hello-out.py print('hello word') [root@TrackerServer chapter3]# cat hello-in.py inp=input() open('1.log','w').write('hello'+inp+'\n') [root@TrackerServer chapter3]#
读取hello-out.py脚本输出,代码以下:shell
>>> import os >>> pipe=os.popen('python3 hello-out.py') >>> pipe.read() 'hello word\n' >>> print(pipe.close()) None >>>
close方法能够获取子程序的退出状态(None表示:‘no error')spa
为hello-in.py脚本提供标准输入流,代码以下:code
>>> pipe=os.popen('python3 hello-in.py','w') >>> pipe.write('lixing\n') 7 >>> pipe.close() >>> open('1.log').read() 'hellolixing\n'
popen将命令字符串做为一个独立的进程来执行,不过只支持单向模式(输入/输出),还能够接受第三个参数来控制写文本的缓冲进程
用subprocess重定向输入输出ip
该模块提供双向流的处理(访问一个程序的输入和输出),将一个程序的输出发送到另外一程序的输入字符串