-
Notifications
You must be signed in to change notification settings - Fork 0
/
sample.py
71 lines (57 loc) · 1.87 KB
/
sample.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import json
import os
import select
import shlex
import subprocess
import sys
import click
def main_call_cmd():
"""Sample to call a command and get back it's output to work with"""
code, output, error = run_cmd('hockeyapp apps list', live=False)
print('Code')
print(code)
print('Output')
print(output)
print('Error')
print(error)
print('Before data')
data = json.loads('{}'.format(output), 'utf-8')
print(data)
print('After data')
def run_cmd(cmd, live=True, readsize=2, working_dir=None, env=None):
"""Live outputs the script call and captures the output"""
if live:
click.secho(cmd, fg='white', bold=True)
if env is None:
env = os.environ
cmdargs = shlex.split(cmd)
p = subprocess.Popen(cmdargs, cwd=working_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
stdout = ''
stderr = ''
rpipes = [p.stdout, p.stderr]
while True:
rfd, wfd, efd = select.select(rpipes, [], rpipes, 1)
if p.stdout in rfd:
dat = os.read(p.stdout.fileno(), readsize)
if live:
sys.stdout.write(dat)
stdout += dat
if dat == '':
rpipes.remove(p.stdout)
if p.stderr in rfd:
dat = os.read(p.stderr.fileno(), readsize)
stderr += dat
if live:
sys.stdout.write(dat)
if dat == '':
rpipes.remove(p.stderr)
# only break out if we've emptied the pipes, or there is nothing to
# read from and the process has finished.
if (not rpipes or not rfd) and p.poll() is not None:
break
# Calling wait while there are still pipes to read can cause a lock
elif not rpipes and p.poll() is None:
p.wait()
return p.returncode, stdout, stderr
if __name__ == '__main__':
main_call_cmd()