File: cmdqueue.py

package info (click to toggle)
xxdiff 1%3A4.0.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 4,716 kB
  • ctags: 2,245
  • sloc: cpp: 18,495; python: 6,134; sh: 1,543; ansic: 1,535; perl: 308; lex: 284; yacc: 279; lisp: 250; tcl: 213; makefile: 82
file content (178 lines) | stat: -rw-r--r-- 5,831 bytes parent folder | download | duplicates (5)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#!/usr/bin/env python
#******************************************************************************\
#* $Source$
#* $Id$
#*
#* Copyright (C) 2001-2002, Martin Blais <blais@furius.ca>
#*
#* This program is free software; you can redistribute it and/or modify
#* it under the terms of the GNU General Public License as published by
#* the Free Software Foundation; either version 2 of the License, or
#* (at your option) any later version.
#*
#* This program is distributed in the hope that it will be useful,
#* but WITHOUT ANY WARRANTY; without even the implied warranty of
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#* GNU General Public License for more details.
#*
#* You should have received a copy of the GNU General Public License
#* along with this program; if not, write to the Free Software
#* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#*
#*****************************************************************************/

"""Implements a command queue.

Implement a queue for commands, where only a given number of commands is allowed
to run at the same time and we wait for the run commands to finish before
starting a new one.

Implementation note: we do not use Python threading capabilities because of
annoying behaviour related to interruptibility of subprocesses. You will need to
poll occasionnally to let this queue execute some of its command before being
destroyed. The queue empties itself (i.e. runs commands) automatically when
destroyed.
"""

__version__ = "$Revision$"
__author__ = "Martin Blais <blais@furius.ca>"

#===============================================================================
# EXTERNAL DECLARATIONS
#===============================================================================

import sys, os
import time

from pprint import pprint, pformat

#===============================================================================
# PUBLIC FUNCTIONS
#===============================================================================

#===============================================================================
# CLASS Command
#===============================================================================

class Command:
    """Just a class to hold information about a command."""

    def __init__(self, command):
        self.command = command # this is in fact a list of arguments
        self.pid = None
        self.interruptible = 1

#===============================================================================
# CLASS CmdQueue
#===============================================================================

class CmdQueue:
    """Command queue object."""

    def __init__(self, nbcmds=1):
        self.nbcmds = nbcmds
        self.waiting = []
        self.running = []
        self.done = []
        self.waitingForAll = 0

    def __del__(self):
        try:
            self.waitAll()
        except KeyboardInterrupt:
            pass
        
    def queue(self, cmdl, cmdobj=None):
        """Queues a command to be run.
        If cmdobj is specified, methods preRun() and postRun() are called before and after
        running the command, respectively."""
        cmd = Command(cmdl)
        cmd.cmdobj = cmdobj
        self.waiting.append(cmd)

    def poll(self):
        """Run this command periodically."""
        for cmd in self.running:
            if self.wait(cmd):
                self.running.remove(cmd)
                self.done.append(cmd)
                cmd.cmdobj.postRun(self)
        if len(self.running) >= self.nbcmds:
            return

        while len(self.running) < self.nbcmds and len(self.waiting) > 0:
            cmd = self.waiting.pop(0)
            self.running.append(cmd)
            cmd.cmdobj.preRun(self)
            self.run(cmd)

    def waitAll(self):
        self.waitingForAll = 1
        self.poll()
        while len(self.running) > 0 or len(self.waiting) > 0:
            os.wait()
            self.poll()
        self.waitingForAll = 0
            
    def run(self, cmd):
        cmd.pid = os.fork()
        if cmd.pid == 0:
            return os.execvp(cmd.command[0], cmd.command)

    def wait(self, cmd):
        try:
            (id, status) = os.waitpid(cmd.pid, os.WNOHANG)
            if id:
                return os.WIFSTOPPED(status) or os.WIFSIGNALED(status) or \
                       os.WIFEXITED(status)
        except OSError, e:
            import errno
            if e.errno == errno.ECHILD:
                return 1
        return 0


#===============================================================================
# CLASS SyncFakeQueue
#===============================================================================

class SyncFakeQueue:
    """Fake command queue which is in fact synchronous."""

    def __init__(self, nbcmds=1):
        self.nbcmds = nbcmds

    def queue(self, cmdl, cmdobj):
        """Queues a command to be run."""
        pid = os.fork()
        cmdobj.preRun(self)
        if pid == 0:
            return os.execvp(cmdl[0], cmdl)
        else:
            os.waitpid(pid, 0)
        cmdobj.postRun(self)

    def poll(self):
        pass


#===============================================================================
# TESTS
#===============================================================================

def selftest():
    """Self-test."""
    print "Performing tests."

    queue = CmdQueue(2)
    queue.queue('xxdiff /users/blais/xxdiff/src/mine /users/blais/xxdiff/src/older')
    queue.queue('xxdiff /users/blais/xxdiff/src/mine /users/blais/xxdiff/src/yours')
    queue.queue('xxdiff /users/blais/xxdiff/src/mine /users/blais/xxdiff/src/older')
    queue.queue('xxdiff /users/blais/xxdiff/src/mine /users/blais/xxdiff/src/yours')
    


# Run main if loaded as a script
if __name__ == "__main__":
    selftest()