调试python不会尊重catch语句

时间:2014-08-17 19:07:51

标签: python debugging syslog

我试图将avg作为程序的一部分运行。程序通常是自动执行的,所以我看不到python的标准输出。

当我通过直接调用程序运行程序时,它运行正常,但是当我通过自动化运行它时,它会失败。

它会在syslog中说 - > "开始扫描:xxx",但它从未说过"意外错误"或"扫描结果"。这意味着,它失败了,但没有使用catch语句,或报告" out"变量

违规功能:

# Scan File for viruses
# fpath -> fullpath, tname -> filename, tpath -> path to file
def scan(fpath, tname, tpath):
    syslog("Starting scan of: " + tname)
    command = ["avgscan",
          "--report=" + tpath + "scan_result-" + tname +".txt",
          fpath]
    try:
        out = subprocess.call(command)
        syslog("Scan Results: " + str(out))
    except:
        syslog("Unexpected error: " + sys.exc_info()[0])
    finally:
        syslog("Finished scan()")

到目前为止,这两个想法都围绕着调试代码本身,在此之前,扫描只是一个简单的subprocess.call(命令),带有简单的syslog输出。使用with语句,try catch被添加以帮助调试。

2 个答案:

答案 0 :(得分:1)

我怀疑错误实际上来自打开调试文件; with语句不会阻止异常被引发。事实上,他们通常会提出自己的例外情况。

请注意try / except块范围的更改。

# Scan File for viruses
# fpath -> fullpath, tname -> filename, tpath -> path to file
def scan(fpath, tname, tpath):
    syslog("Starting scan of: " + tname)
    command = ["avgscan",
        "--report=" + tpath + "scan_result-" + tname +".txt",
        fpath]
    try:
        with open(tpath + tname + "-DEBUG.txt", "w") as output:
            out = subprocess.call(command, stdout = output, stderr = output)
            syslog("Scan Results: " + str(out))
    except:
        syslog("Unexpected error: " + sys.exc_info()[0])
    finally:
        syslog("Finished scan()")

答案 1 :(得分:0)

所以我解决了。解决了这个问题,因为我不再使用AVG Scan,而是使用libclamscan。

通过使用直接使用python的扫描程序,结果更快,错误全部消失。如果有人通过搜索遇到这个,这里是我现在使用的代码:

import os.path
import pyclamav.scanfile

def r_scan(fpath):
    viruslist = []
    if os.path.isfile(fpath):
        viruslist = f_scan(fpath, viruslist)
    for root, subFolders, files in os.walk(fpath):
        for filename in files:
            viruslist = f_scan(
                             os.path.join(root, filename), viruslist)
    writeReport(fpath, viruslist)

def f_scan(filename, viruslist):
    result = pyclamav.scanfile(filename)
    if result[0] > 0:
        viruslist.append([result[1], filename])
    return viruslist

def writeReport(fpath, viruslist):
    header = "Scan Results: \n"
    body = ""
    for virusname, filename in viruslist:
        body = body + "\nVirus Found: " + virusname + " : " + filename

    with open(fpath + "-SCAN_RESULTS.txt", 'w') as f:
        f.write(header+body)