用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
該模塊提供雙向流的處理(訪問一個程序的輸入和輸出),將一個程序的輸出發送到另外一程序的輸入字符串