zix robert zix robert - 1 year ago 75
Perl Question

Combination of scripts: Python, PHP, Ruby, and Perl in single script in Python

I have 8 scripts. I want to put them all into a single script, and the problem is that they are written in different languages:

  • PHP

  • Ruby

  • Perl

  • Python

But the final one should be in Python.

I want to do this without the need to rewrite all of them in Python.

Is there a way to do this?

The scripts accept an input
file as a command line argument, and generate an output

Answer Source

Suppose we have a couple of scripts each accepting a file path as the first argument:


$input_file = $argv[1] ?? 'default-input-file';
echo $input_file, PHP_EOL;



use strict;
use warnings;

my $input_file = $ARGV[0] // 'default-input-file';
print "$input_file\n";

In Python you can call them by means of 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])

input_file = sys.argv[1]

if not os.path.isfile(input_file):
    sys.stderr.write("%s is not a file" % input_file)

    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

You might want to wrap the commands into a shell script. For example, a Bash script might look like the following:

#!/bin/bash -

if ! php ./script.php "$@" ; then
  echo >&2 "php command failed"

if ! perl ./script.pl "$@" ; then
  echo >&2 "perl command failed"

The $@ variable represents all the command line arguments passed to the script. The if statements check if the commands finished successfully. The echo >&2 command prints a string to the standard error descriptor. Having the shell wrapper you might call a single subprocess in Python:

    output = check_output(['./call-scripts.sh', input_file])
    print output
except CalledProcessError as e:
    print >> sys.stderr, "Execution failed: ", e
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download