Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

python - Error when configuring tkinter widget: 'NoneType' object has no attribute

I am running the below code which run fine when I hard code the value

from nsetools import Nse
nse = Nse()
with open('all_nse_stocks') as nse_stocks:
    for stock in nse_stocks:
        q = nse.get_quote('INFY')
        print q.get('open'), '', q.get('lastPrice'), '', q.get('dayHigh'), '', q.get('dayLow')

see that I have hard-coded the value nse.get_quote('INFY') But when I run the following code, I get the following error:

from nsetools import Nse
nse = Nse()
with open('all_nse_stocks') as nse_stocks:
    for stock in nse_stocks:
        q = nse.get_quote(stock)
        print q.get('open'), '', q.get('lastPrice'), '', q.get('dayHigh'), '', q.get('dayLow')

ERROR:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    print q.get('open'), '', q.get('lastPrice'), '', q.get('dayHigh'), '', q.get('dayLow')
AttributeError: 'NoneType' object has no attribute 'get'

Please help

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

NoneType object has no attribute ... means that you have an object that is None, and you're trying to use an attribute of that object.

In your case you're doing q.get(...), so q must be None. Since q is the result of calling nse.get_quote(...), that function must have the possibility of returning None. You'll need to adjust your code to account for that possibility, such as checking the result before trying to use it:

q = nse.get_quote(stock)
if q is not None:
    print ...

The root of the problem is likely in how you're reading the file. stock will include the newline, so you should strip that off before calling nse.get_quote:

q = nse.get_quote(stock.strip())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...