Как из javascript вызвать python
Перейти к содержимому

Как из javascript вызвать python

  • автор:

Как вызвать функцию Python из Node.js

У меня есть приложение Express NodeJS, но у меня также есть алгоритм MachineLearning для использования в Python. Есть ли способ вызвать функции Python из моего приложения NodeJS, чтобы использовать возможности библиотек MachineLearning?

3 ответа

Самый простой способ, которым я знаю, — использовать пакет «child_process», который поставляется в комплекте с node.

Затем вы можете сделать что-то вроде:

Затем все, что вам нужно сделать, это убедиться, что вы import sys в вашем python script, а затем вы можете получить доступ к arg1 с помощью sys.argv[1] , arg2 с помощью sys.argv[2] и т.д.

Чтобы отправить данные обратно в node, выполните следующие действия в python script:

И затем node может прослушивать данные, используя:

Так как это позволяет передавать несколько аргументов в script с помощью spawn, вы можете реструктурировать python script, чтобы один из аргументов решал, какую функцию вызывать, а другой аргумент передается этой функции и т.д..

Надеюсь, это было ясно. Дайте мне знать, если что-то нуждается в разъяснении.

Вызов функции Python из кода JavaScript

Я хотел бы вызвать функцию Python из кода JavaScript, потому что в JavaScript нет альтернативы для выполнения того, что я хочу. Это возможно? Не могли бы вы настроить приведенный ниже фрагмент для работы?

/pythoncode.py содержит функции, использующие расширенные библиотеки, которые не имеют простого в написании эквивалента в JavaScript:

4 ответа

Все, что вам нужно, это сделать ajax-запрос к вашему pythoncode. Вы можете сделать это с помощью jquery http://api.jquery.com/jQuery.ajax/ или использовать только javascript

Общение через процессы

Python: этот блок кода Python должен возвращать случайные температуры.

Javascript (Nodejs): Здесь нам нужно создать новый дочерний процесс, чтобы запустить наш код Python, а затем получить вывод на печать.

Из document.getElementsByTagName я думаю, вы запускаете JavaScript в браузере.

Традиционный способ предоставления функциональности JavaScript, работающему в браузере, — это вызов удаленного URL с использованием AJAX. X в AJAX предназначен для XML, но в настоящее время все используют JSON вместо XML.

Например, используя jQuery, вы можете сделать что-то вроде:

Вам нужно будет реализовать веб-сервис python на стороне сервера. Для простых веб-сервисов мне нравится использовать Flask.

Типичная реализация выглядит так:

Вы можете запустить IronPython (разновидность Python.Net) в браузере с помощью silverlight, но я не знаю, доступен ли NLTK для IronPython.

Обычно вы выполняете это с помощью ajax-запроса, который выглядит следующим образом:

Getting started#

Try Pyodide in a REPL directly in your browser (no installation needed).

Setup#

To include Pyodide in your project you can use the following CDN URL:

You can also download a release from GitHub releases or build Pyodide yourself. See Downloading and deploying Pyodide for more details.

The pyodide.js file defines a single async function called loadPyodide() which sets up the Python environment and returns the Pyodide top level namespace .

Running Python code#

Python code is run using the pyodide.runPython() function. It takes as input a string of Python code. If the code ends in an expression, it returns the result of the expression, translated to JavaScript objects (see Type translations ). For example the following code will return the version string as a JavaScript string:

After importing Pyodide, only packages from the standard library are available. See Loading packages for information about loading additional packages.

Complete example#

Create and save a test index.html page with the following contents:

Alternative Example#

Accessing Python scope from JavaScript#

All functions and variables defined in the Python global scope are accessible via the pyodide.globals object.

For example, if you run the code x = numpy.ones([3,3]) in Python global scope, you can access the global variable x from JavaScript in your browser’s developer console with pyodide.globals.get("x") . The same goes for functions and imports. See Type translations for more details.

You can try it yourself in the browser console. Go to the Pyodide REPL URL and type the following into the browser console:

You can assign new values to Python global variables or create new ones from Javascript.

Accessing JavaScript scope from Python#

The JavaScript scope can be accessed from Python using the js module (see Importing JavaScript objects into Python ). We can use it to access global variables and functions from Python. For instance, we can directly manipulate the DOM:

Name already in use

Work fast with our official CLI. Learn more about the CLI.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

In this example we will be using the Python library Requests in JavaScript.
Note: Using this example in the real world is not a good idea. Just use a JavaScript HTTP library (superagent, request) instead.

The following python versions are supported: 2.6, 2.7, 3.3, 3.4, 3.5, 3.6.
Python 2 is required to build regardless of your target python version.

Download the installer from python.org

If you have multiple python versions on your system, you may want to set a target python version when you install. This can be done by passing something like —python_version=3.3 to npm install .

Lets start coding.

First we need to import the library.

Then we need to import requests.

Then we can make a new request.

Lets break this down.
We are calling the method requests.post with a url as the first argument and then passing kwargs through py.kwargs() .
The method returns a py.Object object which can be manipulated in several ways.

Getting an Attribute

To get an attribute, you can use o.attr_name (the same as you do in Python).

Getting a Value from a Dict

To get a value from a dict, you can use o.$key , this is equal to o[«key»] in Python.

Getting a Value from a List or Tuple

To get a value from a list or tuple, you can use o[key] (the same as you do in Python).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *