我的perl程序存在这个问题,它是从一个文件中读取的(我在STDIN上打开该文件,并使用$line = <>
一次读取每一行)。执行backtick
命令之后,然后从STDIN读取下一行,得到undef,发送信号EOF。我使用调试代码将其隔离到回拨命令,如下所示:
my $dir = dirname(__FILE__);
say STDERR "before: tell(STDIN)=" . tell(STDIN) . ", eof(STDIN)=" . eof(STDIN);
say STDERR "\@export_info = `echo nostdin | perl $dir/pythonizer_importer.pl $fullfile`;";
@export_info = `echo nostdin | perl $dir/pythonizer_importer.pl $fullfile`;
say STDERR "after: tell(STDIN)=" . tell(STDIN) . ", eof(STDIN)=" . eof(STDIN);
产出如下:
before: tell(STDIN)=15146, eof(STDIN)=
@export_info = `echo nostdin | perl ../pythonizer_importer.pl ./Pscan.pm`;
after: tell(STDIN)=15146, eof(STDIN)=1
最近,我将echo nostdin |
添加到perl命令中,但没有任何效果。如何在不破坏STDIN的情况下运行此命令并获取STDOUT?顺便说一句,这都是在Windows上运行的。如果这件事重要的话,我会从git bash启动主程序。
发布于 2022-03-16 22:20:20
在运行backticks命令之前尝试本地未定义STDIN,就像下面的示例脚本所做的那样。注意,从调用本地的子例程调用的任何子程序都会看到新的值。您也可以在open STDIN, "<", "file for child process to read";
之后执行local *STDIN
,但在将STDIN还原到旧值之前记住要对文件进行close()
。
子进程正在影响您的STDIN,因为“命令使用的STDIN文件句柄是从Perl的STDIN继承的”- 佩洛普手册。
这只是一个例子;在实际脚本中,用要运行的实际命令替换sed命令。
use strict;
use warnings;
#Run a command and get its output
sub get_output {
# Prevent passing our STDIN to child process
local *STDIN = undef;
print "Running sed\n";
#replace the sed command with the actual command you want to run
return `sed 's/a/b/'`;
}
my $output = get_output();
print $output;
#We can still read STDIN even after running a child process
print "Waiting for input\n";
print "Readline is " . scalar readline;
输入:
a
b
c
^D
line
输出:
Running sed
b
b
c
Waiting for input
Readline is line
https://stackoverflow.com/questions/71504096
复制相似问题