调试不遵守catch语句的python

调试不遵守catch语句的python,python,debugging,syslog,Python,Debugging,Syslog,我正在尝试将avg作为程序的一部分运行。程序通常是自动执行的,所以我看不到python的标准输出 当我通过直接调用来运行程序时,它工作得很好,但是当我通过自动化运行它时,它失败了 它会在syslog->“开始扫描:xxx”中显示,但不会显示“意外错误”或“扫描结果”。也就是说,它失败了,但没有使用catch语句,也没有在“out”变量中报告错误 冒犯功能: # Scan File for viruses # fpath -> fullpath, tname -> filename,

我正在尝试将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()")

到目前为止,这两个想法都是围绕调试代码本身展开的,在此之前,扫描只是一个简单的子进程。调用(命令)和一个简单的syslog输出。with语句中添加了try-catch以帮助调试。

我怀疑错误实际上来自于打开调试文件<代码>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()")

所以我解决了。解决了它,因为我不再使用AVG扫描,而是使用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)

问题是,
out
未在
syslog
的范围内定义-将语句移动到
try
块内,您应该会没事的。不,更改了块,它失败了:(syslog):
Aug 17 15:16:13 be-flouge handler:接收处理:xxx Aug 17 15:16:16 be-flouge handler:开始扫描:xxx
尝试过,它给出了“开始扫描”然后是“完成扫描”,它从未说过扫描结果,也从未说过意外错误。更不用说,在我意识到它不是扫描之前,我没有添加调试。