python: Handle errors when loading chained modules more properly.
[ashd.git] / python3 / scgi-wsgi3
CommitLineData
55fa3f63 1#!/usr/bin/python3
c06db49a
FT
2
3import sys, os, getopt
4import socket
5import ashd.scgi
6
7def usage(out):
1f3d7aa3 8 out.write("usage: scgi-wsgi3 [-hA] [-p MODPATH] [-T [HOST:]PORT] HANDLER-MODULE [ARGS...]\n")
c06db49a
FT
9
10sk = None
11modwsgi_compat = False
12opts, args = getopt.getopt(sys.argv[1:], "+hAp:T:")
13for o, a in opts:
14 if o == "-h":
15 usage(sys.stdout)
16 sys.exit(0)
17 elif o == "-p":
e4769c65 18 sys.path.insert(0, a)
c06db49a
FT
19 elif o == "-T":
20 sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
21 p = a.rfind(":")
22 if p < 0:
075a379e 23 bindhost = "localhost"
c06db49a
FT
24 bindport = int(a)
25 else:
26 bindhost = a[:p]
27 bindport = int(a[p + 1:])
28 sk.bind((bindhost, bindport))
29 sk.listen(32)
30 elif o == "-A":
31 modwsgi_compat = True
32if len(args) < 1:
33 usage(sys.stderr)
34 sys.exit(1)
35
36if sk is None:
37 # This is suboptimal, since the socket on stdin is not necessarily
38 # AF_UNIX, but Python does not seem to offer any way around it,
39 # that I can find.
40 sk = socket.fromfd(0, socket.AF_UNIX, socket.SOCK_STREAM)
41
42try:
43 handlermod = __import__(args[0], fromlist = ["dummy"])
55fa3f63 44except ImportError as exc:
1f3d7aa3 45 sys.stderr.write("scgi-wsgi3: handler %s not found: %s\n" % (args[0], exc.args[0]))
c06db49a
FT
46 sys.exit(1)
47if not modwsgi_compat:
48 if not hasattr(handlermod, "wmain"):
1f3d7aa3 49 sys.stderr.write("scgi-wsgi3: handler %s has no `wmain' function\n" % args[0])
c06db49a 50 sys.exit(1)
adb11d5f 51 handler = handlermod.wmain(*args[1:])
c06db49a
FT
52else:
53 if not hasattr(handlermod, "application"):
1f3d7aa3 54 sys.stderr.write("scgi-wsgi3: handler %s has no `application' object\n" % args[0])
c06db49a
FT
55 sys.exit(1)
56 handler = handlermod.application
57
58ashd.scgi.servescgi(sk, ashd.scgi.wrapwsgi(handler))