无法从with语句获取返回值?

2024-06-16 00:04:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试访问网络扫描仪,通过此代码扫描文档。这是library和我正在使用的代码

import sane
sane.init()

class saneScanner(object):
    def __init__(self, URI):
        self.URI = URI
    def __enter__(self):
        self.dev = sane.open(self.URI)
        return self.dev
    def __exit__(self, exception_type, exception_value, traceback):
        self.dev.close()
        print(exception_type, exception_value, traceback)

def t():
    with saneScanner("airscan:HP OfficeJet Pro 8020 series [973B68]") as k:
        return k.opt

print(t())

我最终犯了这个错误

Traceback (most recent call last):
  File "with.py", line 23, in <module>
    print(t())
  File "/usr/local/lib/python3.7/dist-packages/sane.py", line 86, in __repr__
    curValue = repr(getattr(self.scanDev, self.py_name))
  File "/usr/local/lib/python3.7/dist-packages/sane.py", line 232, in __getattr__
    return d['dev'].get_option(opt.index)
_sane.error: SaneDev object is closed

如果从函数t()中删除return语句,则不会引发错误。你能告诉我哪里出了问题吗

提前谢谢


Tags: 代码inpydevselfreturninitdef