在 DAG 文件(或 DAG 文件导入的模块)中导入 pywikibot
时,DAG 会损坏,并在网络服务器 UI 中抛出错误:
Broken DAG: [/path/to/airflow/dags/dag.py] encode() argument 1 must be str, not bool
我尝试查找堆栈跟踪,但在 airflow/logs
中搜索时找不到任何内容。即使使用 --report
,airflow list_dags
也会成功运行,并且无助于调试问题(如 this question 所建议)。
我的问题是:如何在 Airflow DAG 任务中使用 Pywikibot?
<小时/>我在下面添加了其他信息来展示我迄今为止所尝试的内容。当我们找到答案后,可以将其删除以使问题更加简洁。
<小时/>以下是示例 DAG 的代码:
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from datetime import timedelta, datetime
#### this part is typically imported from another module ####
# to import, pywikibot requires `user-config.py` file or this env variable
import os
os.environ['PYWIKIBOT_NO_USER_CONFIG'] = '1'
import pywikibot
def do_nothing():
pass
#############################################################
dag = DAG('try_pywikibot', schedule_interval=timedelta(days=1))
default_args = {
'start_date': datetime(2019,1,1),
}
task1 = PythonOperator(
python_callable=do_nothing,
task_id=f'do_nothing',
dag=dag,
default_args=default_args,
)
<小时/>
导入pywikibot
的注意事项:
Pywikibot 需要工作目录中的配置文件 user-config.py
,除非 PYWIKIBOT_NO_USER_CONFIG
环境变量指定为 0
。此类文件的示例:
family = 'wikipedia' # required
mylang = 'en' # required
# verbose_output = 0 # optional
<小时/>
我认为这可能是由于 pywikibot
的日志记录(发送 bool
?)。可以通过在 pywikibot
的配置文件 (user-config.py
) 中添加 verbose_output = 0
来关闭详细日志记录,但这不会解决问题。
奇怪的是,运行这个简单的脚本
import pywikibot
import airflow
使用带有 verbose_output=0
的 user-config.py
文件仍然会从 pywikibot
输出详细日志。但是,当不导入 Airflow 时,它会在没有任何日志输出的情况下运行。但是,我尝试通过修改库的 logging.logoutput()
来完全禁用 pywikibot 的日志记录,即使导入了 Airflow,也会禁用日志记录,但 DAG 仍然被视为被 Airflow 破坏。
当手动触发DAG时,DAG确实“启动”,但任务永远不会排队;他们仍然停留在状态None
。
最佳答案
将行 console_encoding="utf-8"
添加到 pywikibot 的配置 user-config.py
即可。
到底为什么,我不确定。当通过 Airflow 运行时,Pywikibot 似乎无法加载 console_encoding
的默认值 utf-8
。由于 pywikibot 的 transliterator
是预先加载的,这会导致 ln 处的 pywikbot.userinterfaces.transliteration.py
失败。 1108.
奇怪的是,pywikibot 似乎期望一个 bool 值,但现在抛出
_DifferentTypeError: Configuration variable "console_encoding" is defined as "str" in your user-config.py but expected "bool".
但是,可以安全地忽略这一点。
关于python - 如何将 Airflow 与 Pywikibot 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59105092/