0

I'm trying to execute a perl script within another python script. My code is as below:

command = "/path/to/perl/script/" + "script.pl"
input = "< " + "/path/to/file1/" + sys.argv[1] + " >"
output = "/path/to/file2/" + sys.argv[1]

subprocess.Popen(["perl", command, "/path/to/file1/", input, output])

When execute the python script, it returned:

No info key.

All path leading to the perl script as well as files are correct.

My perl script is executed with command:

perl script.pl /path/to/file1/ < input > output

Any advice on this is much appreciate.

4
  • try the following approach as in this SO stackoverflow.com/questions/25079140/… Commented Jun 25, 2015 at 7:33
  • What do you mean, nothing happened? As far as the output is concerned, you communicate with the process, but you don't print or otherwise do anything with the communication result (process's stdout) in your Python script. As per the documentation: "communicate() returns a tuple (stdoutdata, stderrdata)." (emphasis mine.) Commented Jun 25, 2015 at 7:34
  • 3
    You're using the shell redirect operators as part of your input string. Thus, subprocess will try and run something like perl /path/to/perl/script/script.pl '< /path/to/file1/arg1 >' /path/to/file2/. That is, the <, and > become part of the input filename. Commented Jun 25, 2015 at 7:37
  • @Evert thanks so much! I got it working. Yes its shell redirect, i replace it with stdin and stdout, its working as it should now. Commented Jun 25, 2015 at 8:30

1 Answer 1

2

The analog of the shell command:

#!/usr/bin/env python
from subprocess import check_call

check_call("perl script.pl /path/to/file1/ < input > output", shell=True)

is:

#!/usr/bin/env python
from subprocess import check_call

with open('input', 'rb', 0) as input_file, \
     open('output', 'wb', 0) as output_file:
    check_call(["perl", "script.pl", "/path/to/file1/"],
               stdin=input_file, stdout=output_file)

To avoid the verbose code, you could use plumbum to emulate a shell pipeline:

#!/usr/bin/env python
from plumbum.cmd import perl $ pip install plumbum

((perl["script.pl", "/path/to/file1"] < "input") > "output")()

Note: Only the code example with shell=True runs the shell. The 2nd and 3rd examples do not use shell.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.