从写入STDOUT的函数返回值的最佳方法是什么? [英] Best way to return values from a function that writes to STDOUT?
问题描述
为了记录目的,我有一些帮助函数写入STDOUT。其中一些函数向调用者返回一个值,但函数的整个输出被返回。所以我的问题是我如何让我的函数写入STDOUT并返回一个值给调用者而不会被函数调用期间发出的所有STDOUT污染返回值?我正在寻找某种设计模式或最佳做法。
考虑以下脚本:
函数a
{
写入输出In Function a
$ a = 4
return $ a
}
$ b = a
写入输出外部函数:`$ b是$ b
输出是
$ b $ 外部函数:$ b是In函数a 4
但是我希望输出是:
在函数a
$ b是4
em> all 函数中的未捕获输出被返回,而不仅仅是 return
的参数。从文档:
$ b
在Windows PowerShell®中,即使没有包含Return关键字的语句,每个语句的结果也会作为输出返回。
功能如下:
函数Foo {
'foo'
}
或者像这样:
function Foo {
'foo'
return
}
或者像这样:
function Foo {
return'foo'
}
它会以任何方式返回字符串 foo
。
为防止输出被返回,您可以
-
写入主机:
函数a {
Write-Host'一些文字'
$ a = 4
return $ a
}
-
捕获变量中的输出:
函数a {
$ var = Write-Output'一些文本'
$ a = 4
return $ a
}
-
或将输出重定向到
$ null
:
函数a {
写输出'某些文本'| Out-Null
Write-Output'some text'> $ null
$ a = 4
return $ a
}
I have some helper functions that write to STDOUT for logging purposes. Some of these functions return a value to the caller, but the entire output from the function is returned. So my question is how can I have my functions write to STDOUT AND return a value to the caller without the return value being polluted with all the STDOUT emitted during the function call? I'm looking for some kind of design pattern or best practise.
Consider this script:
Function a
{
Write-Output "In Function a"
$a = 4
return $a
}
$b = a
Write-Output "Outside function: `$b is $b"
The output is
Outside function: $b is In Function a 4
But I want the output to be:
In Function a
$b is 4
In PowerShell all non-captured output inside a function is returned, not just the argument of return
. From the documentation:
In Windows PowerShell®, the results of each statement are returned as output, even without a statement that contains the Return keyword.
It doesn't matter if the function looks like this:
function Foo {
'foo'
}
or like this:
function Foo {
'foo'
return
}
or like this:
function Foo {
return 'foo'
}
it will return the string foo
either way.
To prevent output from being returned, you can
write to the host:
Function a { Write-Host 'some text' $a = 4 return $a }
capture the output in a variable:
Function a { $var = Write-Output 'some text' $a = 4 return $a }
or redirect the output to
$null
:Function a { Write-Output 'some text' | Out-Null Write-Output 'some text' >$null $a = 4 return $a }
这篇关于从写入STDOUT的函数返回值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!