0

我需要运行一个命令行工具来验证一个文件并显示一堆关于它的信息。我可以将此信息导出到 txt 文件,但其中包含大量额外数据。我只需要一行文件:

“签名带有时间戳:2012 年 5 月 24 日星期四 17:13:16”

时间可能不同,但我只需要提取这些数据并将其放入文件中。有没有从命令行本身或 python 执行此操作的好方法?我计划使用 Python 来定位和下载要验证的文件,然后运行命令行工具来验证它,以便它可以获取数据,然后通过电子邮件发送该数据。

这是在 Windows PC 上。

谢谢你的帮助

4

4 回答 4

5

您不需要使用 Python 来执行此操作。如果您使用的是 Unix 环境,则可以fgrep直接从命令行使用并将输出重定向到另一个文件。

fgrep "The signature is timestamped: " input.txt > output.txt

在 Windows 上,您可以使用:

find "The signature is timestamped: " < input.txt > output.txt
于 2012-08-02T21:52:13.450 回答
2

您提到命令行实用程序“显示”一些信息,因此很可能打印到stdout,因此一种方法是在 Python 中运行该实用程序并捕获输出。

import subprocess
# Try with some basic commands here maybe...
file_info = subprocess.check_output(['your_command_name', 'input_file'])
for line in file_info.splitlines():
    # print line here to see what you get
    if file_info.startswith('The signature is timestamped: '):
        print line # do something here

这应该与“使用 python 下载和定位”非常吻合——这样就可以使用 urllib.urlretrieve 进行下载(可能使用临时名称),然后在临时文件上运行命令行工具以获取详细信息,然后smtplib 发送电子邮件...

于 2012-08-02T22:23:40.747 回答
1

在 python 中,您可以执行以下操作:

timestamp = ''
with open('./filename', 'r') as f:
  timestamp = [line for line in f.readlines() if 'The signature is timestamped: ' in line]

我没有对此进行测试,但我认为它会起作用。不确定是否有更好的解决方案。

于 2012-08-02T22:00:03.517 回答
0

我不太确定您拥有的这个导出文件的确切语法,但 python 的readlines()函数可能对此有所帮助。

h=open(pathname,'r') #opens the file for reading
for line in h.readlines():
    print line#this will print out the contents of each line of the text file

如果文本文件每次都具有相同的格式,那么剩下的就简单了;如果不是,你可以做类似的事情

for line in h.readlines():
    if line.split()[3] == 'timestamped':
         print line
         output_string=line

至于写入文件,您需要打开文件进行写入h=open(name, "w"),然后使用h.write(output_string)将其写入文本文件

于 2012-08-02T22:01:00.130 回答