简体   繁体   English

解析从 python 脚本中运行的 perl 脚本的输出

[英]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.我有一个 perl 脚本,我想在 Python 脚本中运行它。 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).我想从 python 脚本中运行这个脚本并获取日志(可能是 .txt 文件)。 Then i would want to further open this txt file and search and parse some values to continue further in my program.然后我想进一步打开这个 txt 文件并搜索和解析一些值以在我的程序中继续。

So how can I invoke the perl script to run and the log be collected in a txt file.那么如何调用 perl 脚本来运行并将日志收集在 txt 文件中。 Then open this text file and search for a string and value.然后打开此文本文件并搜索字符串和值。

Lets say the log output is:假设日志输出是:

"total time: 72" “总时间:72”

I would like to extract the value 72 doing all of this and then use it in my program我想提取值 72 做所有这些,然后在我的程序中使用它

The perl script also has to have input parameters while invoking it. perl 脚本在调用它时还必须有输入参数。 For ex: perl duration.pl -x some_value1 -y some_value2例如: 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 :这是一个假设 Perl 脚本在表单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.run()函数是在 Python 3.5 中引入的,如果您有旧版本,则可以使用subprocess.call()代替:

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

Edit 2 :编辑2

To redirect output to a file when running the Perl script, you can invoke the shell from subprocess.call() like this:要在运行 Perl 脚本时将输出重定向到文件,您可以像这样从subprocess.call()调用 shell:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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