【问题标题】:Parse output of a perl script run from within a python script解析从 python 脚本中运行的 perl 脚本的输出
【发布时间】:2020-12-31 20:51:14
【问题描述】:

我有一个 perl 脚本,我想在 Python 脚本中运行它。目前,当我从命令提示符运行每个脚本时,我会得到一个小日志。

我想从 python 脚本中运行这个脚本并获取日志(可能是一个 .txt 文件)。然后我想进一步打开这个 txt 文件并搜索和解析一些值以继续在我的程序中继续。

那么我怎样才能调用 perl 脚本来运行并将日志收集到一个 txt 文件中。然后打开此文本文件并搜索字符串和值。

假设日志输出是:

“总时间:72”

我想提取值 72 执行所有这些操作,然后在我的程序中使用它

perl 脚本在调用它时也必须有输入参数。例如:perl duration.pl -x some_value1 -y some_value2

【问题讨论】:

  • 能否请您向我们展示您的代码。详细说明请参考link
  • 您可以使用subprocess.run() 从 Python 运行 Perl 脚本

标签: python perl


【解决方案1】:

这是一个假设 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)

编辑

subprocess.run() 函数是在 Python 3.5 中引入的,如果您有旧版本,可以使用 subprocess.call() 代替:

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

编辑 2

要在运行 Perl 脚本时将输出重定向到文件,您可以从 subprocess.call() 调用 shell,如下所示:

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

【讨论】:

  • get this error, perl.py", line 4, in subprocess.run(["perl", "duration_calc.pl", "-vht", "-bc", " 100", "-bw", "20", "-nss", "1"]) AttributeError: 'module' object has no attribute 'run'
  • 您使用的是哪个 python 版本?然后在 Python 3.5 中添加了subprocess.run() 函数
  • 版本 2.7.2,我认为 subprocess.call() 在这个版本中有效,你能告诉我如何将这个 perl 脚本的输出写入 txt 文件。对于命令行中的 ex,我会执行类似 perl duration.pl > log.txt 的操作
  • 现在这段代码显示:“perl.py”,第 5 行,在 中,open("result.txt") as fh: IOError: [Errno 2] No such file或目录:'result.txt'
  • 这行得通:subprocess.call("perl duration.pl -x 8 -y 9 > result.txt", shell=True)
猜你喜欢
  • 2012-09-05
  • 2010-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-29
  • 2015-11-24
  • 1970-01-01
  • 2011-01-01
相关资源
最近更新 更多