Debian Codegraph @

lib/dbtexmf/core/commander.py

raw
1 import os
2 from subprocess import Popen, PIPE
3 from io import open
4
5 class Command:
6 """Contains the needed data to run a command"""
7 def __init__(self, args, stdin=None, stdout=None, shell=False):
8 self.arguments = args
9 self.stdin = stdin
10 self.stdout = stdout
11 self.shell = shell
12
13 class CommandRunner:
14 """
15 Execute the differents registered commands in the specified order,
16 either independantly or as a pipe process chain if required
17 """
18 def __init__(self, module_name="", log=None):
19 self.module_name = module_name
20 self.commands = []
21 self.processes = []
22 self.log = log
23
24 def info(self, text):
25 if self.log: self.log.info(text)
26
27 def set_name(self, module_name):
28 self.module_name = module_name
29
30 def add_command(self, args, stdin=None, stdout=None, shell=False):
31 command = Command(args, stdin, stdout, shell)
32 self.commands.append(command)
33 return command
34
35 def shcmd(self, args):
36 nargs = []
37 for arg in args:
38 if len(arg.split()) > 1: arg = '"%s"' % arg
39 nargs.append(arg)
40 return " ".join(nargs)
41
42 def run(self, kw=None):
43 if not(self.commands):
44 return
45 if not(kw): kw = {}
46 pipe_top = False
47 rc = 0
48 for cmd in self.commands:
49 if rc != 0:
50 break
51 stdin, stdout = None, None
52 prev_pipe = None
53 if cmd.stdin == "PIPE":
54 if self.processes:
55 prev_pipe = self.processes[-1]
56 stdin = prev_pipe.stdout
57 else:
58 pipe_top = True
59 stdin = PIPE
60 if cmd.stdout == "PIPE":
61 stdout = PIPE
62 elif cmd.stdout:
63 stdout = open(cmd.stdout % kw, "wb")
64
65 if kw: args = [a % kw for a in cmd.arguments]
66 else: args = cmd.arguments
67
68 self.info(" ".join(args))
69 # Some commands work only in shell env (e.g. links), so take care
70 if cmd.shell:
71 p = Popen(self.shcmd(args), stdin=stdin, stdout=stdout,
72 shell=True)
73 else:
74 p = Popen(args, stdin=stdin, stdout=stdout)
75 self.processes.append(p)
76
77 if stdin and prev_pipe:
78 # Close stdout to allow <prev_pipe> receiving SIGPIPE
79 prev_pipe.stdout.close()
80 if stdout != PIPE:
81 # Wait until the process is finished if not in a pipe chain
82 rc = p.wait()
83 if stdout: stdout.close()
84
85 return rc
86