我正在尝试使用python创建一个小型查找程序,它会显示理论组合的所有当前价格,然后提供基本刷新您的投资组合的选项,或者查找您选择的新报价
我可以在程序中使用一切,我遇到的问题是定义的函数。
如果你看一下run_price1(),你会发现它与run_price()的相同;但是run_price()位于更新函数中。
如果我将其从更新功能中删除,则更新功能不起作用。如果我还没有在更新函数之外的某个地方列出它,则后面的用户输入不起作用。
问题:我正在寻找一种方法来调用另一个函数中定义的函数,或者在辅助函数中使用先前定义的函数的方法。
我的代码:
import mechanize
from bs4 import BeautifulSoup
def run_price1():
myBrowser = mechanize.Browser()
htmlPage=myBrowser.open(web_address)
htmlText=htmlPage.get_data()
mySoup = BeautifulSoup(htmlText)
myTags = mySoup.find_all("span", id=tag_id)
myPrice = myTags[0].string
print"The current price of, {} is: {}".format(ticker.upper(), myPrice)
def update():
my_stocks = ["aapl","goog","sne","msft","spy","trgt","petm","fslr","fb","f","t"]
counter = 0
while counter < len(my_stocks):
web_address = "http://finance.yahoo.com/q?s={}".format(my_stocks[counter])
ticker = my_stocks[counter]
#'yfs_l84_yhoo' - that 1(one) is really a lowercase "L"
tag_id = "yfs_l84_{}".format(ticker.lower())
def run_price():
myBrowser = mechanize.Browser()
htmlPage=myBrowser.open(web_address)
htmlText=htmlPage.get_data()
mySoup = BeautifulSoup(htmlText)
myTags = mySoup.find_all("span", id=tag_id)
myPrice = myTags[0].string
print"The current price of, {} is: {}".format(ticker.upper(), myPrice)
run_price()
counter=counter+1
update()
ticker = ""
while ticker != "end":
ticker = raw_input("Type 'update', to rerun portfolio, 'end' to stop program, or a lowercase ticker to see price: ")
web_address = "http://finance.yahoo.com/q?s={}".format(ticker.lower())
tag_id = "yfs_l84_{}".format(ticker.lower())
if ticker == "end":
print"Good Bye"
elif ticker == "update":
update()
else:
run_price1()
答案 0 :(得分:0)
您只需从run_price1()
功能拨打update()
,即可拨打run_price
。
模块顶部定义的函数在模块中是全局的,因此其他函数可以简单地通过名称引用它们并调用它们。
您的函数需要的任何值 需要作为参数传递:
def run_price1(web_address, tag_id):
# ...
def update():
my_stocks = ["aapl","goog","sne","msft","spy","trgt","petm","fslr","fb","f","t"]
counter = 0
while counter < len(my_stocks):
web_address = "http://finance.yahoo.com/q?s={}".format(my_stocks[counter])
ticker = my_stocks[counter]
#'yfs_l84_yhoo' - that 1(one) is really a lowercase "L"
tag_id = "yfs_l84_{}".format(ticker.lower())
run_price1(web_address, tag_id)
counter=counter+1