AttributeError: Wave_write instance has no attribute '__exit__'

AttributeError: Wave_write instance has no attribute '__exit__'

在使用我的教授给我的一些代码用于作业时,我无法按照说明进行更改。我一直在四处寻找并在初始写入周围添加了关闭,但是否可以防止修改起始代码?

代码来自:

调用代码:

def run_menu():

    global CURRENT_TIME

    # Provide a minimal indication that the program has started.
    print(MINIMAL_HELP_STRING)

    # Get the first keystroke.
    c = readchar.readchar()

    # Endless loop responding to the user's last keystroke.
    # The loop breaks when the user hits the QUIT_MENU_KEY.
    while True:

        # Respond to the user's input.
        if c == FORWARD_KEY:

            # Advance the time, looping back around to the start.
            CURRENT_TIME += 1
            if CURRENT_TIME == len(NUMBERS_WAV):
                CURRENT_TIME = 0

            # Concatenate three audio files to generate the message.
            sound.combine_wav_files(TMP_FILE_WAV, YOU_SELECTED_WAV,
                                    NUMBERS_WAV[CURRENT_TIME], AM_WAV)

            # Play the concatenated file.
            sound.Play(TMP_FILE_WAV)

函数代码:

def combine_wav_files(out_file, *files):
    with wave.open(out_file, 'wb') as out:
        with wave.open(files[0], 'rb') as first_in:
            (nchannels, sampwidth, framerate, nframes, comptype, compname) =\
              first_in.getparams()
            out.setparams(first_in.getparams())
        for filename in files:
            with wave.open(filename, 'rb') as cur_in:
                if (cur_in.getnchannels() != nchannels or
                    cur_in.getsampwidth() != sampwidth or
                    cur_in.getframerate() != framerate or
                    cur_in.getcomptype() != comptype or
                    cur_in.getcompname() != compname):
                    raise Exception('Mismatched file parameters: ' + filename)
                out.writeframes(cur_in.readframes(cur_in.getnframes()))

错误信息:

Exception wave.Error: Error('# channels not specified',) in <bound method Wave_write.__del__ of <wave.Wave_write instance at 0x104029e60>> ignored
Traceback (most recent call last):
    File "sample_menu.py", line 144, in <module>
      main()
    File "sample_menu.py", line 25, in main
      run_menu()
    File "sample_menu.py", line 113, in run_menu
      NUMBERS_WAV[CURRENT_TIME], AM_WAV)
    File "/Users/jaredsmith/Desktop/443/P1 Starter Code 2017/sound.py", line 86, in combine_wav_files
      with wave.open(out_file, 'wb') as out:
AttributeError: Wave_write instance has no attribute '__exit__'

我将修复程序放在导入下,它起作用了!

修复(更新):

####
# From http://web.mit.edu/jgross/Public/21M.065/sound.py 9-24-2017    
####

def _trivial__enter__(self):
    return self
def _self_close__exit__(self, exc_type, exc_value, traceback):
    self.close()

wave.Wave_read.__exit__ = wave.Wave_write.__exit__ = _self_close__exit__
wave.Wave_read.__enter__ = wave.Wave_write.__enter__ = _trivial__enter__

这一行的with关键字

with wave.open(out_file, 'wb') as out

暗示 wave.open 已被编写为上下文管理器,但它还没有。取出 with 并改为执行此操作:

out = wave.open(out_file, 'wb')

您正在 with 语句中使用 Wave_write 实例。为了使其正常工作,Wave_write 必须是上下文管理器,这意味着它必须同时实现方法 __enter__()__exit__()。这里情况不同。

您必须将 __exit__ 方法添加到 Wave_write,或者删除 with 语句并手动关闭输入(如果需要)。示例:

out = wave.open(out_file, 'wb'):
    [do_stuff]
out.close() # if Wave_write implements a closing method, use it. the with statement and __exit__() method would have handled that for you.

https://docs.python.org/2/reference/compound_stmts.html#with and https://docs.python.org/2/library/contextlib.html

如果该代码是您的教授给您的,那么他正在使用 python3,其中 wave.open() 返回的对象可用作上下文管理器。您似乎在使用 python2,但事实并非如此。

你应该使用与你的教授相同的版本,否则你会 运行 一直陷入这样的问题。所以你应该切换到 python3.

对我来说,解决方法是添加以下代码,如 JD Smith 在上述线程 () 中提到的那样。 这对我有用。只需在您的导入语句下方添加这些代码行,它就会起作用。 确保添加(导入 wave 语句)

import wave

def _trivial__enter__(self):
    return self
def _self_close__exit__(self, exc_type, exc_value, traceback):
    self.close()

wave.Wave_read.__exit__ = wave.Wave_write.__exit__ = _self_close__exit__
wave.Wave_read.__enter__ = wave.Wave_write.__enter__ = _trivial__enter__