subprocess模块的使用
1、调用本地shell脚本
[root@133 systeminformation]# cat test.sh #!/bin/bash echo "hello world!" In [1]: from subprocess import Popen,PIPE In [2]: p=Popen('./test.sh',shell=True) hello world!
2、p1的输出作为p2的输入(PIPE即是管道)
In [15]: p1 = Popen(['ls'],stdout=PIPE) In [16]: p2 = Popen(['grep','py'],stdin=p1.stdout,stdout=PIPE) In [17]: result = p2.stdout In [18]: for i in result:print i 10_httpd.py 1_md5.py 1_walk.py ErrorExcept.py hashlib2.py isNum.py process_check_call.py subprocess.py subprocess.pyc top10.py walk1.py yield1.py yield2.py
p.communicate()方法相当于p.stdin.write()、p.stdin.close()和p.stdout.read()这3个方法
p.communicate返回的是两个元素的元祖
In [29]: p = Popen(['cat'],stdin=PIPE,stdout=PIPE) In [30]: p.communicate('abc') Out[30]: ('abc', None)
In [19]: p = Popen(['wc'],stdin=PIPE,stdout=PIPE,stderr=PIPE) In [20]: p.terminate() In [21]: p.wait() Out[21]: -15 In [22]: p.wait() Out[22]: -15 In [23]: p.wait() Out[23]: -15 In [24]: p.pid Out[24]: 6241 In [25]: p.returncode Out[25]: -15 In [43]: help(p1.wait) Help on method wait in module subprocess: wait(self) method of subprocess.Popen instance Wait for child process to terminate. Returns returncode attribute. ~ In [44]: help(p1.returncode) Help on NoneType object: class NoneType(object) | Methods defined here: | | __hash__(...) | x.__hash__() <==> hash(x) | | __repr__(...) | x.__repr__() <==> repr(x) (END)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。