提供Perl腳本來回答Python問題可能有點奇怪,但它對於Python的作用與對Perl的作用一樣。這是一個名爲'fixin
'的腳本,意思是'修復解釋器'。它將shebang行更改爲當前PATH的正確字符串。
#!/Users/jleffler/perl/v5.10.0/bin/perl
#
# @(#)$Id: fixin.pl,v 1.3 2003/03/11 21:20:08 jleffler Exp $
#
# FIXIN: from Programming Perl
# Usage: fixin [-s] [file ...]
# Configuration
$does_hashbang = 1; # Kernel recognises #!
$verbose = 1; # Verbose by default
# Construct list of directories to search.
@absdirs = reverse grep(m!^/!, split(/:/, $ENV{'PATH'}, 999));
# Process command line arguments
if ($ARGV[0] eq '-s')
{
shift;
$verbose = 0;
}
die "Usage: $0 [-s] [file ...]\n" unless @ARGV || !-t;
@ARGV = '-' unless @ARGV;
# Process each file.
FILE: foreach $filename (@ARGV)
{
open(IN, $filename) || ((warn "Can't process $filename: $!\n"), next);
$_ = <IN>;
next FILE unless /^#!/; # Not a hash/bang file
chop($cmd = $_);
$cmd =~ s/^#! *//;
($cmd, $arg) = split(' ', $cmd, 2);
$cmd =~ s!^.*/!!;
# Now look (in reverse) for interpreter in absolute path
$found = '';
foreach $dir (@absdirs)
{
if (-x "$dir/$cmd")
{
warn "Ignoring $found\n" if $verbose && $found;
$found = "$dir/$cmd";
}
}
# Figure out how to invoke interpreter on this machine
if ($found)
{
warn "Changing $filename to $found\n" if $verbose;
if ($does_hashbang)
{
$_ = "#!$found";
$_ .= ' ' . $arg if $arg ne '';
$_ .= "\n";
}
else
{
$_ = <<EOF;
:
eval 'exec $found $arg -S \$0 \${1+"\[email protected]"}'
if \$running_under_some_shell;
EOF
}
}
else
{
warn "Can't find $cmd in PATH, $filename unchanged\n" if $verbose;
next FILE;
}
# Make new file if necessary
if ($filename eq '-') { select(STDOUT); }
else
{
rename($filename, "$filename.bak") ||
((warn "Can't modify $filename"), next FILE);
open(OUT, ">$filename") ||
die "Can't create new $filename: $!\n";
($def, $ino, $mode) = stat IN;
$mode = 0755 unless $dev;
chmod $mode, $filename;
select(OUT);
}
# Print the new #! line (or the equivalent) and copy the rest of the file.
print;
while (<IN>)
{
print;
}
close IN;
close OUT;
}
該代碼由原始駱駝書('Programming Perl',first edition)中的同名腳本派生而來。此後,此副本已被黑客入侵 - 並且應該被更多黑客入侵。我卻用它經常 - 事實上,我只是複製它從一臺Mac到另一個,因爲我還沒有在第二安裝的Perl 5.10.0,我跑:
$ perl fixin fixin
Changing fixin to /usr/bin/perl
$
私營從而改變安裝Perl的標準之一。
讀者練習 - 用Python重寫腳本。
用符號鏈接替換/ usr/bin/python可能不是最好的辦法。有些OS X實用程序可能會引用/ usr/bin/python,並且由於Python 3K與Python 2.x不是100%向後兼容,因此存在破壞其中一些實用程序的風險。 – mipadi 2009-05-24 17:09:07