def run_command_in_existing(daemon_host, daemon_port, args, auto_start=True):
  # Prelaunched processes are DISPLAY-specific
  if sys.platform == 'darwin':
    if os.getenv('DISPLAY'):
      display = os.getenv('DISPLAY')
    else:
      display = 'cocoa'
  else:
    if os.getenv('DISPLAY'):
      display = os.getenv('DISPLAY')
    else:
      display = 'terminal';

  def existing_quickopen_port():
      conn = httplib.HTTPConnection(daemon_host, daemon_port, True)
      conn.request('GET', '/existing_quickopen/%s' % display)
      res = conn.getresponse()
      assert res.status == 200
      port = int(res.read())
      return port

  # Get the pid of an existing quickopen process via
  # quickopend. This routes through prelaunchd.py
  try:
    port = existing_quickopen_port()
  except socket.error:
    if not auto_start:
      from db_status import DBStatus
      return "%s.\n" % DBStatus.not_running_string()

    # quickopend not started; attempt once to start it automatically
    import StringIO
    try:
      # Squelch any output from starting the db
      orig_stdout = sys.stdout
      orig_stderr = sys.stderr
      sys.stdout = StringIO.StringIO()
      sys.stderr = sys.stdout

      sys.path.append(os.path.join(os.path.dirname(__file__), "../third_party/py_trace_event/"))
      import db_proxy
      db_proxy.DBProxy.try_to_start_quickopend(daemon_port)
      try:
        port = existing_quickopen_port()
      except socket.error:
        from db_status import DBStatus
        return "%s.\n" % DBStatus.not_running_string()
    finally:
      sys.stdout = orig_stdout
      sys.stderr = orig_stderr

  # Get a connection to the prelaunched process.
  # We may have to try a few times --- it may be coming up still.
  connected = False
  s = None
  for i in range(20): # 5 seconds
    try:
      s = socket.socket()
      s.connect((daemon_host, port))
      break
    except:
      time.sleep(0.25)
  if not s:
    raise Exception("Could not connect to the provided process.")
  try:
    f = s.makefile()

    # Send our commandline to the existing quickopend. Pass with it our
    # daemon_host and daemon_port so that it tries talking to the same quickopend
    # instance as us.
    full_args = list(args)
    full_args.extend(["--host=%s" % daemon_host])
    full_args.extend(["--port=%s" % str(daemon_port)])
    f.write(repr(full_args))
    f.write("\n")
    f.flush()

    # Wait for the result of the quickopening. It comes over as a repr'd string
    # so eval it to get the real multi-line string.
    l = eval(f.readline(), {}, {})
    return l
  finally:
    s.close()
dataset/ETHPy150Open natduca/quickopen/src/prelaunch_client.py/run_command_in_existing/original