File: execute-json-from-fifo

package info (click to toggle)
subuser 0.6.2-3.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,216 kB
  • sloc: python: 5,204; sh: 380; makefile: 73; javascript: 43
file content (86 lines) | stat: -rwxr-xr-x 2,163 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# This file is copyright Timothy Hobbs
# And is released under the LGPL-3.0 license

import json
import subprocess
import fileinput
import sys
import optparse

usage = "usage: execute-json-from-fifo PATH_TO_NAMED_PIPE"
description = """
This is a very simple script which executes commands passed as JSON to a given named pipe.

To launch this script run:

$ execute-json-from-fifo PATH_TO_NAMED_PIPE

The protocol is as follows:

{
  "command":["echo","some","command"],
  "stdin":"path",
  "stdout":"path",
  "stderr":"path",
  "cwd":"path"
  "env":{"ENVVAR":"value"}
}

``stdin``,``stdout``,``stderr``,``cwd`` and ``env`` are all optional.

Passing ``["exit"]`` to command stops the script.
"""


parser=optparse.OptionParser(usage=usage,description=description)
options,args = parser.parse_args()

while True:
  with open(args[0],"r") as fd:
    for line in fd:
      print(line)
      try:
        rpc = json.loads(line)
      except ValueError as e:
        print(e)
        continue
      if "stdin" in rpc:
        stdin = open(rpc["stdin"],"r+")
        del rpc["stdin"]
      else:
        stdin = open("/dev/null","r")
      if "stdout" in rpc:
        stdout = open(rpc["stdout"],"w")
        del rpc["stdout"]
      else:
        stdout = open("/dev/null","w")
      if "stderr" in rpc:
        stderr = open(rpc["stderr"],"w")
        del rpc["stderr"]
      else:
        stderr = open("/dev/null","w")
      cwd = None
      if "cwd" in rpc:
        cwd = rpc["cwd"]
        del rpc["cwd"]
      env = None
      if "env" in rpc:
        env = rpc["env"]
        del rpc["env"]
      if "command" in rpc:
        command = rpc["command"]
        del rpc["command"]
      else:
        print("Warning, no command specified.")
        continue
      if rpc != {}:
        print("Warning, unsupported options passed "+str(rpc))
      if command == ["exit"]:
        sys.exit()
      else:
        try:
          subprocess.Popen(command,stdin=stdin,stdout=stdout,stderr=stderr,cwd=cwd,env=env,close_fds=True)
        except FileNotFoundError:
          print("Warning, command "+str(command)+" not found.")