A solution to pass multiples parameters to your python script is to use a unique json which contains all parameters.
From Nodered to Python : Build your JSON with multiples elements
We build a JSON and pass it in one argument : inject an msg.payload to {} : {"myfirst":"hello","mysecond":"world"}
- Each element is divided in key and value ->
"key":"value"
- Every elements are separated by
,
- JSON is always writed between {}
To receive this message from nodered into your python script :
noderedmsg = json.loads(sys.argv[1]) # read the argument with json library
noderedmsg will be a dictionnarie
value = mydictionnarie["key"]
In our case :
first_parameter = noderedmsg["myfirst"] # in first_parameter you'll find the value. myfirst is the key.
second_parameter = noderedmsg["mysecond"]
myfile= (sys.argv[0]) # argv[0] give the name of python file executed
From Python to Nodered : Build your return as a payload with multiples lines
In your python script :
print("Where does it come from : {}".format(myfile))
print("The first is {}, and the second is {}".format(noderedmsg["myfirst"], noderedmsg["mysecond"]))
Example for Nodered :
[{"id":"d8a446b8227bbacb","type":"inject","z":"f827b63b46b85c49","name":"Now","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"{\"myfirst\":\"hello\",\"mysecond\":\"world\"}","payloadType":"json","x":170,"y":280,"wires":[["c1f609ed5b7e2b1e"]]},{"id":"c1194e81047211de","type":"debug","z":"f827b63b46b85c49","name":"Python return","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":620,"y":280,"wires":[]},{"id":"c1f609ed5b7e2b1e","type":"pythonshell in","z":"f827b63b46b85c49","name":"nodered <-> python","pyfile":"/home/pi/BirdRec/program/Python/my_pythonfile_fornodered.py","virtualenv":"","continuous":false,"stdInData":false,"x":400,"y":280,"wires":[["c1194e81047211de"]]}]
Example for Python [my_pythonfile_fornodered.py] :
# You need to use the librairy to read a json format message
import json
def main(args):
# Read differents elements of execution
myfile= (sys.argv[0]) # argv[0] give the name of python file executed
noderedmsg = json.loads(sys.argv[1]) # read the argument with json library
print("Where does it come from : {}".format(myfile))
print("The first is {}, and the second is {}".format(noderedmsg["myfirst"], noderedmsg["mysecond"]))
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv)) # Return the prints from main()