Below is code that checks a price on a website and shoots it out to Twitter. As you can see, on line 22, I pass the first function(which fetches the price) as an argument in the second function(which streams to Twitter). When I run this I keep getting an error message that says "TypeError: send_to_twitter() takes no arguments (1 given)". Can't figure out why it won't take an argument. Any idea?
import urllib.request
import time
def get_price():
page = urllib.request.urlopen("http://www.beans-r-us.biz/prices.html")#get price from website
text = page.read().decode("utf8")
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 4
return float(text[start_of_price:end_of_price])
def send_to_twitter():
password_manager = urllib.request.HTTPPasswordMgr()
password_manager.add_password('Twitter API','http://twitter.com/statuses','eyemademusic','selfishgene')
http_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
page_opener = urllib.request.build_opener(http_handler)
urllib.request.install_opener(page_opener)
params开发者_运维百科 = urllib.parse.urlencode({'status':msg})
resp = urllib.request.urlopen('http://twitter.com/statuses/update.json', params)
resp.read
price_now = input('Would you like to check the price? Y/N')
if price_now == 'Y':
send_to_twitter(get_price())
else:
price = 99.99
while price > 4.74:
time.sleep(900)
price = get_price
send_to_twitter('Buy!')
def send_to_twitter(name_of_the_argument_you_want):
def send_to_twitter():
should be def send_to_twitter(msg):
and resp.read
should be resp.read()
and price = get_price
should be price = get_price()
Because this:
def send_to_twitter():
...
Defines a function of zero arguments. Think about this for a second; how would you refer to the argument you want it to take? What name would it have inside the function? Inside the parentheses after the function name, you need to list the names of all the arguments the function takes.
Also, where you have this:
send_to_twitter(get_price())
you're not actually passing the function get_price
as an argument to send_to_twitter
, you're calling get_price
and passing the result. If you want to pass the function, you need to just use the function name, not the parentheses, like so:
send_to_twitter(get_price)
精彩评论