Как исправить эту ошибку типа "не могу выбрать объекты модуля", пытаясь собрать твиты из API - PullRequest
0 голосов
/ 18 апреля 2019

Я пытался заставить этот код (предоставленный на github) работать для потоковой передачи учетных записей с использованием API.Но это дает мне ошибку.Это связано со строкой кода, "p.start ()".Я не могу выяснить, что на самом деле вызывает эту ошибку и как я могу ее исправить.

Engine (mysql: // root: *** @ localhost: 3306 / local) Traceback (последний вызов был последним): Файл "C: \ Users \ Hafsa \ Documents \ Hafsa \ Диссертация \ Сбор данных \ collect.py", строка 177, в main () Файл "C: \ Users \ Hafsa \ Documents \ Hafsa \ Диссертация \ Сбор данных \ collect.py ", строка 145, в главном файле p.start ()" C: \ Users \ Hafsa \ Anaconda3 \ lib \ multiprocessing \ process.py ", строка 105, в стартовом файле self._popen = self._Popen (self)"C: \ Users \ Hafsa \ Anaconda3 \ lib \ multiprocessing \ context.py", строка 223, в _Popen return _default_context.get_context (). Файл Process._Popen (process_obj) "C: \ Users \ Hafsa \ Anaconda3 \ lib \multiprocessing \ context.py ", строка 322, в _Popen возвращает Popen (process_obj) файл" C: \ Users \ Hafsa \ Anaconda3 \ lib \ multiprocessing \ popen_spawn_win32.py ", строка 65, в init сокращение.Файл дампа (process_obj, to_child) "C: \ Users \ Hafsa \ Anaconda3 \ lib \ multiprocessing \uration.py", строка 60, в дампе ForkingPickler (файл,протокол) .dump (obj) TypeError: невозможно выбрать объекты модуля Traceback (последний вызов был последним): файл "", строка 1, в файле "C: \ Users \ Hafsa \ Anaconda3 \ lib \ multiprocessing \ spawn.py", строка 99, в spawn_main new_handle = extension.steal_handle (parent_pid, pipe_handle) Файл "C: \ Users \ Hafsa \ Anaconda3 \ lib \ multiprocessing \uration.py", строка 87, в steal_handle _winapi.DUPLICATE_SAME_ACCESS |_winapi.DUPLICATE_CLOSE_SOURCE) PermissionError: [WinError 5] Доступ запрещен

def parse_args():
    # Parses the command line arguments.
    parser = argparse.ArgumentParser(
        description='Enumerate public Twitter profiles and tweets')
    parser.add_argument(
        '--max-id',
        type=int,
        help='Max Twitter ID to use for enumeration',
        default=DEFAULT_MAX_ID),
    parser.add_argument(
        '--min-id',
        type=int,
        help='Minimum ID to use for enumeration',
        default=DEFAULT_MIN_ID)
    parser.add_argument(
        '--enum-percentage',
        '-p',
        type=int,
        default=100,
        help='The percentage of 32bit account space to enumerate (0-100).')
    parser.add_argument(
        '--no-stream',
        dest='stream',
        action='store_false',
        help='Disable the streaming',
        default=True)
    parser.add_argument(
        '--no-enum',
        dest='enum',
        action='store_false',
        help='Disable the account id enumeration',
        default=True)
    parser.add_argument(
        '--stream-query',
        '-q',
        type=str,
        help='The query to use when streaming results',
        default=None)
    parser.add_argument(
        '--account-filename',
        '-af',
        type=str,
        help='The filename to store compressed account JSON data',
        default='accounts.json.gz')
    parser.add_argument(
        '--stdout',
        action='store_true',
        dest='stdout',
        help='Print JSON to stdout instead of a file',
        default=False)
    return parser.parse_args()


def main():
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        datefmt='%m/%d/%Y %I:%M:%S %p',
        level=logging.INFO)
    logger = logging.getLogger(__name__)

    args = parse_args()
    consumer_key = os.environ.get('TWEEPY_CONSUMER_KEY')
    consumer_secret = os.environ.get('TWEEPY_CONSUMER_SECRET')
    access_token = os.environ.get('TWEEPY_ACCESS_TOKEN')
    access_token_secret = os.environ.get('TWEEPY_ACCESS_TOKEN_SECRET')

    if not (consumer_key and consumer_secret and access_token
            and access_token_secret):
        logger.error('Need to specify the OAuth configuration.')
        sys.exit(1)

    user_auth = OAuthHandler(consumer_key, consumer_secret)
    user_auth.set_access_token(access_token, access_token_secret)
    user_api = API(
        user_auth, wait_on_rate_limit_notify=True, wait_on_rate_limit=True)

    api_auth = AppAuthHandler(consumer_key, consumer_secret)
    app_api = API(
        api_auth, wait_on_rate_limit_notify=True, wait_on_rate_limit=True)

    account_queue = RedisQueue('accounts')
    lookup_queue = RedisQueue('lookup')

    streamer_class = JSONStreamer
    if args.stdout:
        streamer_class = StdoutStreamer

    account_streamer = streamer_class(args.account_filename)

    processes = []

    if args.stream:
        stream_process = Process(
            target=start_streamer,
            args=[user_api, account_queue, lookup_queue],
            kwargs={'query': args.stream_query})
        processes.append(stream_process)
    else:
        logger.info('Skipping stream')

    if args.enum:
        enumerate_process = Process(
            target=fetch_accounts,
            args=[user_api, account_queue],
            kwargs={
                'min_id': args.min_id,
                'max_id': args.max_id,
                'percentage': args.enum_percentage
            })
        processes.append(enumerate_process)
    else:
        logger.info('Skipping enum')

    lookup_account_process = Process(target=start_lookup, args=[app_api, lookup_queue, account_queue])
    processes.append(lookup_account_process)


    for p in processes:
        p.start()

    # The main loop's job is simple - it simply fetches account dicts coming
    # from the various processes and saves them to the database so the tweet
    # fetcher can process them.
    try:
        account_count = 0
        while True:
            try:
                account = account_queue.get()
                # Verify the account isn't already in our database
                if Account.exists(account['id']):
                    continue
                account_count += 1
                if account_count % CHECKIN_THRESHOLD == 0:
                    logger.info(
                        'Accounts discovered: {}'.format(account_count))
                # Add the account to our database cache
                Account.from_dict(account).save()
                # Write the account to our account streamer
                account_streamer.write_row(account)
            except Exception as e:
                print('Error fetching account: {}'.format(e))
    except KeyboardInterrupt:
        print('\nCtrl+C received. Shutting down...')
        for p in processes:
            p.terminate()
            p.join()
        account_streamer.close()


if __name__ == '__main__':
    main()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...