【问题标题】:How to use output redirection in powershell's command-measure?如何在 powershell 的命令度量中使用输出重定向?
【发布时间】:2014-11-12 02:48:53
【问题描述】:

如何在powershell的command-measure中使用输出重定向?

我想要类似于来自 Linux 的 time 的东西,一个简单的程序来计时程序运行的时间

我认为这会起作用,但标准输出没有重定向:Measure-Command {start-process python printstuff.py > Output.txt -Wait}

示例输入:

测量命令 {echo hi}

示例输出:

天数:0 小时 : 0 分钟:0 秒:0 毫秒:0 滴答声 : 1318 总天数:1.52546296296296E-09 总时数:3.66111111111111E-08 总分钟数:2.19666666666667E-06 总秒数:0.0001318 总毫秒数:0.1318

【问题讨论】:

  • 使用start-process的-redirectstandardoutput参数
  • 您也可以在现有示例中在Start-Process 上添加-PassThru,这应该可以。 Start-Process 除非出现提示,否则不会在标准输出上生成任何输出。
  • 为什么首先使用 Start-Process?只需执行python printstuff.py > Output.txt
  • 感谢@KeithHill! (你被标记了吗?-我没有看到 @ 改变)我认为启动过程是 Measure-Command 的必要部分。我在这里找到了一些优秀的文档 - technet.microsoft.com/en-us/library/hh849848.aspx

标签: powershell time cmd


【解决方案1】:

问题是Start-Process 不写入标准输出。相反,它会创建一个新的控制台窗口并运行将其标准输出设置为控制台窗口的进程。使用重定向运算符将为 Start-Process 重定向标准输出,但由于它不写入标准输出,您会得到一个空文件。

解决方案是使用-RedirectStandardOutput 选项告诉Start-Process 为它启动的进程重定向标准输出。

Measure-Command { Start-Process python printstuff.py -RedirectStandardOutput output.txt -Wait }

请注意,如果您想将任何选项传递给 python 程序,您必须明确指定 -ArgumentList:

Measure-Command { Start-Process python -ArgumentList ('printstuff.py','-opt') -RedirectStandardOutput output.txt -Wait }

-ArgumentList 的混乱意味着除非你真的需要使用 Start-Process,否则你可能会发现删除它会更容易,然后重定向就可以正常工作:

Measure-Command { python printstuff.py >output.txt }

请注意,如果您想引用可执行文件的名称(或使用变量中的值),您将需要使用调用运算符(我提到这一点是因为我想知道这是否是您查看 Start-Process 的原因首先):

Measure-Command { & "C:\Python34\python" printstuff.py >output.txt }

【讨论】:

    猜你喜欢
    • 2021-10-04
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    相关资源
    最近更新 更多