[英]Read a text file contents from second line in python
I wrote a python code which executes the bash command and save the output in txt file, now i want to read the txt file which actually contains details from line 2 always, and print true if output exists and send a mail to the user. 我编写了一个python代码,该代码执行bash命令并将输出保存在txt文件中,现在我想读取txt文件,该文件实际上始终包含第2行中的详细信息,如果输出存在,则输出true并向用户发送邮件。
Looking for a further solution how I can read specific second line output of file output.txt and print true if the line exists to send a mail to the user otherwise goodbye. 寻找进一步的方案我怎么能读文件output.txt中的特定的第二输出线,如果线存在将邮件发送给用户,否则再见打印真实。
Am very new to this approach, please help with your guidance. 这种方法非常新,请提供指导。 TIA.
TIA。
import subprocess
p = subprocess.Popen("bash command > output.txt", stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
p_status = p.wait()
print "command exit status/return code: ", p_status
Above code prints the output in the txt file in the below format 上面的代码以以下格式在txt文件中输出输出
PID PPID %CPU ELAPSED COMMAND
3435 1 0 4-05:20:09
Requirement: Read from "3435 1 0 4-05:20:09 "
this line and print true as line exist and send a mail to user. 要求:读自
"3435 1 0 4-05:20:09 "
这条线,并打印成线存在的真实和发送邮件到用户。 If not output after "PID PPID %CPU ELAPSED COMMAND"
it should send no mail 如果在
"PID PPID %CPU ELAPSED COMMAND"
之后未输出,则不应发送邮件
you can use it like this: 您可以像这样使用它:
lines = output.split('\n')
Now you can access lines by index eg lines[1]
or lines[1:]
. 现在,您可以按索引访问行,例如
lines[1]
或lines[1:]
。
You need to remove > output.txt
from your command to get the output in output
variable instead of output.txt file 您需要从命令中删除
> output.txt
才能在output
变量而不是output.txt文件中获取输出
You can create list of lines from a file like this: 您可以像这样从文件创建行列表:
with open('output.txt') as input_file:
lines_list = input_file.readlines()
if len(lines_list) > 1:
lines_list=lines_list[1:] # drop the first line
send_mail()
else:
print ("else condition")
you open a file for reading using "r"
and you build a list of lines. 您使用
"r"
打开一个文件进行读取,并建立了一个行列表。 if the list is longer then 1, you build a new list by dropping the first line 如果列表长于1,则通过删除第一行来构建新列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.