如何将STDIN(多个参数)发送到外部进程并在交互模式下工作

时间:2012-03-13 15:26:04

标签: perl

外部程序具有交互模式,要求提供一些细节。每个传递的参数必须由返回键接受。到目前为止,我设法将一个参数传递给外部进程,但是我面临的问题是多于一个参数,perl会在关闭管道时执行。 当参数逐个传递时,它在交互模式中是不切实际的。

#!/usr/bin/perl

use strict;
use warnings;

use IPC::Open2;

open(HANDLE, "|cmd|");
print HANDLE "time /T\n";
print HANDLE "date /T\n";
print HANDLE "dir\n";
close HANDLE;

1 个答案:

答案 0 :(得分:4)

很遗憾,您无法按照自己的意愿将双重管道传递到open,而加载IPC::Open2并不能解决问题。您必须使用IPC :: Open2导出的open2函数。

use strict;
use warnings;

use IPC::Open2;
use IO::Handle;  # so we can call methods on filehandles

my $command = 'cat';
open2( my $out, my $in, $command ) or die "Can't open $command: $!";

# Set both filehandles to print immediately and not wait for a newline.
# Just a good idea to prevent hanging.
$out->autoflush(1);
$in->autoflush(1);

# Send lines to the command
print $in "Something\n";
print $in "Something else\n";

# Close input to the command so it knows nothing more is coming.
# If you don't do this, you risk hanging reading the output.
# The command thinks there could be more input and will not
# send an end-of-file.
close $in;

# Read all the output
print <$out>;

# Close the output so the command process shuts down
close $out;

如果您只需发送一串命令然后读取输出一次,则此模式有效。如果你需要是交互式的,你的程序很容易挂起等待永远不会出现的输出。对于互动工作,我建议IPC::Run。它相当过于强大,但它将涵盖您可能想要使用外部流程执行的所有操作。