Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute python scripts from react-js?

I have a use case where I need to execute a local python script from the browser and display the output returned.

I have written my web app using react-js.

My current solution is to launch a local instance of a jupyter notebook (assuming the client is already running it) and make the user execute the prefilled first cell, but I want to be able to do this directly from the browser.

like image 342
Arun Swaminathan Avatar asked Jun 10 '18 09:06

Arun Swaminathan


People also ask

Can we run Python code in React?

This is because React uses a very different syntax and data structures than Python, which makes it difficult for Python developers to adapt to. In this article, we'll map out a road plan for getting started with React, as well as the core prerequisites for diving into React as a Python developer.

Can we run Python in Nodejs?

Note that sys is the module that allows Python to read parameters from your Node. js server, we will pass parameters from server to Python in the next examples. If nothing wrong happens, you will receive this message from the console after running your script.py using Node.


2 Answers

web pages cannot run arbitrary OS commands (such as executing a python scripts) from the browser - due to security reasons

a server has to provide an API for the web page to call (note that Jupyter Notebook is using it's own server to execute commands specified in a browser - python code is NOT executed directly in the browser)

there are many ways how to start a python web server, I personally recommend Flask: http://flask.pocoo.org/

like image 149
Aprillion Avatar answered Sep 22 '22 11:09

Aprillion


If you wish to program in Python but have the code execute in browser, you need either:

A) to run some kind of python program on client machine (separate from browser) which would listen and allow browser to connect to it using some kind of Api (Rest etc);

Or B) transpile your Python to client side Javascript which you inject into the web page client views. There are several tools that support it, such as https://www.transcrypt.org or http://pyjs.org

Or C) use libraries which allow client side Python in browser, such as http://www.skulpt.org (basically similar to B) but does it transparently)

like image 29
Gnudiff Avatar answered Sep 22 '22 11:09

Gnudiff