-->

ImportError: cannot import name Pubnub

2019-07-13 04:14发布

问题:

I am trying to control an LED on my Raspberry Pi with the Pubnub platform. I just started and I tried this tutorial:

https://www.pubnub.com/blog/2015-05-27-internet-of-things-101-getting-started-w-raspberry-pi/

However, when I want to execute a Python file that imports the Pubnub library with the following line:

from pubnub import Pubnub

I get this error message:

ImportError: cannot import name Pubnub

I did everything exactly as told in the tutorial. I even copied the .py classes from their Github repository.

This is my class:

import RPi.GPIO as GPIO
import time
import sys
from pubnub import Pubnub

GPIO.setmode (GPIO.BCM)

LED_PIN = 17

GPIO.setup(LED_PIN,GPIO.OUT)

pubnub = Pubnub(publish_key='xxxx', subscribe_key='xxxx')

channel = 'disco'

def _callback(m, channel):
        print(m)
        if m['led'] == 1:
                for i in range(6):
                    GPIO.output(LED_PIN,True)
                    time.sleep(0.5)
                    GPIO.output(LED_PIN,False)
                    time.sleep(0.5)
                    print('blink')

def _error(m):
        print(m)

pubnub.subscribe(channels=channel, callback=_callback, error=_error)

回答1:

try:

pip install pubnub

I did it and it works fine. No need to github anything. pip is available for Linux and Windows.



回答2:

If you're running into this since early November 2016; the pubnub API has changed in version 4.0.

from pubnub import Pubnub

does not work. It's now (to my best knowledge):

from pubnub.pubnub import PubNub


回答3:

I experienced the same problem on my Raspberry Pi 3. It ended up being a very silly issue! I had a file called pubnub.py which is why when I ran my script when it was located in the folder "Desktop" it didn't work. However, after I brought it up to its parent directory "pi" it imported pubnub without an issue!