我在Windows 7 x86下运行perl,当我调用从另一个脚本执行外部命令的子例程时,我得到一个错误。
我有两个脚本,script1有一个执行程序(patt.exe
)的子程序和script2通过require
使用该子程序。
当我运行script1时,它工作正常。但是,当我尝试从script2内部使用此子例程时,我得到以下错误:
错误:
'patt.exe' is not recognized as an internal or external command, operable program or batch file.
script1 :
#patt('file.txt');
sub patt {
my $filename=shift@;
system("cmd.exe /c patt.exe -S $filename");
}
1;
script2 :
require 'sub-directory/script1.pl';
patt('file.txt');
我应该提到script1和pat .exe位于子目录(require 'sub-directory/script1.pl';
)中,当我将所有文件放在同一目录(require 'script1.pl';
)时,一切正常工作。如果我使用qx
或当我将参数作为数组传递给脚本时,这个问题仍然存在。
如果有人能帮助我,我将非常感激。
一种解决方案是将当前工作目录更改为外部程序的工作目录。为此,您可以利用perl脚本的__FILE__
变量,该变量与您的程序共享同一目录。
当然,需要注意的一点是,如果采用这种解决方案,您可能需要为$filename
提供完全限定的路径:
use strict;
use warnings;
use Cwd;
use File::Spec;
sub patt {
my $filename = shift;
# Temporarily change cwd
my $oldcwd = cwd;
my ($vol, $path) = File::Spec->splitpath(__FILE__);
chdir($path);
# Execute program. Note that $filename will likely need to be a fully qualified path
system("patt.exe -S $filename");
# Revert cwd
chdir($oldcwd);
}
1;
首先,您不需要通过cmd.exe
调用pratt.exe
。您应该能够这样做:
system "patt.exe -S $filename";
错误来自于系统命令无法找到命令patt.exe
来执行它。试试这个:
warn "WARN: @INC: " . join "n ", $ENV{PATH};
这将打印出要搜索可执行文件的所有目录。通常在Windows中,当前目录是$PATH
中的最后一个条目。我不是100%确定require
与当前工作目录的关系。例如,当您将子例程放在另一个目录中的文件中时,可能无法在当前目录中找到pratt.exe
,因为当前目录现在是子例程所在的位置。
Cwd
导入cad
命令:
use strict; # Always! This will help point to errors.
use warnings; # Always! This will help point to errors.
use Cwd;
sub patt {
my $filename = shift;
warn "Current Working Directory is: " . cwd;
warn "PATH is: " . join "n", $ENV{PATH};
my $error = system("cmd.exe /c patt.exe -S $filename");
if ( $error ) {
die qq(Patt failed.);
}
}
1;
根据Windows PATH检查当前工作目录,看看这是否给你一个提示为什么patt
没有被执行