9

I'm using Node-Red, hosted on a Raspberry Pi for an IoT project.

How do I trigger a Python script that is on the raspi from Node-Red? I want to run a script that updates the text on an Adafruit LCD shield which is sitting on the Pi

Should I be looking to expose the Python script as a web service somehow?

I'm using a Raspberry Pi B+

pronoob
  • 811
  • 1
  • 10
  • 20
  • 1
    Had an issue where I got Permission Denied when trying to execute the sh file from the exec node. For anyone with the same issue, I ran: sudo chmod -R 777 /home/pi/file.sh – pronoob Aug 18 '15 at 00:09

4 Answers4

10

Node-RED supplies an exec node as part of it's core set, which can be used to call external commands, this could be call your python script.

More details of how to use it can be found in the info sidebar when a copy is dragged onto the canvas.

Or you could wrap the script as a web service or just a simple TCP socket, both of which have nodes that can be used to drive them.

hardillb
  • 54,545
  • 11
  • 67
  • 105
  • 1
    Awesome, thanks! Is there any way to pass a variable into the exec node? Would be cool if I could send a tweet or something – pronoob Aug 17 '15 at 23:26
2
  1. I hope you have installed red-node along with Python. If not, install it using following either in Power shell or CMD: npm install -g node-red-contrib-python3-function
  2. After starting node-red, you can find pythonshell node in Node Panel of node-red. Drag and Drop it and double click it to get "node properties" panel, Enter Python.exe path in Name and Python File in Py File and click on Done.
  3. Have and msg-payload node connected to it and Deploy.
  4. Click on PythonShell node input, you will get your python program executed and displayed in output.
1

You can call a Python script with arguments with the exec node command:

python ~/script.py arg1 arg2

in your Python script you can catch the arguments with the sys module:

import sys

var1 = sys.argv[1]
var2 = sys.argv[2]

sys.argv[0] is reserved for the script name.

Eddy
  • 21
  • 2
0

I had a similar challenge with a Raspberry pi 4.

I solved it by using an execute node. On the command slot, enter the path of the python script as follows.

sudo python3 /home/pi/my_script.py

Change the script path to yours. Use the inject node to run the script and the debug node to view your output.

Ensure you grant superuser permission using sudo and you have python3 installed.

  • > Ensure you grant superuser permission using `sudo` This is terrible for introducing security vulnerabilities. Far better to add a specific rule to `/etc/sudoers.d/`, e.g. `nodered ALL=(root) NOPASSWD: somePath` where this point to you script which should be executable and include a "#!" prefix line. – TerryE Aug 18 '22 at 14:45