假设我们有几个脚本,每个脚本都接受文件路径作为第一个参数:
script.php
<?php
$input_file = $argv[1] ?? 'default-input-file';
echo $input_file, PHP_EOL;
script.pl
#!/usr/bin/perl
use strict;
use warnings;
my $input_file = $ARGV[0] // 'default-input-file';
print "$input_file\n";
在 Python 中,您可以通过 subprocess.check_output 调用它们:
#/usr/bin/env python2
import os.path
import sys
from subprocess import check_output, STDOUT, CalledProcessError
if len(sys.argv) < 2:
sys.stderr.write("Usage: %s input-file" % sys.argv[0])
sys.exit(1)
input_file = sys.argv[1]
if not os.path.isfile(input_file):
sys.stderr.write("%s is not a file" % input_file)
sys.exit(1)
try:
output = check_output(['php', './script.php', input_file], stderr=STDOUT)
print "PHP: %s" % output
output = check_output(['perl', './script.pl', input_file], stderr=STDOUT)
print "Perl: %s" % output
except CalledProcessError as e:
print >> sys.stderr, "Execution failed: ", e
您可能希望将命令包装到 shell 脚本中。例如,Bash 脚本可能如下所示:
#!/bin/bash -
if ! php ./script.php "$@" ; then
echo >&2 "php command failed"
fi
if ! perl ./script.pl "$@" ; then
echo >&2 "perl command failed"
fi
$@ 变量代表传递给脚本的所有命令行参数。 if 语句检查命令是否成功完成。 echo >&2 命令将字符串打印到标准错误描述符。有了 shell 包装器,您可能会在 Python 中调用单个子进程:
try:
output = check_output(['./call-scripts.sh', input_file])
print output
except CalledProcessError as e:
print >> sys.stderr, "Execution failed: ", e