```import os import sys try: from twitter.commo...
# pex
Copy code
import os
import sys

  from twitter.common import log
except ImportError:
  log = None
from twitter.common.dirutil import chmod_plus_x
from twitter.common_internal.cmd.stream import LineIterableSubprocess

from .base import WSGIServerHandler

from pyuwsgi import UWSGI_BINARY_PATH, UWSGI_BOOTSTRAP_PATH, uwsgi_context

class UwsgiServer(WSGIServerHandler):
  """uWSGI WSGI Server runner."""

  def construct_command(self, *cmd_sets):
    cmd = []
    for cmd_set in cmd_sets:
      cmd = cmd + cmd_set
    return cmd

  def run(self):
    bind_type = self.config.get('bind_type', 'http')
    worker_type = self.config.get('worker_type', 'processes')
    extra_args = self.config.get('uwsgi_args', [])

    base_args = [
      '--%s' % bind_type, '%s:%s' % (self.host, self.port),    # e.g. --http h:p, --http-socket h:p
      '--%s' % worker_type, '%s' % (self.workers or 1),        # e.g. --processes 32, --threads 50
      '--env', 'UWSGI_PEX=%s' % os.path.abspath(sys.argv[0]),  # Pass the pex path to bootstrap.py.
      '--need-app',                     # Bail if no apps are found.
      '--force-cwd', os.getcwd(),       # Set runtime working directory to cwd vs /.
      '--module', self.app,             # Load the app via path.to.module:app
      '--master',                       # Start a uWSGI master process.
      '--vacuum',                       # Clean up after ourselves on exit - remove sockets, etc.
      '--enable-metrics',               # Enable metrics.
      '--stats', 'metrics.sock'         # Bind the stats server on a local file socket in the cwd.

    # Determine output stream for uWSGI stdout/stderr.
    writer = <http://log.info|log.info> if log else lambda x: sys.stdout.write(x + '\n')

    # This creates a temp directory with the uWSGI resources for the lifetime of the context mgr.
    with uwsgi_context() as uwsgi_path:
      writer('uwsgi_path: %s' % uwsgi_path)
      writer('cwd: %s' % os.getcwd())

      base_args = ['--import', os.path.join(uwsgi_path, UWSGI_BOOTSTRAP_PATH)] + base_args

      uwsgi_binary = os.path.join(uwsgi_path, UWSGI_BINARY_PATH)
      cmd = self.construct_command([uwsgi_binary], base_args, extra_args)

      writer('running cmd: %s' % ' '.join(cmd))


      with LineIterableSubprocess(cmd) as stream:
        writer('started uwsgi (pid: %s)' % stream.pid)
        for line in stream:
👀 1