1
- import subprocess , os , time
1
+ import subprocess , os , time , json , psutil
2
2
from browserstack .local_binary import LocalBinary
3
3
from browserstack .bserrors import BrowserStackLocalError
4
4
@@ -17,12 +17,17 @@ def __xstr(self, key, value):
17
17
return ['-' + key , value ]
18
18
19
19
def _generate_cmd (self ):
20
- cmd = [self .binary_path , '-logFile' , self .local_logfile_path , self .key ]
20
+ cmd = [self .binary_path , '-d' , 'start' , '- logFile' , self .local_logfile_path , self .key ]
21
21
for o in self .options .keys ():
22
22
if self .options .get (o ) is not None :
23
23
cmd = cmd + self .__xstr (o , self .options .get (o ))
24
24
return cmd
25
25
26
+ def _generate_stop_cmd (self ):
27
+ cmd = self ._generate_cmd ()
28
+ cmd [2 ] = 'stop'
29
+ return cmd
30
+
26
31
def start (self , ** kwargs ):
27
32
self .options = kwargs
28
33
@@ -43,34 +48,29 @@ def start(self, **kwargs):
43
48
if "onlyCommand" in kwargs and kwargs ["onlyCommand" ]:
44
49
return
45
50
46
- self .proc = subprocess .Popen (self ._generate_cmd (), stdout = subprocess .PIPE )
47
- self . stderr = self .proc .stderr
51
+ self .proc = subprocess .Popen (self ._generate_cmd (), stdout = subprocess .PIPE , stderr = subprocess . PIPE )
52
+ ( out , err ) = self .proc .communicate ()
48
53
49
54
os .system ('echo "" > "' + self .local_logfile_path + '"' )
50
- with open (self .local_logfile_path , 'r' ) as local_logfile :
51
- while True :
52
- line = local_logfile .readline ()
53
- if 'Error:' in line .strip ():
54
- raise BrowserStackLocalError (line )
55
- elif line .strip () == 'Press Ctrl-C to exit' :
56
- break
55
+ try :
56
+ if out :
57
+ data = json .loads (out .decode ())
58
+ else :
59
+ data = json .loads (err .decode ())
57
60
58
- while True :
59
- if self .isRunning ():
60
- break
61
- time .sleep (1 )
61
+ if data ['state' ] != "connected" :
62
+ raise BrowserStackLocalError (data ["message" ])
63
+ else :
64
+ self .pid = data ['pid' ]
65
+ except ValueError :
66
+ raise BrowserStackLocalError ('Error parsing JSON output from daemon' )
62
67
63
68
def isRunning (self ):
64
- if (hasattr (self , 'proc' )):
65
- return True if self .proc .poll () is None else False
66
- return False
69
+ return hasattr (self , 'pid' ) and psutil .pid_exists (self .pid )
67
70
68
71
def stop (self ):
69
72
try :
70
- self .proc .terminate ()
71
- while True :
72
- if not self .isRunning ():
73
- break
74
- time .sleep (1 )
73
+ proc = subprocess .Popen (self ._generate_stop_cmd (), stdout = subprocess .PIPE , stderr = subprocess .PIPE )
74
+ (out , err ) = proc .communicate ()
75
75
except Exception as e :
76
- return
76
+ return
0 commit comments