从写入STDOUT的函数返回值的最佳方法 [英] Best way to return values from a function that writes to STDOUT

查看:106
本文介绍了从写入STDOUT的函数返回值的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些辅助功能,这些功能可以写入STDOUT以便进行日志记录.其中一些函数将值返回给调用者,但返回了该函数的全部输出.

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.

如何让我的函数写入STDOUT 并向调用方返回一个值,而不会在函数调用过程中发出的所有STDOUT都污染返回值?

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.

考虑此脚本:

Function a
{
    Write-Output "In Function a"
    $a = 4
    return $a   
}

$b = a

Write-Output "Outside function: `$b is $b"

输出为

Outside function: $b is In Function a 4

但我希望输出为:

In Function a
$b is 4

推荐答案

在PowerShell all 中,返回的是函数内部未捕获的输出,而不仅仅是return的参数.从文档:

In PowerShell all non-captured output inside a function is returned, not just the argument of return. From the documentation:

在PowerShell中,即使没有包含return关键字的语句,每个语句的结果也将作为输出返回.

In 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'
}

或类似这样:

function Foo {
  'foo'
  return
}

或类似这样:

function Foo {
  return 'foo'
}

它将以任何一种方式返回字符串foo.

it will return the string foo either way.

要防止返回输出,您可以

To prevent output from being returned, you can

  • 写入主机或其他输出流(取决于您要创建的输出类型):

  • write to the host or one of the other ouptput streams (depending on the type of output you want to create):

Function a {
  Write-Host 'some text'
  Write-Verbose 'verbose message'
  Write-Information 'info message'   # requires PowerShell v5 or newer
  $a = 4
  return $a
}

旁注:Write-Information在PowerShell v5之前不可用,当

Side note: Write-Information is not available prior to PowerShell v5 when the information stream was introduced, and starting with that version Write-Host also writes to that stream rather than directly to the host console.

将输出捕获到变量中或将其分配"给$null:

capture the output in a variable or "assign" it to $null:

Function a {
  $var = Write-Output 'some text'
  $null = Write-Output 'some text'
  $a = 4
  return $a
}

  • 或将输出重定向到$null:

    Function a {
      Write-Output 'some text' | Out-Null
      Write-Output 'some text' >$null
      $a = 4
      return $a
    }
    

  • 这篇关于从写入STDOUT的函数返回值的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆