-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubprocess_exe.py
More file actions
56 lines (49 loc) · 1.88 KB
/
subprocess_exe.py
File metadata and controls
56 lines (49 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# -*- coding: utf-8 -*-
__author__ = 'jerry'
__version__= 'v1'
__copyright__ = '2014@jerry.D'
"""
@since: 2014-07-20
@summary:
execute shell script command via creating subprocess.
python script filter STDOUT text,and split key-word that u provided to get return value.
"""
import subprocess
import sys
__BUFSIZE__ = 1024
# stdout without return value
# cmdArgsList : shell name and cmd args
# cmdArgsList=['ping','google.com','-c','10']
def subprocess_stdout(cmdArgsList):
try:
sp = subprocess.Popen(cmdArgsList,bufsize=__BUFSIZE__,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=False)
spid = sp.pid
while True:
nextLine = sp.stdout.readline()
if( nextLine == '' and sp.poll() != None):
break
sys.stdout.write(nextLine)
except Exception, e:
print e
# return value via stdout PIPE filter.
# cmdArgsList : shell name and cmd args
# cmdArgsList=['ping','google.com','-c','10']
# rvKeyword : set rvKeyword=key, 'subprocess_returnvalue' will filter text line like 'key=value',
# when 'key=value' appeared, subprocess will be terminated, and 'value' be returned.
def subprocess_returnvalue(cmdArgsList,rvKeyword):
try:
sp = subprocess.Popen(cmdArgsList,bufsize=__BUFSIZE__,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=False)
spid = sp.pid
while True:
nextLine = sp.stdout.readline()
if( nextLine == '' and sp.poll() != None):
break
resultArray = nextLine.split('%s='%rvKeyword)
if len(resultArray) == 2:
sp.terminate()
return resultArray[1]
except Exception, e:
print e
if __name__ == '__main__':
cmdList=['ping','baidu.com','-c','100']
print subprocess_returnvalue(cmdList,'time')