【问题标题】:Combination of scripts: Python, PHP, Ruby, and Perl in single script in Python [closed]脚本组合:Python、PHP、Ruby 和 Perl 在 Python 中的单个脚本 [关闭]
【发布时间】:2017-02-09 21:29:58
【问题描述】:

我有 8 个脚本。我想把它们全部放在一个脚本中,问题是它们是用不同的语言编写的:

  • PHP
  • 红宝石
  • Perl
  • Python

但最后一个应该是 Python 的。

我想这样做而不需要用 Python 重写所有这些。

有没有办法做到这一点?

脚本接受输入 .txt 文件作为命令行参数,并生成输出 .txt 文件。

【问题讨论】:

  • 你试过写shell脚本吗?
  • 我对 sh 有一点了解,但我如何尝试使用 shell 脚本?
  • 视情况而定。例如,在 GNU/Linux 平台上,最好的 shell 之一是 Bash。在最简单的情况下,shell 脚本看起来像一个命令列表。如果你想从 Python 脚本调用脚本,那么你应该使用subprocess
  • 我理解投反对票,因为到目前为止您还没有发布您尝试过的内容。

标签: php python ruby python-2.7 perl


【解决方案1】:

假设我们有几个脚本,每个脚本都接受文件路径作为第一个参数:

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 &gt;&amp;2 命令将字符串打印到标准错误描述符。有了 shell 包装器,您可能会在 Python 中调用单个子进程:

try:
    output = check_output(['./call-scripts.sh', input_file])
    print output
except CalledProcessError as e:
    print >> sys.stderr, "Execution failed: ", e

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-11
    • 2020-01-04
    • 2014-10-10
    • 2014-10-06
    • 2021-08-13
    • 2015-09-03
    • 2012-12-17
    • 1970-01-01
    相关资源
    最近更新 更多