PageRenderTime 23ms CodeModel.GetById 12ms app.highlight 7ms RepoModel.GetById 2ms app.codeStats 0ms

/lib/ansible/utils/cmd_functions.py

https://github.com/ajanthanm/ansible
Python | 59 lines | 34 code | 6 blank | 19 comment | 8 complexity | b5eedd77a0d662d0db64e4041a0cd57d MD5 | raw file
 1# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
 2#
 3# This file is part of Ansible
 4#
 5# Ansible is free software: you can redistribute it and/or modify
 6# it under the terms of the GNU General Public License as published by
 7# the Free Software Foundation, either version 3 of the License, or
 8# (at your option) any later version.
 9#
10# Ansible is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
17
18import os
19import sys
20import shlex
21import subprocess
22import select
23
24def run_cmd(cmd, live=False, readsize=10):
25
26    #readsize = 10
27
28    cmdargs = shlex.split(cmd)
29    p = subprocess.Popen(cmdargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
30    
31    stdout = ''
32    stderr = ''
33    rpipes = [p.stdout, p.stderr]
34    while True:
35        rfd, wfd, efd = select.select(rpipes, [], rpipes, 1)
36
37        if p.stdout in rfd:
38            dat = os.read(p.stdout.fileno(), readsize)
39            if live:
40                sys.stdout.write(dat)
41            stdout += dat
42            if dat == '':
43                rpipes.remove(p.stdout)
44        if p.stderr in rfd:
45            dat = os.read(p.stderr.fileno(), readsize)
46            stderr += dat
47            if live:
48                sys.stdout.write(dat)
49            if dat == '':
50                rpipes.remove(p.stderr)
51        # only break out if we've emptied the pipes, or there is nothing to
52        # read from and the process has finished.
53        if (not rpipes or not rfd) and p.poll() is not None:
54            break
55        # Calling wait while there are still pipes to read can cause a lock
56        elif not rpipes and p.poll() == None:
57            p.wait()
58
59    return p.returncode, stdout, stderr