[英]Can I capture shell invocations from Perl?
我有一个调用其他程序的Perl脚本,即调用system
和/或exec
和/或用管道open
和/或使用反引号操作符。
我是否可以运行此脚本,以便打印出上述每个参数,以便我可以看到它调用的内容?
例如像我这样的程序,我无法修改
#!/usr/bin/perl
sub get_arg {return "argument$_[0]";}
system "./foo", get_arg(1), get_arg(2);
print `./foo abc def`;
调用了类似这样的东西
perl --shell-trace-on ./myscript.pl
在这种情况下输出
./foo argument1 argument2
./foo abc def
抛弃myscript.pl的正常输出或将其与此跟踪混合是可以接受的。
非常感谢。
这被认为是高级Perl,但您可以在编译时在CORE::GLOBAL
命名空间中定义子例程并劫持Perl的内置函数。 在CORE
名称空间中调用函数将调用原始内置函数。
BEGIN {
# have to use a BEGIN block so these functions are defined before
# run time
*CORE::GLOBAL::system = sub {
print STDERR "about to invoke system @_\n";
return CORE::system(@_);
};
*CORE::GLOBAL::qx = sub {
print STDERR "about to invoke qx/backticks @_\n";
return CORE::qx(@_);
};
*CORE::GLOBAL::exec = sub { ... };
};
system("sleep 5");
print `ls`;
1;
要将此功能应用于任意独立脚本,您可以将此代码放入一个简单模块(例如, ShellTrace.pm
),然后使用-MShellTrace
开关调用perl
。 (HT:perlman):
package ShellTrace;
BEGIN {
*CORE::GLOBAL::system = sub { ... };
*CORE::GLOBAL::qx = sub { ... };
*CORE::GLOBAL::exec = sub { ... };
*CORE::GLOBAL::open = sub { ... };
}
1;
$ perl -MShellTrace ./myscript.pl
about to invoke system ./foo argument1 argument2
about to invoke qx/backticks ./foo abc def
...
不,系统命令不会将其执行的命令放在任何特殊变量中。
#!/usr/bin/perl
sub get_arg {return "argument$_[0]";}
my $command = './foo ' . join(' ', get_arg(1), get_arg(2));
print "$command\n";
my $resp = `$command`; # or system($command);
print `ls *bar*`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.