简体   繁体   中英

Running python script from perl, with argument to stdin and saving stdout output

My perl script is at path:

a/perl/perlScript.pl

my python script is at path:

a/python/pythonScript.py

pythonScript.py gets an argument from stdin, and returns result to stdout. From perlScript.pl , I want to run pythonScript.py with the argument hi to stdin, and save the results in some variable. That's what I tried:

my $ret = `../python/pythonScript.py < hi`;                   

but I got the following error:

The system cannot find the path specified.            

Can you explain the path can't be found?

The qx operator (backticks) starts a shell ( sh ), in which prog < input syntax expects a file named input from which it will read lines and feed them to the program prog . But you want the python script to receive on its STDIN the string hi instead, not lines of a file named hi .

One way is to directly do that, my $ret = qx(echo "hi" | python_script) .

But I'd suggest to consider using modules for this. Here is a simple example with IPC::Run3

use warnings;
use strict;
use feature 'say';

use IPC::Run3;

my @cmd = ('program', 'arg1', 'arg2');

my $in = "hi";

run3 \@cmd, \$in, \my $out;

say "script's stdout: $out";

The program is the path to your script if it is executable, or perhaps python script.py . This will be run by system so the output is obtained once that completes, what is consistent with the attempt in the question. See documentation for module's operation.

This module is intended to be simple while " satisfy 99% of the need for using system , qx , and open3 [...] . For far more power and control see IPC::Run .

You're getting this error because you're using shell redirection instead of just passing an argument

../python/pythonScript.py < hi

tells your shell to read input from a file called hi in the current directory, rather than using it as an argument. What you mean to do is

my $ret = `../python/pythonScript.py hi`; 

Which correctly executes your python script with the hi argument, and returns the result to the variable $ret .

The Some of the other answers assume that hi must be passed as a command line parameter to the Python script but the asker says it comes from stdin.

Thus:

my $ret = `echo "hi" | ../python/pythonScript.py`;

To launch your external script you can do

system "python ../python/pythonScript.py hi";

and then in your python script

import sys
def yourFct(a, b):
    ...

if __name__== "__main__":
    yourFct(sys.argv[1])

you can have more informations on the python part here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM