Pass function and arguments from node.js to Python
Last Updated :
04 Sep, 2022
Prerequisites: How to run python scripts in node.js using the child_process module.
In this article, we are going to learn how to pass functions and arguments from node.js to Python using child_process.
Although Node.js is one of the most widely used web development frameworks, it lacks machine learning, deep learning, and artificial intelligence libraries. Python, fortunately, supports all of these and many more. Fortunately, those who are unfamiliar with the Django Framework but who utilize the Node.js framework can run Python using the child_process module for Node.js.
The Node.js Child Process module allows us to run scripts or commands written in languages other than JavaScript (like Python, Java, and C++). Machine learning algorithms, deep learning algorithms, and many other capabilities provided by the Python library may be integrated into a Node.js application. We can use Child Process to execute Python scripts in Node.js applications and feed data into and out of Python scripts.
As you might be aware, what child_process basically does is sort of under the hood run the command you provide it with, along with the command line arguments. We can use this very fact to pass functions and arguments from node.js to python.
Syntax: python3 -c <command>
Example:
So basically there is a -c option that can be used to directly run commands provided as a string without having to create a python file.
python3 -c "print('Hello World');"
Output:
Stepwise Implementation
Step 1: Here we have created a file name compliment.py, whose job is to output a gender specific compliment as soon as a call to compliment.giveMe() is made. It takes a Boolean argument isHe which is used to identify the gender of the person asking for the compliment. The following is the code:
Python3
import random
def output(compliments):
print(random.choice(tuple(compliments)))
def giveMe(isHe):
she = [
"I miss your grin.",
"You're an incredible buddy.",
"I can't believe I met someone like you.",
"I feel thrilled every time I see you.",
"I adore making you laugh.",
"You're my greatest friend.",
"I'll always have your back.",
"I adore every inch of you— even your toes.",
"You have a seductive personality.",
"You're my queen.",
"I miss you even when you haven't left yet.",
"I feel happy to be with you.",
"You always know how to make me feel at home.",
"I can totally be myself with you," "I love your style.",
"I love your style.",
]
he = [
"What did you do to become in such great shape?\
I'm interested in learning more about your training\
regimen",
"I like men who take care of themselves",
"Wow, you're extremely gorgeous!",
"What sort of deodorant are you wearing today? It smells\
fantastic! ",
"Your eyes have a nice look to them. I find it simple to\
become lost in them. It really makes you look like you have\
something deep to think about.",
"Have you experimented with your hair? It appeals to me much.",
"What sort of shoes are you wearing today? You should wear\
it like that more often!",
"Your posture is quite straight, which I admire. That must \
have taken a long time for you to perfect ",
"I'm quite impressed with how well you look after your health\
. What do you do to keep your work-life balance?",
"I admire how gentlemanly you are at all times. You are living\
proof that chivalry still exists ",
"You're very amusing. Your wonderful sense of humour is always\
appreciated ",
"I appreciate your thoughtfulness. Finding a man who is kind\
might be challenging ",
"I believe you comprehend what I'm saying. In the past, I've\
had difficulty finding folks who comprehend what I'm saying \
and thinking. I appreciate you always taking the time to learn\
about me.",
"I'm blown away by how composed you are in stressful situations\
. It makes working through difficult situations a lot simpler. ",
"You're incredibly good at active listening. I can always tell \
whether you're paying attention to what I'm saying. That is \
very appreciated ",
]
if isHe:
output(he)
else:
output(she)
Step 2: Here, we have created a file named index.js which is used to provide the Boolean argument to call the function compliment.giveMe() from node.js. to run the code.
JavaScript
import {spawn} from "child_process";
let argument = "True";
const pythonProcess = spawn('python3', ['-c',
`import compliment; compliment.giveMe(${argument});`]);
pythonProcess.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
pythonProcess.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
pythonProcess.on('exit', (code) => {
console.log(`Python process ended with code: ${code}`);
});
Output:
Similar Reads
Python Function Parameters and Arguments
Parameters are variables defined in a function declaration. This act as placeholders for the values (arguments) that will be passed to the function. Arguments are the actual values that you pass to the function when you call it. These values replace the parameters defined in the function. Although t
3 min read
Pass list as command line argument in Python
The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. One of them is sys module. sys Module A module is a file containing Python definiti
3 min read
How to print command line arguments passed to the script in Node.js ?
Node.js is an open-source and cross-platform runtime environment built on Chrome's V8 engine that enables us to use JavaScript outside the browser. Node.js helps us to use build server-side applications using JavaScript. In Node.js if you want to print the command line arguments then we can access
2 min read
How to communicate JSON data between Python and Node.js ?
The following article covers how to communicate JSON data between Python and Node.js. Suppose we are working with the Node.js application, and we want to make use of a specific library that is only available in python or vice versa. We should be able to share the results from one language to another
7 min read
Command Line Arguments in Python
The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. The three most common are: Table of ContentUsing sys.argvUsing getopt moduleUsing a
5 min read
How to call a function in Python
Python is an object-oriented language and it uses functions to reduce the repetition of the code. In this article, we will get to know what are parts, How to Create processes, and how to call them.In Python, there is a reserved keyword "def" which we use to define a function in Python, and after "de
5 min read
How to Parse Command Line Arguments in Node ?
Command-line arguments, in the context of a command-line interface (CLI), are text strings that provide extra information to a program when it is executed.In Nodejs, these arguments are accessible through an array known as argv (arguments values), where the shell passes all received command-line arg
3 min read
Difference Between Node.js and Python
Node.js and Python are two of the most popular programming languages for backend development. Each has its own strengths and weaknesses, and the choice between them often depends on the specific requirements of the project. This article provides a detailed comparison of Node.js and Python, highlight
4 min read
Executing functions with multiple arguments at a terminal in Python
Commandline arguments are arguments provided by the user at runtime and gets executed by the functions or methods in the program. Python provides multiple ways to deal with these types of arguments. The three most common are: Using sys.argv Using getopt module/li> Using argparse module The Python
4 min read
Python | Set 6 (Command Line and Variable Arguments)
Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5) This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python. Command Line Arguments Till now, we have taken input in python using raw_input() or input() [for integers].
2 min read