如何安排datalabipynb定期运行

2024-04-25 13:40:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计划在datalab(来自googlecloud平台,或GCP)ipynb文件中定期运行我的代码(比如说,每天1个)。请帮助说明可能的解决方法。谢谢!你知道吗

  • 我认为GCP云调度器或cron作业(克朗.ysml)应该这样做,但我不知道他们到底是怎么工作的。你知道吗

以下是我的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'

Tags: fromimportcomurlhtmltableunicodecss
1条回答
网友
1楼 · 发布于 2024-04-25 13:40:13

我认为,安排一个来自云数据实验室ipythonnotebook的定期运行可能是一种太多的反模式,不值得鼓励。你知道吗

jupyter“服务器”在计算引擎VM实例的容器中运行。你知道吗

乍一看,人们可能希望通过将“notebook”转换为常规的Python模块,然后远程运行它来实现这一点,问题是您可能拥有的第三方库依赖关系。你知道吗

即使没有依赖项,转换notebookrequired software也不会安装在container的映像上,因此您需要在实例重新启动之间的每次运行中安装它。你知道吗

您也可以“自己”将其转换,虽然这并不能保证在任何情况下都能成功运行,但作为对notebook格式的深入研究(尽管乍一看似乎并不太复杂),我将在下面演示如何执行。你知道吗

因此,让我们将notebook源代码通过管道传输到execBuilt-in Function,加载依赖项,以便exec调用成功运行。你知道吗

所有这些都是通过VM实例上运行的datalabcontainer远程完成的。你知道吗

$ 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)
"""
'

到目前为止,由于我的专业知识不多,我找不到另一种不逃避角色的方法。你知道吗

至少,您还将得到与某些imp.load_package库的依赖项不可用相关的警告。这提醒我们,这种方法根本不可伸缩。你知道吗

我不知道您对此有何看法,但最好是在云函数上运行Python源代码,然后使用云调度程序触发该函数。看看这个community example。你知道吗

我相信从这篇文章中可以得出一个合理的结论,即notebook可以有不同于Pythonmodule的用例。你知道吗

另外,一定要通过云数据实验室documentation至少了解这个答案所涉及的一些概念。你知道吗

相关问题 更多 >