【发布时间】:2017-08-13 08:08:38
【问题描述】:
我正在使用 Win32::Process 在 Perl 脚本中运行命令,我需要将该命令的输出重定向到文本文件。在做了一些研究之后,这就是我正在尝试的:
use Win32::Process;
open (OLDOUT, ">&STDOUT");
open (OLDERR, ">&STDERR");
my $file = "output.txt";
open (STDOUT, ">$file");
open (STDERR, ">&STDOUT");
my $timeout = 1000 * 60; # 60 second timeout
my $proc;
my $exit;
my $exe = "C:/Windows/System32/cmd.exe";
Win32::Process::Create($proc, $exe, "echo hello from process", 1, DETACHED_PROCESS, ".");
$proc->Wait($timeout);
$proc->GetExitCode($exit);
system("echo hello from system"); # To verify that the redirect is working
close (STDOUT);
close (STDERR);
open (STDOUT, ">&OLDOUT");
open (STDERR, ">&OLDERR");
close (OLDOUT);
close (OLDERR);
不幸的是,这不起作用。在 output.txt 文件中,我只得到“来自系统的你好”。有没有办法使用 Win32::Process 完成我想要的?
我使用 Win32::Process 而不是反引号的原因是因为我的命令有时会崩溃,并且我需要提供超时以便在必要时终止它。 Win32::Process 的 ->Wait() 函数允许我这样做。
我宁愿有一个使用 Win32::Process 的解决方案,因为我受限于我可以访问的模块。但是,如果这真的做不到,我会欢迎使用其他模块的示例解决方案。
谢谢。
【问题讨论】:
标签: perl winapi win32-process