我希望在datalab (来自Google平台或GCP) ipynb文件中定期运行我的代码(例如,每天运行1)。请帮助阐明一些可能的解决办法。谢谢!
以下是我的ipynb中的代码(工作正常):
import requests
from bs4 import BeautifulSoup
import os
import io
url = "https://www.taiwanlottery.com.tw/lotto/superlotto638/history.aspx"
soup = BeautifulSoup(urllib.request.urlopen(url).read(),
features="html.parser", from_encoding='utf-8')
css_url = "https://www.taiwanlottery.com.tw/css1.css"
soup_css = BeautifulSoup(urllib.request.urlopen(
css_url).read(), features="html.parser", from_encoding='utf-8')
table = soup.find("table", id="SuperLotto638Control_history1_dlQuery")
with io.open("superLottery.html", "w", encoding='utf-16') as f:
f.write(unicode(table))
f.write(unicode('<style type = "text/css">'))
f.write(unicode(soup_css))
f.write(unicode("</style>"))
!gsutil cp 'superLottery.html' 'gs://astral-petal-222508.appspot.com/datalab-backups/asia-east1-a/new-env'发布于 2019-09-27 14:51:58
我认为,从Cloud定期运行ipython notebook可能是一种难以鼓励的反模式。
jupyter "server“运行在Compute实例上的容器中。
乍一看,人们可能希望通过将“记事本”转换为常规Python模块,然后远程运行它,问题在于您可能存在第三方库依赖关系。
即使没有依赖项,转换所需软件的notebook也没有安装在container的映像上,因此您需要在实例重新启动之间的每次运行中安装它。
您也可以将其转换为“亲自”,虽然并不保证在每一种情况下都能成功运行,但作为对notebook格式的深入研究(尽管乍一看似乎并不太复杂),我将在下面演示如何实现它。
因此,让我们将notebook源代码输送到exec 内建函数,加载我们的依赖项,以便我们的exec调用成功运行。
所有这些都是通过运行在VM实例上的datalab container远程完成的。
$ project= #TODO edit
$ zone= #TODO edit
$ instance= #TODO edit
$ gcloud compute ssh $instance --project $project --zone $zone -- docker exec datalab python '-c """
import json
import imp
#TODO find a better way and not escape quote characters?...
bs4 = imp.load_package(\"bs4\", \"/usr/local/envs/py2env/lib/python2.7/site-packages/bs4\")
BeautifulSoup = bs4.BeautifulSoup
notebook=\"/content/datalab/notebooks/notebook0.ipynb\"
source_exclude = (\"from bs4 import BeautifulSoup\")
with open(notebook) as fp:
source = \"\n\".join(line for cell in json.load(fp)[\"cells\"] if cell[\"cell_type\"]==\"code\" for line in cell[\"source\"] if line not in source_exclude)
#print(source)
exec(source)
"""
'到目前为止,由于我的bash专业知识不多,我无法找到其他方法来避免这些角色的出现。
至少,您还将得到与一些imp.load_package库的依赖项不可用相关的警告。这提醒我们,这种方法根本就不具有可伸缩性。
我不知道您对此有何看法,但也许最好在云函数上运行Python源代码,然后使用触发该函数。看看这个社区范例就知道了。
我认为这篇文章的一个合理观点是,notebook可以有不同于Python module的不同用例。
另外,确保通过Cloud 文档来至少理解这个答案所涉及的一些概念。
https://stackoverflow.com/questions/58049886
复制相似问题