Run python functions by execute node

Hi, I have a python script with simple functions:

import sys

a = sys.argv[1]
b = int(sys.argv[2])

class Hello:

def __init__(self, a, b):
	self.a = a
	self.b = b
	
def hello(self, a):
	name = 'hello, ' + self.a
	print(name)
	
def square(self, b):
	print(self.b ** 2)

How do I run hello and square functions separately from Execute Node? eg, "python test.py John 5"?

How would you do it from a command line outside of NR?

use exec node to run "python myfile.py" etc

It isn't clear exactly what you don't know how to do. If you want to run the script via an exec node then put the command in the exec node and it should run. Use the full path to the myfile.py command so it knows where to find it. You may need to specify the full path to the python command too. So you might have to use something like
/usr/bin/python /home/user/myfile.py

If that isn't what you want to do then please try to explain in more detail.

I have some python scripts that need to import libraries, either public like numpy or my own libraries, under a virtual environment. Therefore I am thinking to call the virtual environment and run the script under Exec Node.

The scripts are under Class and Function structures. I am not sure how to structure them best to be run by Node-Red, but these are how I run them in Jupyter Notebook/ Spyder.

As I understand Python Function Node cannot run the code under virtual environment, not sure about Pythonshell Node.

Use the core Exec node and run whatever command you would run in a terminal. If you need to run more than one command then put them in a shell script and call that from the Exec node.

for example, if I want to run the "square" function, what should be the command and arguments?

Exactly the same in the Exec node as in the terminal. Or do you mean you don't know how to run it in a terminal? In that case that isn't a node red issue.

I don't know a lot of Python but it seems to me that the script you posted is not capable of running the square function as there is no code in there to run it. It is defined as a class member but you are not calling it anywhere.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.