2

Ich versuche, ein Python-Skript zu starten, das Verkehrssensoren simuliert, die Daten in Echtzeit an PubSub in meinem Google senden Wolkenschale. Ich bin diesen FehlerSo beheben Sie AttributeError: 'Modul' -Objekt hat kein Attribut 'Client' beim Ausführen von Python in Google Cloud Interactive Shell

Traceback (most recent call last): 
    File "./send_sensor_data.py", line 87, in <module> 
    psclient = pubsub.Client() 
AttributeError: 'module' object has no attribute 'Client' 

Versuchte google.cloud.pubsub.__file__ ausgeführt wird, gibt es keine Duplikate. Ich habe überall gesucht und der populäre Konsens war, das pubsub-Paket in eine virtuelle Umgebung zu installieren, die ich vergeblich versucht habe. Was ich versucht habe, so weit:

  • Set VM-Status
  • Uninstalled zu reinigen und neu installiert alle Komponenten gcloud
  • Aktualisiert alle gcloud Komponenten auf die neueste Version
  • uninsalled und neu installiert Python PubSub Bibliothek
  • installiert PubSub in einem virtualenv
  • aus einem anderen Projekt versucht
  • von einem Versuchte verschiedene GCP Konto

Das ist mein Skript:

import time 
import gzip 
import logging 
import argparse 
import datetime 
from google.cloud import pubsub 

TIME_FORMAT = '%Y-%m-%d %H:%M:%S' 
TOPIC = 'sandiego' 
INPUT = 'sensor_obs2008.csv.gz' 

def publish(topic, events): 
    numobs = len(events) 
    if numobs > 0: 
     with topic.batch() as batch: 
     logging.info('Publishing {} events from {}'. 
        format(numobs, get_timestamp(events[0]))) 
     for event_data in events: 
       batch.publish(event_data) 

def get_timestamp(line): 
    # look at first field of row 
    timestamp = line.split(',')[0] 
    return datetime.datetime.strptime(timestamp, TIME_FORMAT) 

def simulate(topic, ifp, firstObsTime, programStart, speedFactor): 
    # sleep computation 
    def compute_sleep_secs(obs_time): 
     time_elapsed = (datetime.datetime.utcnow() - programStart).seconds 
     sim_time_elapsed = (obs_time - firstObsTime).seconds/speedFactor 
     to_sleep_secs = sim_time_elapsed - time_elapsed 
     return to_sleep_secs 

    topublish = list() 

    for line in ifp: 
     event_data = line # entire line of input CSV is the message 
     obs_time = get_timestamp(line) # from first column 

     # how much time should we sleep? 
     if compute_sleep_secs(obs_time) > 1: 
      # notify the accumulated topublish 
      publish(topic, topublish) # notify accumulated messages 
      topublish = list() # empty out list 

      # recompute sleep, since notification takes a while 
      to_sleep_secs = compute_sleep_secs(obs_time) 
      if to_sleep_secs > 0: 
      logging.info('Sleeping {} seconds'.format(to_sleep_secs)) 
      time.sleep(to_sleep_secs) 
     topublish.append(event_data) 

    # left-over records; notify again 
    publish(topic, topublish) 

def peek_timestamp(ifp): 
    # peek ahead to next line, get timestamp and go back 
    pos = ifp.tell() 
    line = ifp.readline() 
    ifp.seek(pos) 
    return get_timestamp(line) 


if __name__ == '__main__': 
    parser = argparse.ArgumentParser(description='Send sensor data to Cloud Pub/Sub in small groups, simulating real-time behavior') 
    parser.add_argument('--speedFactor', help='Example: 60 implies 1 hour of data sent to Cloud Pub/Sub in 1 minute', required=True, type=float) 
    args = parser.parse_args() 

    # create Pub/Sub notification topic 
    logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO) 
    psclient = pubsub.Client() 
    topic = psclient.topic(TOPIC) 
    if not topic.exists(): 
     logging.info('Creating pub/sub topic {}'.format(TOPIC)) 
     topic.create() 
    else: 
     logging.info('Reusing pub/sub topic {}'.format(TOPIC)) 

    # notify about each line in the input file 
    programStartTime = datetime.datetime.utcnow() 
    with gzip.open(INPUT, 'rb') as ifp: 
     header = ifp.readline() # skip header 
     firstObsTime = peek_timestamp(ifp) 
     logging.info('Sending sensor data from {}'.format(firstObsTime)) 
     simulate(topic, ifp, firstObsTime, programStartTime, args.speedFactor) 

Antwort

1

Die pubsub.Client Klasse existiert, bis die 0.27.0 Version des PubSub Python-Paket sehen wählen müssen. Also habe ich eine virtuelle Umgebung erstellt und die Version 0.27.0 von pubsub darin installiert. Hier sind die Befehle:

virtualenv venv 
source venv/bin/activate 
pip install google-cloud-pubsub==0.27.0 
Verwandte Themen