我需要运行一个命令行工具来验证文件并显示一堆有关它的信息。我可以将此信息导出到txt文件,但它包含大量额外数据。我只需要一行文件:
“签名有时间戳:2012年5月24日星期五17:13:16”
时间可能不同,但我只需要提取这些数据并将其放入文件中。有没有一种好的方法可以从命令行本身或python执行此操作?我计划使用Python来查找和下载要验证的文件,然后运行命令行工具进行验证,以便它可以获取数据然后通过电子邮件发送数据。
这是在Windows PC上。
感谢您的帮助
答案 0 :(得分:5)
您不需要使用Python来执行此操作。如果您使用的是Unix环境,可以直接从命令行使用fgrep
并将输出重定向到另一个文件。
fgrep "The signature is timestamped: " input.txt > output.txt
在Windows上,您可以使用:
find "The signature is timestamped: " < input.txt > output.txt
答案 1 :(得分: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下载(可能带有临时名称),然后在temp文件上运行命令行util来获取详细信息,然后smtplib发送电子邮件......
答案 2 :(得分:1)
在python中你可以这样做:
timestamp = ''
with open('./filename', 'r') as f:
timestamp = [line for line in f.readlines() if 'The signature is timestamped: ' in line]
我没有对此进行测试,但我认为它有效。不确定是否有更好的解决方案。
答案 3 :(得分: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)
将其写入文本文件