繁体   English   中英

(python)从回调中查找父函数的参数

[英](python) Finding the argument of a parent function from a callback

我如何才能找到给该呼叫一个函数参数callback函数,从内callback

以下代码(不完整)将启动一个音频流,该音频流将调用回调函数。 它使用pyaudio。

现在, callback函数中包含硬编码的内容。 我正在努力摆脱这些。

我已经阅读了pyaudio文档,但似乎无法将额外的参数传递给callback函数。 我已经阅读了对我来说似乎很有趣的inspect python模块,其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)

您可以执行类似的操作来为传递的回调创建作用域吗?

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))

尽管答案已经被接受,但我想展示一种替代方法,例如从技术上讲,您可以通过使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM