Rectangle 27 2

if Connection_Type == '1':
    conn = 'Telnet()' 
elif Connection_Type == '2':
    conn = 'SSH2()'
'Telnet()'.connect
'SSH2()'.connect

If you have imported SSH or Telnet from somewhere and presuming they are classes then remove the single quotes and you will create an instance which should work once the classes have a connect method.

if Connection_Type == '1':
    conn = Telnet()
elif Connection_Type == '2':
    conn = SSH2()

yes, conn is string type variable and string variable do not have connect method.

Thanks guys. Made perfect sense once it was pointed out to me.

Python EXscript - AttributeError: 'str' object has no attribute 'conne...

python
Rectangle 27 1

How about simply checking if your dictionary value does provide the method/attribute you need?

for keys in interfaces:
      counters = interfaces[keys].get(u'interfaceCounters', {})
      if hasattr(counters, 'get'): 
          # Only print if counters supports `get`
          print keys, "inOctets:", counters.get(u'inOctets', {}), "outOctets:", counters.get(u'outOctets',  {})

Thank you I love this fix, very helpful for what we are doing with gathering nested output from switches.

Cheers, but performance wise Martijn Pieters answer is better, but less explicit ;-)

python - AttributeError: 'str' object has no attribute 'get' - Stack O...

python
Rectangle 27 1

If some of your interfaceCounters keys reference a string instead of a nested dictionary, just use exception handling to ignore those:

for keys in interfaces:
    counters = interfaces[keys].get(u'interfaceCounters', {})
    try:
        print keys, "inOctets:", counters.get(u'inOctets', {}), "outOctets:", counters.get(u'outOctets',  {})
    except AttributeError:
        # counters is not a dictionary, ignore and move on
        pass

This is the ask forgiveness principle; if most of your entries do have the .get() method this is simply faster than the look before you leap principle, where you test if the method is available.

@Wilken: glad we were both of help! Note that you can only mark one of the answers as accepted; pick the one you feel helped you the best! (And yes, it is fine if that is SmCaterpillar's answer, it is your choice).

I've been going back and forth on which one to choose, Both are very good answers that help a lot!

python - AttributeError: 'str' object has no attribute 'get' - Stack O...

python
Rectangle 27 3

Looks like you have a typo:

driver = webdriver.PhantomJS=("c:|phantomjs-2.1.1/windows/bin/phantomjs")
                            ^

web scraping - Python AttributeError: 'str' object has no attribute 'g...

python web-scraping attributes
Rectangle 27 2

Your assumption that runAnalytics is running is correct since the function is executed when binding it to the button the way you did.

According to the effbot docs you need to use a lambda function in order to bind a function with passed arguments to a button like this:

import tkinter

def test_func(val):
    print(type(val))
    print(val)
    share_id = val.get()
    print(share_id)


loadApplication = tkinter.Tk()
loadApplication.title("Stock Analytics")
loadApplication.geometry("1080x720")

label1 = tkinter.Label(loadApplication, text = "Ticker")
input1 = tkinter.Entry(loadApplication)

loadAnalytics = tkinter.Button(loadApplication, text="Load Analytics", command=lambda: test_func(input1))


loadAnalytics.pack()
label1.pack()
input1.pack()

loadApplication.mainloop()

However, there is a second thing to keep in mind:

input1 = tkinter.Entry(loadApplication)

creates an Entry widget called input1 which is then passed to the function. The thing is that input1 does not contain the string you typed into the entry widget but a reference to the widget (widget ID). In order to get the widget's content you need to call its .get() method as shown in my code snippet.

Okay thank you! That fixed the issue of them both running! As I said earlier, I am new to this. Can you explain what the "def test_func(val): print(val)" is doing?

I commented it out and the program still ran.

You need to bind a callback function to a button which is executed whenever the button is clicked. Since I was in need of a simple sample callback and do not have the yahoo_fincance module installed on my system I decided to go this way. The porgramm code is not updated 'on-line' like live-reloading. So to make any changes working and see what's the difference you need to start and restart the whole script.

After reading your edit, I changed ticker = Share(input1) to ticker = Share(input1.get()) and my problem was resolved! I wish I could upvote your answer twice. Thank you so much, I was working on this all day and the simplest error got me tied up. @albert

string - Python AttributeError: 'str' object has no attribute 'get_pri...

python string tkinter python-3.5 attributeerror
Rectangle 27 5

Edit After reading the stacktrace again, you can see that urllib3 tries to import something from the http module. Your file is called http.py and is thus imported instead of the expected one.

The actual error happens because of the circular nature of the import. Since requests hasn't finished importing completely yet. The get function in requests isn't defined yet when the http import reaches import requests again.

Note: You will also want to always guard your entry point with the if __name__ == '__main__' construct. This will often avoid nasty errors for unsuspecting future developers (including yourself).

@Bruce ah sorry, I was close though. I just noticed that urllib3 does an from http.client import HTTPConnection, HTTPException. It seems your http.py file is shadowing that instead? Try renaming it.

Yes! That was it! Thanks for the advice.

'module' object has no attribute 'post'
email.py

python - AttributeError: 'module' object has no attribute - Stack Over...

python python-requests attributeerror
Rectangle 27 124

I'm adding this solution for people who make the same mistake as I did.

In most cases: rename your project file 'serial.py' and delete serial.pyc if exists, then you can do simple 'import serial' without attribute error.

Wow, didn't see that coming. Spent 45 minutes pulling hair out.

Additional point for GAE users - try flushing memcache. Somehow ran into this and got stumped for ages after moving a model to a different file. Not sure what was cached that caused it, but it flush fixed it.

AttributeError: 'module' object has no attribute 'SerialException

Python AttributeError: 'module' object has no attribute 'Serial' - Sta...

python serial-port raspberry-pi
Rectangle 27 119

I'm adding this solution for people who make the same mistake as I did.

In most cases: rename your project file 'serial.py' and delete serial.pyc if exists, then you can do simple 'import serial' without attribute error.

Wow, didn't see that coming. Spent 45 minutes pulling hair out.

Additional point for GAE users - try flushing memcache. Somehow ran into this and got stumped for ages after moving a model to a different file. Not sure what was cached that caused it, but it flush fixed it.

AttributeError: 'module' object has no attribute 'SerialException

Python AttributeError: 'module' object has no attribute 'Serial' - Sta...

python serial-port raspberry-pi
Rectangle 27 64

I had the same problem several times while importing modules. I don't understand why it does work in some cases (for instance when you look at some examples in the serial website)

I tried. not work. The error will be "ImportError: cannot import name serial"

This looks utterly wrong, sorry. At first the class is Serial not serial, then you don't have to import a class to use it. module.class() should work very fine. Last but not least there is no real explanation for what's going on here at all.

Python AttributeError: 'module' object has no attribute 'Serial' - Sta...

python serial-port raspberry-pi
Rectangle 27 62

I had the same problem several times while importing modules. I don't understand why it does work in some cases (for instance when you look at some examples in the serial website)

I tried. not work. The error will be "ImportError: cannot import name serial"

This looks utterly wrong, sorry. At first the class is Serial not serial, then you don't have to import a class to use it. module.class() should work very fine. Last but not least there is no real explanation for what's going on here at all.

Python AttributeError: 'module' object has no attribute 'Serial' - Sta...

python serial-port raspberry-pi
Rectangle 27 5

for root, dirs, files in os.walk(directory):
    for file in files:
        floc = file
        im = Image.open(str(directory) + '\\' + floc)
        pix = np.array(im.getdata())
        pixels.append(pix)
        labels.append(1)   # append(i)???

So far ok. But you want to leave pixels as a list until you are done with the iteration.

pixels = np.array(pixels)
labels = np.array(labels)

You had this indention right in your other question. What happened? previous

Iterating, collecting values in a list, and then at the end joining things into a bigger array is the right way. To make things clear I often prefer to use notation like:

alist = []
for ..
    alist.append(...)
arr = np.array(alist)

If names indicate something about the nature of the object I'm less likely to get errors like yours.

I don't understand what you are trying to do with traindata. I doubt if you need to build it during the loop. pixels and labels have the basic information.

traindata = np.array([traindata[i][i],traindata[1]], dtype=object)

comes from the previous question. I'm not sure you understand that answer.

traindata = []
traindata.append(pixels)
traindata.append(labels)

if done outside the loop is just

traindata = [pixels, labels]

labels is a 1d array, a bunch of 1s (or [0,1,2,3...] if my guess is right). pixels is a higher dimension array. What is its shape?

Stop right there. There's no point in turning that list into an array. You can save the list with pickle.

You are copying code from an earlier question, and getting the formatting wrong. cPickle very large amount of data

Python - AttributeError: 'numpy.ndarray' object has no attribute 'appe...

python numpy pickle
Rectangle 27 5

for root, dirs, files in os.walk(directory):
    for file in files:
        floc = file
        im = Image.open(str(directory) + '\\' + floc)
        pix = np.array(im.getdata())
        pixels.append(pix)
        labels.append(1)   # append(i)???

So far ok. But you want to leave pixels as a list until you are done with the iteration.

pixels = np.array(pixels)
labels = np.array(labels)

You had this indention right in your other question. What happened? previous

Iterating, collecting values in a list, and then at the end joining things into a bigger array is the right way. To make things clear I often prefer to use notation like:

alist = []
for ..
    alist.append(...)
arr = np.array(alist)

If names indicate something about the nature of the object I'm less likely to get errors like yours.

I don't understand what you are trying to do with traindata. I doubt if you need to build it during the loop. pixels and labels have the basic information.

traindata = np.array([traindata[i][i],traindata[1]], dtype=object)

comes from the previous question. I'm not sure you understand that answer.

traindata = []
traindata.append(pixels)
traindata.append(labels)

if done outside the loop is just

traindata = [pixels, labels]

labels is a 1d array, a bunch of 1s (or [0,1,2,3...] if my guess is right). pixels is a higher dimension array. What is its shape?

Stop right there. There's no point in turning that list into an array. You can save the list with pickle.

You are copying code from an earlier question, and getting the formatting wrong. cPickle very large amount of data

Python - AttributeError: 'numpy.ndarray' object has no attribute 'appe...

python numpy pickle
Rectangle 27 13

sudo python -m pip install serial
sudo python -m pip install pyserial

If the previously mentioned solutions did not work for you, double check if you installed the correct library.

Python AttributeError: 'module' object has no attribute 'Serial' - Sta...

python serial-port raspberry-pi
Rectangle 27 3

Numpy arrays do not have an append method. Use the Numpy append function instead:

import numpy as np

array_3 = np.append(array_1, array_2, axis=n)
# you can either specify an integer axis value n or remove the keyword argument completely

For example, if array_1 and array_2 have the following values:

array_1 = np.array([1, 2])
array_2 = np.array([3, 4])

If you call np.append without specifying an axis value, like so:

array([1, 2, 3, 4])

Else, if you call np.append with an axis value of 0, like so:

array_3 = np.append(array_1, array_2, axis=0)

array_3 will have the following value:

array([[1, 2],
        [3, 4]])

He could also avoid converting the lists to arrays during the loop (i.e. move pixels = np.array(pixels) to end of loop)

Don't use np.append, especially not in a loop. It is inefficient.

Python - AttributeError: 'numpy.ndarray' object has no attribute 'appe...

python numpy pickle
Rectangle 27 3

Numpy arrays do not have an append method. Use the Numpy append function instead:

import numpy as np

array_3 = np.append(array_1, array_2, axis=n)
# you can either specify an integer axis value n or remove the keyword argument completely

For example, if array_1 and array_2 have the following values:

array_1 = np.array([1, 2])
array_2 = np.array([3, 4])

If you call np.append without specifying an axis value, like so:

array([1, 2, 3, 4])

Else, if you call np.append with an axis value of 0, like so:

array_3 = np.append(array_1, array_2, axis=0)

array_3 will have the following value:

array([[1, 2],
        [3, 4]])

He could also avoid converting the lists to arrays during the loop (i.e. move pixels = np.array(pixels) to end of loop)

Don't use np.append, especially not in a loop. It is inefficient.

Python - AttributeError: 'numpy.ndarray' object has no attribute 'appe...

python numpy pickle
Rectangle 27 115

You have mutual top-level imports, which is almost always a bad idea.

If you really must have mutual imports in Python, the way to do it is to import them within a function:

# In b.py:
def cause_a_to_do_something():
    import a
    a.do_something()

Now a.py can safely do import b without causing problems.

(At first glance it might appear that cause_a_to_do_something() would be hugely inefficient because it does an import every time you call it, but in fact the import work only gets done the first time. The second and subsequent times you import a module, it's a quick operation.)

Thank you! I know for the first time that importing in different places make such a difference.

Please be aware that this adds over-head when the function is called, as you put the import logic at function call time, rather than program load time.

Interesting; I wonder why the interpreter does not give a proper error message in this case?

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 114

You have mutual top-level imports, which is almost always a bad idea.

If you really must have mutual imports in Python, the way to do it is to import them within a function:

# In b.py:
def cause_a_to_do_something():
    import a
    a.do_something()

Now a.py can safely do import b without causing problems.

(At first glance it might appear that cause_a_to_do_something() would be hugely inefficient because it does an import every time you call it, but in fact the import work only gets done the first time. The second and subsequent times you import a module, it's a quick operation.)

Thank you! I know for the first time that importing in different places make such a difference.

Please be aware that this adds over-head when the function is called, as you put the import logic at function call time, rather than program load time.

Interesting; I wonder why the interpreter does not give a proper error message in this case?

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 1

line is a string and you've only rebound the adict name to the stripped string, so you don't have a dict, but a string.

You can instead use ast.literal_eval to build your dictionary from the inputted string:

import ast

adict = ast.literal_eval(input())

Python 3 - Dictionary.items str object has no attribute items error - ...

python python-3.x dictionary
Rectangle 27 60

I have also seen this error when inadvertently naming a module with the same name as one of the standard Python modules. E.g. I had a module called commands which is also a Python library module. This proved to be difficult to track down as it worked correctly on my local development environment but failed with the specified error when running on Google App Engine.

I used abc.py to write a test to demonstrate the import behavior in python, that bites me a lot...

I suspected this and deleted the .py module but forgot to delete the .pyc which was still causing the error.

I created a math module , which is already standard module.

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 60

I have also seen this error when inadvertently naming a module with the same name as one of the standard Python modules. E.g. I had a module called commands which is also a Python library module. This proved to be difficult to track down as it worked correctly on my local development environment but failed with the specified error when running on Google App Engine.

I used abc.py to write a test to demonstrate the import behavior in python, that bites me a lot...

I suspected this and deleted the .py module but forgot to delete the .pyc which was still causing the error.

I created a math module , which is already standard module.

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror