python - 将参数传递给 Python 中的回调函数

标签 python callback arguments

我想知道将参数传递给回调函数的语法。

这是我的代码:

#!/usr/bin/env python3
import sys,os,time
import RPi.GPIO as GPIO
import subprocess

flag_callback=True

def Callback(channel,port_nb,dist_user,dist_ip):
        global flag_callback
        flag_callback=False
        print('Button Pushed. SSH Tunnel open on port: \"{}\" until reboot.'.format(port_nb))
        bashCommand = "nohup ssh -NR {}:localhost:22 {}@{}".format(port_nb,dist_user,dist_ip)
        subprocess.Popen(bashCommand.split(),
                stdout=open('/dev/null', 'w'),
                stderr=open('logfile.log', 'a'),
                preexec_fn=os.setpgrp
                )

def main():
        if len(sys.argv) > 1:
                port_nb=sys.argv[1]
        else:
                port_nb='2222'

        if len(sys.argv) > 2:
                dist_user=sys.argv[2]
        else:
                dist_user='martin'

        if len(sys.argv) > 3:
                dist_ip = sys.argv[3]
        else:
                dist_ip='192.168.11.111'
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.add_event_detect(4, GPIO.FALLING, callback = Callback(port_nb,dist_user,dist_ip), bouncetime = 1000)
        try:
                while(flag_callback):
                        time.sleep(1)
        except:
                pass

if __name__== "__main__":
  main()

但是它不起作用......:

Traceback (most recent call last):
  File "./OnPushButton_PULLUP.py", line 55, in <module>
    main()
  File "./OnPushButton_PULLUP.py", line 47, in main
    GPIO.add_event_detect(4, GPIO.FALLING, callback = Callback(port_nb,dist_user,dist_ip), bouncetime = 1000)
TypeError: Callback() missing 1 required positional argument: 'dist_ip'

我错过了某事,但我不明白是什么...我看了一下吧 here但仍然停留在这一点上:/

最佳答案

这种情况的通常解决方案是使用functools.partial()。请参阅这篇文章以获取示例说明:https://www.geeksforgeeks.org/partial-functions-python/

关于python - 将参数传递给 Python 中的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57109719/

相关文章:

python - 有没有办法检查子进程是否仍在运行?

javascript - Undefined 不是 Jquery 脚本中的函数

javascript - Angular - 订阅http服务回调

c - C 函数的参数是相反的

bash - 如何输出 Bash 函数的每个参数?

c pthread_create 字符串参数

python - 如何在 pytest 中进行自定义比较?

Python 的 Sklearn ngram 准确度随着 ngram 长度的增加而降低

python - 将 Object dtype 列转换为数据框 Pandas 中的 Number Dtype

javascript .catch() 的一个回调和 .then() 的另一个回调?