summaryrefslogtreecommitdiffstats
path: root/Monitoring/MonitoringService/Driver/LocalExec.py
blob: 2cf4f8ff57a3b3a81e8e26f1f7bc956d70aa411e (plain)
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
'''
Created on Feb 4, 2013

@author: steger, jozsef
@organization: ELTE
@contact: steger@complex.elte.hu
'''

#TODO: nested command execution is not working properly: e.g.: echo `hostname`

from Driver import Driver
from subprocess import Popen, PIPE

class LocalExec(Driver):
    '''
    @summary: implements a driver to execute local commands
    @ivar command: the default command
    @type command: str
    @ivar p: the process api
    @type p: subprocess.Popen or None
    '''

    def __init__(self, command = "echo -n helloworld"):
        '''
        @summary: save a default command
        @param command: the default command
        @type command: str
        '''
        self.command = command
        self.p = None

    def __del__(self):
        '''
        @summary: an implicit deletion of the driver triggers a kill signal on a running process
        '''
        if self.p:
            self.p.kill()
            self.p = None
        
    def execute(self, command = None):
        '''
        @summary: executes a local command
        @param command: the command to run, if None, the default command is issued
        @type command: str or None
        @return: the standard output of the command run
        @rtype: str
        '''
        if command is None:
            command = self.command
        self.p = Popen(args = command.split(' '), stdout = PIPE, stderr = PIPE)
        stout, sterr = self.p.communicate()
        self.p = None
        self.logger.debug("executed '%s'" % (command))
        if len(sterr):
            self.logger.warning("execution '%s' failed: %s" % (command, sterr))
        return stout