【问题标题】:How to send STDIN(multiple arguments) to external process and work within interactive mode如何将 STDIN(多个参数)发送到外部进程并在交互模式下工作
【发布时间】:2012-03-13 15:26:04
【问题描述】:

外部程序有交互模式,询问一些细节。每个传递的参数都必须被返回键接受。到目前为止,我设法将一个参数传递给外部进程,但是我面临的问题不止一个参数被传递,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;

【问题讨论】:

  • 在管道的写入端启用自动刷新到外部进程。如果您实际上以正确的方式使用IPC::Open2,这将为您完成。
  • @mob 与其指出代码错误,他们已经知道它不起作用,您应该加紧回答,显示“正确的方式”?

标签: perl


【解决方案1】:

不幸的是,您不能将双管道传递给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。它相当强大,但它几乎涵盖了您可能想要对外部进程执行的所有操作。

【讨论】:

  • 不知道为什么你说我使用的代码不起作用。使用 AUTOFLUSH 可以正常工作。
  • 您的代码似乎根本不起作用。我的问题也是 IPC:Run 不适用于 perl for windows
  • @jey 我说您使用的代码不起作用,因为open(HANDLE, "|cmd|") 会产生警告“无法打开双向管道”。如果您的代码有效,那么它与您发布的代码不同。 IPC::Run 在 Windows 上可用,但您必须像安装任何其他 CPAN 模块一样安装它。你是什​​么意思我的代码不起作用?您是否收到错误消息?是完全静音吗?它会整天坐在沙发上喝所有的牛奶吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多