简体   繁体   中英

Parse output of a perl script run from within a python script

I have a perl script which i would like to run from within a Python script. Currently, when I run the per script from command prompt I get a small log.

I want to run this script from within the python script and get the log(maybe to a .txt file). Then i would want to further open this txt file and search and parse some values to continue further in my program.

So how can I invoke the perl script to run and the log be collected in a txt file. Then open this text file and search for a string and value.

Lets say the log output is:

"total time: 72"

I would like to extract the value 72 doing all of this and then use it in my program

The perl script also has to have input parameters while invoking it. For ex: perl duration.pl -x some_value1 -y some_value2

Here is an example assuming the Perl script produces a single line of output on the form total time: 72 :

import re
import subprocess

subprocess.run(["perl", "duration.pl", "-x", "8", "-y", "9"], check=True)
with open("result.txt") as fh:
    line = fh.readline()  # assume the script produces a single line output

match_object = re.search(r"total time:\s+(\d+)", line)
if match_object:
    result = match_object.group(1)

Edit :

The subprocess.run() function was introduced in Python 3.5, if you have an older version you can use subprocess.call() instead:

subprocess.call(["perl", "duration.pl", "-x", "8", "-y", "9"])

Edit 2 :

To redirect output to a file when running the Perl script, you can invoke the shell from subprocess.call() like this:

subprocess.call(["perl duration.pl -x 8 -y 9 > result.txt"], shell=True)

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