[英]How can I capture STDOUT on a Python UDF in Snowflake to return as string?
一些 Python 庫 output 將其函數的結果發送到 STDOUT - 並且在 Python UDF 中,我需要將其返回到一個字符串中的雪花。
例如help()
或numpy.show_config()
的 output 。
您可以使用contextlib.redirect_stdout
捕獲標准輸出。
例如,要捕獲help(numpy)
的 output :
create or replace function help_numpy()
returns string
language python
runtime_version = '3.8'
packages = ('numpy')
handler = 'x'
as $$
import io
from contextlib import redirect_stdout
from pydoc import help
import numpy
def x():
f = io.StringIO()
with redirect_stdout(f):
help(numpy)
return f.getvalue()
$$;
select help_numpy();
或者要捕獲numpy.show_config()
的 output,您只需替換在redirect_stdout()
塊中調用的函數:
with redirect_stdout(f):
numpy.show_config()
請注意,要使用help()
我們還必須from pydoc import help
。 否則你會得到錯誤NameError: name 'help' is not defined in function HELP with handler
。
這對所有 UDF 語言來說都是一個好主意。 開源 JavaScript 經常充滿alert
, window.alert
, console.log
等。要捕獲 JavaScript 中的警報和控制台輸出功能:
create or replace function STDOUT()
returns array
language javascript
as
$$
//----- Start of standard out intercepts. Add to top of UDF
console.logs = [];
window = {};
console.log = function(){ console.logs.push({"type":"log", "timestamp":new Date().toISOString(), "out":Array.from(arguments)}) };
console.warn = function(){ console.logs.push({"type":"warn", "timestamp":new Date().toISOString(), "out":Array.from(arguments)}) };
console.error = function(){ console.logs.push({"type":"error", "timestamp":new Date().toISOString(), "out":Array.from(arguments)}) };
console.debug = function(){ console.logs.push({"type":"debug", "timestamp":new Date().toISOString(), "out":Array.from(arguments)}) };
alert = function(){ console.logs.push({"type":"alert", "timestamp":new Date().toISOString(), "out":Array.from(arguments)}) };
window.alert = function(){ console.logs.push({"type":"alert", "timestamp":new Date().toISOString(), "out":Array.from(arguments)}) };
//----- End of standard out intercepts
console.log("My log.");
console.warn("My warning");
console.error("My error");
alert("My alert");
window.alert("My window alert");
return console.logs;
$$;
select STDOUT();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.