我有一个程序,可以从键盘获取输入并呈现出漂亮的可视化效果。该程序的目的是让我的婴儿可以敲击键盘并让计算机做一些事情。
但是,我想编写一个与主程序脱节的键盘输入清理程序。从概念上讲,我希望该程序具有以下功能:
sanitize_keyboard_input | my_program
Wheremy_program
认为它是从键盘获取输入,但实际上是从 获取输入sanitize_keyboard_input
。有没有办法做到这一点?我正在运行 Ubuntu linux,如果有帮助的话。
答案1
这是我很久以前写的。它是位于用户输入和交互式程序之间的脚本,并允许截取输入。当运行提出很多问题的旧 Fortran 程序时,我用它转义到 shell 来检查文件名。您可以轻松修改它以拦截特定输入并清理它们。
#!/usr/bin/perl
# shwrap.pl - Wrap any process for convenient escape to the shell.
use strict;
use warnings;
# Provide the executable to wrap as an argument
my $executable = shift;
my @escape_chars = ('#'); # Escape to shell with these chars
my $exit = 'bye'; # Exit string for quick termination
open my $exe_fh, "|$executable @ARGV" or die "Cannot pipe to program $executable: $!";
# Set magic buffer autoflush on...
select((select($exe_fh), $| = 1)[0]);
# Accept input until the child process terminates or is terminated...
while ( 1 ) {
chomp(my $input = <STDIN>);
# End if we receive the special exit string...
if ( $input =~ m/$exit/ ) {
close $exe_fh;
print "$0: Terminated child process...\n";
exit;
}
foreach my $char ( @escape_chars ) {
# Escape to the shell if the input starts with an escape character...
if ( my ($command) = $input =~ m/^$char(.*)/ ) {
system $command;
}
# Otherwise pass the input on to the executable...
else {
print $exe_fh "$input\n";
}
}
}
您可以尝试使用一个简单的示例测试程序:
#!/usr/bin/perl
while (<>) {
print "Got: $_";
}