def __init__(self, bin_dir, ports):
        self._ports = ports
        self._postgres_cmd = os.path.join(bin_dir, 'postgres')

        # init db
        init_db = os.path.join(bin_dir, 'initdb')
        self._temp_dir = tempfile.mkdtemp()
        command = init_db + ' -D ' + self._temp_dir + ' -U ' + DatabaseRunner.ADMIN_USER
        logger.debug('Running command: {command}'.format(command=command))
        os.system(command)

        # overwrite pg_hba.conf to only allow local access with password authentication
        with open(os.path.join(self._temp_dir, 'pg_hba.conf'), 'w') as fd:
            fd.write(
                '# TYPE  DATABASE        USER            ADDRESS                 METHOD\n'
                '# "local" is for Unix domain socket connections only\n'
                'local   all             {admin}                                 trust\n'
                'local   all             all                                     md5\n'
                'host    all             {admin}         127.0.0.1/32            trust\n'
                'host    all             all             127.0.0.1/32            md5\n'
                '# IPv6 local connections:\n'
                'host    all             {admin}         ::1/128                 trust\n'
                'host    all             all             ::1/128                 md5\n'.format(admin=DatabaseRunner.ADMIN_USER)
            )

        def can_connect(port):
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            return sock.connect_ex(('127.0.0.1', port)) != 0

        self.running_port = next((port for port in ports if can_connect(port)), None)
        if self.running_port is None:
            raise PyEmbedPgException('Cannot run postgres on any of these ports [{ports}]'.format(ports=', '.join((str(p) for p in ports))))

        self.proc = Popen([self._postgres_cmd, '-D', self._temp_dir, '-p', str(self.running_port)])
        logger.debug('Postgres started on port {port}...'.format(port=self.running_port))

        # Loop until the server is started
        logger.debug('Waiting for Postgres to start...')
        start = time.time()
        while time.time() - start < DatabaseRunner.TIMEOUT:
            try:
                with psycopg2.connect(database='postgres', user=DatabaseRunner.ADMIN_USER, host='localhost', port=self.running_port):
                    break
            except OperationalError:
                pass
            time.sleep(0.1)
        else:
            raise PyEmbedPgException('Cannot start postgres after {timeout} seconds'.format(timeout=DatabaseRunner.TIMEOUT))