简体   繁体   English

Python中的错误和警告处理

[英]Error and Warning Handling in Python

I'm trying to make a script that handles errors and warnings from other scripts, it can be other python or bash scripts. 我正在尝试制作一个处理其他脚本中的错误和警告的脚本,它可以是其他python或bash脚本。

The only way I found to do this is by using Popen, I execute the script using Popen and store the stderr into a variable. 我发现执行此操作的唯一方法是使用Popen,我使用Popen执行脚本并将stderr存储到变量中。

Checking the returncode of Popen I can say if the stderr is a warning (returncode 0, the script ran successfully) or if it is in fact an error (returncode 1, the script did not run successfully). 检查Popen的返回码,我可以说stderr是一个警告(返回码0,脚本已成功运行)还是实际上是一个错误(返回码1,脚本未成功运行)。

But there are some scripts that even with error they continue the commands and so the returncode is 0 like it was some warning or the script did run successfully. 但是有些脚本即使执行错误也可以继续执行命令,因此返回码为0,就像警告或脚本成功运行一样。 How can I handle this sort of thing? 我该如何处理这种事情?

Here are some samples to get a full understanding: 以下是一些示例,可让您全面了解:

sshpass -p password sftp -q username@host << EOF
cd Export
get file.csv
EOF

This bash script gives me an error that it cannot find the file.csv, ok. 这个bash脚本给我一个错误,它找不到file.csv,好。

File "/Export/file.csv" not found.

This python script executes the script above. 这个python脚本执行上面的脚本。

script = 'bash_script'
proc = subprocess.Popen("bash {}.sh ".format(script), stderr=subprocess.PIPE, shell=True)
(stdout, stderr) = proc.communicate()
if (proc.returncode) and (stderr != ''):
      print("\n[ERROR]:\n" + str(stderr))
elif (not proc.returncode) and (stderr != ''):
      print("\n[WARNING]:\n" + str(stderr))
else # (not proc.returncode) and (stderr == '')
      print("\n[SUCCESS]\n")

But executing the script above I get: 但是执行上面的脚本我得到:

[WARNING]:
File "/Export/file.csv" not found

When it should be: 什么时候应该是:

[ERROR]:
File "/Export/file.csv" not found

This happens because the returncode is 0 and the error went to stderr as expected. 发生这种情况是因为returncode为0,并且错误按预期到达了stderr。

How can I handle this case? 我该如何处理? What is the best way to diferentiate errors from warnings? 从警告中区分错误的最佳方法是什么? Why the sftp command is returning 0 when it should be returning 1 which corresponds to an error? 为什么sftp命令在应返回1(对应于错误)时返回0?

Instead of trying to do this entirely from python, I suggest you implement logging in the bash scripts. 建议您不要在bash脚本中实现日志记录,而不是尝试完全从python做到这一点。 In python, you can simply read the error from the logs like: 在python中,您可以简单地从日志中读取错误,例如:

fault = ""
error = ""
warning = ""
with open('log.txt','r') as f:
    x = f.readline()
    if 'error' in x.lower():
       fault = "error"
       error = x
       print("The type is {} and it says:\n {}".format(fault,error))
    elif 'warning' in x.lower():
       fault = "warning"
       warning = x
       print("The type is {} and it says:\n {}".format(fault,warning))

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

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