[英]passing arguments to a callback function in Python
I want to know the syntax for passing arguments to a callback function. 我想知道将参数传递给回调函数的语法。
Here is my code : 这是我的代码:
#!/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()
But it's not working... : 但这不起作用...:
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'
I missed sth but I don't understand what...I took a look right here but still stuck at this point :/ 我错过了某事,但我不知道是什么...我在这里看了一下,但仍然停留在这一点:/
好吧,我这样做来管理:
GPIO.add_event_detect(4, GPIO.FALLING, lambda channel,tmp_port=port_nb,tmp_user=dist_user,tmp_ip=dist_ip:Callback(channel,tmp_port,tmp_user,tmp_ip), bouncetime = 1000)
The usual solution for this scenario is to use functools.partial()
. 对于这种情况,通常的解决方案是使用functools.partial()
。 See this article for one explanation with examples: https://www.geeksforgeeks.org/partial-functions-python/ 有关示例的说明,请参见本文: https : //www.geeksforgeeks.org/partial-functions-python/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.