How to trigger Python script on Raspberry Pi from Node-Red
Asked Answered
B

4

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+

Ballast answered 17/8, 2015 at 19:7 Comment(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.shBallast
A
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.

Accordion answered 17/8, 2015 at 19:27 Comment(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 somethingBallast
P
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.
Pancake answered 11/2, 2019 at 15:33 Comment(0)
D
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.

Dripdry answered 20/6, 2018 at 10:6 Comment(0)
C
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.

Cavatina answered 15/3, 2022 at 14:48 Comment(1)
> 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.Semination

© 2022 - 2024 — McMap. All rights reserved.