从回调中查找父函数的参数

2024-10-02 00:28:18 发布

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

如何从callback中找到给定给调用callback函数的函数的参数

下面的代码(不完整)将启动调用回调函数的音频流。它使用pyaudio

现在,callback函数中有硬编码的内容。我正试图摆脱这些

我已经阅读了pyaudio文档,似乎无法向callback函数传递额外的参数。我读过关于inspectpython模块的书,它的getsourcegetouterframes对我来说似乎很有趣,希望能够得到PlayStream函数的参数,但这并没有让我有所收获

如何从callback中引用SoundGeneratorObject参数

def PlayStream(SoundGeneratorObject):
    p = pyaudio.PyAudio()
    stream = p.open(format = p.get_format_from_width(SoundGeneratorObject.WIDTH), 
                 channels = SoundGeneratorObject.CHANNELS, 
                 rate = SoundGeneratorObject.BITRATE, 
                 frames_per_buffer = SoundGeneratorObject.CHUNKSIZE,
                 output = True,
                 stream_callback = callback)
    stream.start_stream()
    while stream.is_active():
        time.sleep(0.1)
    stream.stop_stream()
    stream.close()
    p.terminate()

def callback(in_data, frame_count, time_info, status_flags):
    signal = waves.next()
    return (signal, pyaudio.paContinue)

waves = SoundGenerator()
PlayStream(waves)

Tags: 函数代码format编码stream参数signaltime
2条回答

虽然答案已被接受,但我想展示一个替代方案,即如何从技术上使用inspectglobals()从父函数访问参数,此示例将起作用:

import inspect

# as argument
SoundGeneratorObject = 'Hello World'

def PlayStream(SoundGeneratorObject):
    a, b, c = 8, 9, 10
    print "do a callback"
    callback(a, b, c)

def callback(a, b, c):
    print a, b, c
    # inspect.stack[1][3] can get the function name that called the callback
    # inner globals then access to the function by its name
    # func_code.co_varnames will then get the argument name from the function
    # since you only have 1 argument, that's why I use index [0]
    # the outer globals will then access the argument value by its name
    print globals()[globals()[inspect.stack()[1][3]].func_code.co_varnames[0]]

# call the parent function
PlayStream(SoundGeneratorObject)

do a callback
8 9 10
Hello World # successfully get the argument value

您可以这样做来为正在传递的回调创建一个作用域吗

def callback_maker(waves):
    def callback(in_data, frame_count, time_info, status_flags):
        # do stuff (waves is in scope)
        signal = waves.next()
        return (signal, pyaudio.paContinue)
    return callback

如果可以,请这样使用:

stream = p.open(format = p.get_format_from_width(SoundGeneratorObject.WIDTH), 
                channels = SoundGeneratorObject.CHANNELS, 
                rate = SoundGeneratorObject.BITRATE, 
                frames_per_buffer = SoundGeneratorObject.CHUNKSIZE,
                output = True,
                stream_callback = callback_maker(SoundGeneratorObject))

相关问题 更多 >

    热门问题