标签归档:node-js

结合使用node.js和Python

问题:结合使用node.js和Python

Node.js非常适合我们的Web项目,但是很少有需要Python的计算任务。我们已经为他们准备了Python代码。我们非常关心速度,如何以异步非阻塞方式从node.js调用Python“工作者”的最优雅方法是什么?

Node.js is a perfect match for our web project, but there are few computational tasks for which we would prefer Python. We also already have a Python code for them. We are highly concerned about speed, what is the most elegant way how to call a Python “worker” from node.js in an asynchronous non-blocking way?


回答 0

对于node.js和Python服务器之间的通信,如果两个进程都在同一服务器上运行,则我将使用Unix套接字,否则将使用TCP / IP套接字。对于封送处理协议,我将使用JSON或协议缓冲区。如果线程化Python成为瓶颈,请考虑使用Twisted Python,它提供与node.js相同的事件驱动的并发性。

如果您喜欢冒险,请学习clojureclojurescriptclojure-py),您将获得与Java,JavaScript(包括node.js),CLR和Python上的现有代码可运行并互操作的相同语言。通过使用clojure数据结构,您将获得出色的编组协议。

For communication between node.js and Python server, I would use Unix sockets if both processes run on the same server and TCP/IP sockets otherwise. For marshaling protocol I would take JSON or protocol buffer. If threaded Python shows up to be a bottleneck, consider using Twisted Python, which provides the same event driven concurrency as do node.js.

If you feel adventurous, learn clojure (clojurescript, clojure-py) and you’ll get the same language that runs and interoperates with existing code on Java, JavaScript (node.js included), CLR and Python. And you get superb marshalling protocol by simply using clojure data structures.


回答 1

这听起来像一个零MQ非常合适的场景。这是一个消息传递框架,与使用TCP或Unix套接字类似,但功能更强大(http://zguide.zeromq.org/py:all

有一个库使用zeroMQ提供了一个运行良好的RPC框架。它称为zeroRPC(http://www.zerorpc.io/)。这是你好世界。

Python“ Hello x”服务器:

import zerorpc

class HelloRPC(object):
    '''pass the method a name, it replies "Hello name!"'''
    def hello(self, name):
        return "Hello, {0}!".format(name)

def main():
    s = zerorpc.Server(HelloRPC())
    s.bind("tcp://*:4242")
    s.run()

if __name__ == "__main__" : main()

和node.js客户端:

var zerorpc = require("zerorpc");

var client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");
//calls the method on the python object
client.invoke("hello", "World", function(error, reply, streaming) {
    if(error){
        console.log("ERROR: ", error);
    }
    console.log(reply);
});

反之亦然,node.js服务器:

var zerorpc = require("zerorpc");

var server = new zerorpc.Server({
    hello: function(name, reply) {
        reply(null, "Hello, " + name, false);
    }
});

server.bind("tcp://0.0.0.0:4242");

和python客户端

import zerorpc, sys

c = zerorpc.Client()
c.connect("tcp://127.0.0.1:4242")
name = sys.argv[1] if len(sys.argv) > 1 else "dude"
print c.hello(name)

This sounds like a scenario where zeroMQ would be a good fit. It’s a messaging framework that’s similar to using TCP or Unix sockets, but it’s much more robust (http://zguide.zeromq.org/py:all)

There’s a library that uses zeroMQ to provide a RPC framework that works pretty well. It’s called zeroRPC (http://www.zerorpc.io/). Here’s the hello world.

Python “Hello x” server:

import zerorpc

class HelloRPC(object):
    '''pass the method a name, it replies "Hello name!"'''
    def hello(self, name):
        return "Hello, {0}!".format(name)

def main():
    s = zerorpc.Server(HelloRPC())
    s.bind("tcp://*:4242")
    s.run()

if __name__ == "__main__" : main()

And the node.js client:

var zerorpc = require("zerorpc");

var client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");
//calls the method on the python object
client.invoke("hello", "World", function(error, reply, streaming) {
    if(error){
        console.log("ERROR: ", error);
    }
    console.log(reply);
});

Or vice-versa, node.js server:

var zerorpc = require("zerorpc");

var server = new zerorpc.Server({
    hello: function(name, reply) {
        reply(null, "Hello, " + name, false);
    }
});

server.bind("tcp://0.0.0.0:4242");

And the python client

import zerorpc, sys

c = zerorpc.Client()
c.connect("tcp://127.0.0.1:4242")
name = sys.argv[1] if len(sys.argv) > 1 else "dude"
print c.hello(name)

回答 2

如果您安排将Python工作进程放在单独的进程中(长时间运行的服务器类型进程或按需生成的子进程),则与之进行的通信在node.js端将是异步的。UNIX / TCP套接字和stdin / out / err通信本身在节点中是异步的。

If you arrange to have your Python worker in a separate process (either long-running server-type process or a spawned child on demand), your communication with it will be asynchronous on the node.js side. UNIX/TCP sockets and stdin/out/err communication are inherently async in node.


回答 3

我也会考虑Apache Thrift http://thrift.apache.org/

它可以在几种编程语言之间架起桥梁,非常高效,并支持异步或同步调用。在此处查看完整功能http://thrift.apache.org/docs/features/

多语言可能对将来的计划很有用,例如,如果您以后想要在C ++中完成部分计算任务,则可以很容易地使用Thrift将其添加到混合中。

I’d consider also Apache Thrift http://thrift.apache.org/

It can bridge between several programming languages, is highly efficient and has support for async or sync calls. See full features here http://thrift.apache.org/docs/features/

The multi language can be useful for future plans, for example if you later want to do part of the computational task in C++ it’s very easy to do add it to the mix using Thrift.


回答 4

使用thoonk.jsthoonk.py取得了很多成功。Thoonk利用Redis(内存中的键值存储)为您提供供稿(如发布/订阅),队列和作业模式进行通信。

为什么这比unix套接字或直接tcp套接字更好?总体性能可能会有所下降,但是Thoonk提供了一个非常简单的API,该API简化了手动处理套接字的过程。Thoonk还可帮助您轻松实现一个分布式计算模型,该模型可让您扩展python worker来提高性能,因为您只是启动了python worker的新实例并将它们连接到同一Redis服务器。

I’ve had a lot of success using thoonk.js along with thoonk.py. Thoonk leverages Redis (in-memory key-value store) to give you feed (think publish/subscribe), queue and job patterns for communication.

Why is this better than unix sockets or direct tcp sockets? Overall performance may be decreased a little, however Thoonk provides a really simple API that simplifies having to manually deal with a socket. Thoonk also helps make it really trivial to implement a distributed computing model that allows you to scale your python workers to increase performance, since you just spin up new instances of your python workers and connect them to the same redis server.


回答 5

我建议使用一些工作队列,例如使用出色的Gearman,它将为您提供一种很好的方式来调度后台作业,并在处理后异步获取其结果。

Digg(在许多其他公司中)经常使用的优点是,它提供了一种强大,可扩展和强大的方法,使任何语言的工作人员都能与任何语言的客户进行交谈。

I’d recommend using some work queue using, for example, the excellent Gearman, which will provide you with a great way to dispatch background jobs, and asynchronously get their result once they’re processed.

The advantage of this, used heavily at Digg (among many others) is that it provides a strong, scalable and robust way to make workers in any language to speak with clients in any language.


回答 6

更新2019

有几种方法可以做到这一点,以下是按复杂度从高到低排列的清单

  1. Python Shell,您将流写入python控制台,它将回写给您
  2. Redis Pub Sub,当节点js发布者推送数据时,您可以使用Python监听频道
  3. Websocket连接,其中Node充当客户端,Python充当服务器,反之亦然
  4. 与Express / Flask / Tornado等的API连接分别与暴露给其他用户查询的API端点一起工作

方法1 Python Shell最简单的方法

source.js文件

const ps = require('python-shell')
// very important to add -u option since our python script runs infinitely
var options = {
    pythonPath: '/Users/zup/.local/share/virtualenvs/python_shell_test-TJN5lQez/bin/python',
    pythonOptions: ['-u'], // get print results in real-time
    // make sure you use an absolute path for scriptPath
    scriptPath: "./subscriber/",
    // args: ['value1', 'value2', 'value3'],
    mode: 'json'
};

const shell = new ps.PythonShell("destination.py", options);

function generateArray() {
    const list = []
    for (let i = 0; i < 1000; i++) {
        list.push(Math.random() * 1000)
    }
    return list
}

setInterval(() => {
    shell.send(generateArray())
}, 1000);

shell.on("message", message => {
    console.log(message);
})

destination.py文件

import datetime
import sys
import time
import numpy
import talib
import timeit
import json
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

size = 1000
p = 100
o = numpy.random.random(size)
h = numpy.random.random(size)
l = numpy.random.random(size)
c = numpy.random.random(size)
v = numpy.random.random(size)

def get_indicators(values):
    # Return the RSI of the values sent from node.js
    numpy_values = numpy.array(values, dtype=numpy.double) 
    return talib.func.RSI(numpy_values, 14)

for line in sys.stdin:
    l = json.loads(line)
    print(get_indicators(l))
    # Without this step the output may not be immediately available in node
    sys.stdout.flush()

注意:创建一个名为“订户”的文件夹,该文件夹与source.js文件位于同一级别,并将destination.py放入其中。不要忘记更改您的virtualenv环境

Update 2019

There are several ways to achieve this and here is the list in increasing order of complexity

  1. Python Shell, you will write streams to the python console and it will write back to you
  2. Redis Pub Sub, you can have a channel listening in Python while your node js publisher pushes data
  3. Websocket connection where Node acts as the client and Python acts as the server or vice-versa
  4. API connection with Express/Flask/Tornado etc working separately with an API endpoint exposed for the other to query

Approach 1 Python Shell Simplest approach

source.js file

const ps = require('python-shell')
// very important to add -u option since our python script runs infinitely
var options = {
    pythonPath: '/Users/zup/.local/share/virtualenvs/python_shell_test-TJN5lQez/bin/python',
    pythonOptions: ['-u'], // get print results in real-time
    // make sure you use an absolute path for scriptPath
    scriptPath: "./subscriber/",
    // args: ['value1', 'value2', 'value3'],
    mode: 'json'
};

const shell = new ps.PythonShell("destination.py", options);

function generateArray() {
    const list = []
    for (let i = 0; i < 1000; i++) {
        list.push(Math.random() * 1000)
    }
    return list
}

setInterval(() => {
    shell.send(generateArray())
}, 1000);

shell.on("message", message => {
    console.log(message);
})

destination.py file

import datetime
import sys
import time
import numpy
import talib
import timeit
import json
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

size = 1000
p = 100
o = numpy.random.random(size)
h = numpy.random.random(size)
l = numpy.random.random(size)
c = numpy.random.random(size)
v = numpy.random.random(size)

def get_indicators(values):
    # Return the RSI of the values sent from node.js
    numpy_values = numpy.array(values, dtype=numpy.double) 
    return talib.func.RSI(numpy_values, 14)

for line in sys.stdin:
    l = json.loads(line)
    print(get_indicators(l))
    # Without this step the output may not be immediately available in node
    sys.stdout.flush()

Notes: Make a folder called subscriber which is at the same level as source.js file and put destination.py inside it. Dont forget to change your virtualenv environment


在NPM安装期间如何使用其他版本的python?

问题:在NPM安装期间如何使用其他版本的python?

我可以通过终端访问运行centos 5.9的VPS,并安装了默认的python 2.4.3。我还通过以下命令安装了python 2.7.3 :(我使用make altinstall代替make install

wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz
tar -xf Python-2.7.3.tgz
cd Python-2.7.3
./configure
make
make altinstall

然后我通过以下命令从源代码安装了node.js:

python2.7 ./configure
make
make install

问题是,当我使用npm install并尝试安装需要python> 2.4.3的node.js软件包时,出现此错误:

gyp ERR! configure error
gyp ERR! stack Error: Python executable "python" is v2.4.3, which is not supported by gyp.
gyp ERR! stack You can pass the --python switch to point to Python >= v2.5.0 & < 3.0.0.
gyp ERR! stack     at failPythonVersion (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:125:14)
gyp ERR! stack     at /usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:114:9

我应该如何“通过–python开关以指向Python> = v2.5.0”

I have terminal access to a VPS running centos 5.9 and default python 2.4.3 installed. I also installed python 2.7.3 via these commands: (I used make altinstall instead of make install)

wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz
tar -xf Python-2.7.3.tgz
cd Python-2.7.3
./configure
make
make altinstall

then I installed node.js from source via these commands:

python2.7 ./configure
make
make install

The problem is, when I use npm install and try to install a node.js package which requires python > 2.4.3 I get this error:

gyp ERR! configure error
gyp ERR! stack Error: Python executable "python" is v2.4.3, which is not supported by gyp.
gyp ERR! stack You can pass the --python switch to point to Python >= v2.5.0 & < 3.0.0.
gyp ERR! stack     at failPythonVersion (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:125:14)
gyp ERR! stack     at /usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:114:9

how should I “pass the –python switch to point to Python >= v2.5.0”?


回答 0

您可以使用--pythonnpm选项,如下所示:

npm install --python=python2.7

或将其设置为始终使用:

npm config set python python2.7

Npm会在需要时依次将此选项传递给node-gyp。

(注意:我是在Github上发布一个问题将此文档包含在文档中的人,因为对此有太多问题;-))

You can use --python option to npm like so:

npm install --python=python2.7

or set it to be used always:

npm config set python python2.7

Npm will in turn pass this option to node-gyp when needed.

(note: I’m the one who opened an issue on Github to have this included in the docs, as there were so many questions about it ;-) )


回答 1

在运行npm install之前将python设置为python2.7

Linux:

export PYTHON=python2.7

视窗:

set PYTHON=python2.7

set python to python2.7 before running npm install

Linux:

export PYTHON=python2.7

Windows:

set PYTHON=python2.7

回答 2

对于Windows用户,类似这样的方法应该起作用:

PS C:\angular> npm install --python=C:\Python27\python.exe

For Windows users something like this should work:

PS C:\angular> npm install --python=C:\Python27\python.exe

回答 3

好的,所以您已经找到了解决方案。只想分享对我有用很多次的东西;

我创建了setpy2别名,可以帮助我切换python。

alias setpy2="mkdir -p /tmp/bin; ln -s `which python2.7` /tmp/bin/python; export PATH=/tmp/bin:$PATH"

执行setpy2之前运行npm install。该开关将一直有效,直到您退出终端为止,之后python将其设置回系统默认值。

您也可以将这种技术用于任何其他命令/工具。

Ok, so you’ve found a solution already. Just wanted to share what has been useful to me so many times;

I have created setpy2 alias which helps me switch python.

alias setpy2="mkdir -p /tmp/bin; ln -s `which python2.7` /tmp/bin/python; export PATH=/tmp/bin:$PATH"

Execute setpy2 before you run npm install. The switch stays in effect until you quit the terminal, afterwards python is set back to system default.

You can make use of this technique for any other command/tool as well.


回答 4

为了快速使用它,npm install –python =“ c:\ python27”

for quick one time use this works, npm install –python=”c:\python27″


回答 5

如果您在路径上没有python或想指定目录,此方法效果更好:

//for Windows
npm config set python C:\Python27\python.exe

//for Linux
npm config set python /usr/bin/python27

This one works better if you don’t have the python on path or want to specify the directory :

//for Windows
npm config set python C:\Python27\python.exe

//for Linux
npm config set python /usr/bin/python27

如何从Node.js调用Python函数

问题:如何从Node.js调用Python函数

我有一个Express Node.js应用程序,但我还有一个机器学习算法可在Python中使用。有没有一种方法可以从Node.js应用程序调用Python函数来利用机器学习库的功能?

I have an Express Node.js application, but I also have a machine learning algorithm to use in Python. Is there a way I can call Python functions from my Node.js application to make use of the power of machine learning libraries?


回答 0

我知道的最简单的方法是使用与节点打包在一起的“ child_process”包。

然后,您可以执行以下操作:

const spawn = require("child_process").spawn;
const pythonProcess = spawn('python',["path/to/script.py", arg1, arg2, ...]);

然后,所有要做的就是确保您import sys在python脚本中,然后可以arg1使用 sys.argv[1]arg2使用 sys.argv[2],等等进行访问。

要将数据发送回节点,只需在python脚本中执行以下操作:

print(dataToSendBack)
sys.stdout.flush()

然后节点可以使用以下方法侦听数据:

pythonProcess.stdout.on('data', (data) => {
    // Do something with the data returned from python script
});

由于这允许使用spawn将多个参数传递给脚本,因此您可以重组python脚本,以便其中一个参数决定调用哪个函数,而另一个参数传递给该函数,依此类推。

希望这很清楚。让我知道是否需要澄清。

Easiest way I know of is to use “child_process” package which comes packaged with node.

Then you can do something like:

const spawn = require("child_process").spawn;
const pythonProcess = spawn('python',["path/to/script.py", arg1, arg2, ...]);

Then all you have to do is make sure that you import sys in your python script, and then you can access arg1 using sys.argv[1], arg2 using sys.argv[2], and so on.

To send data back to node just do the following in the python script:

print(dataToSendBack)
sys.stdout.flush()

And then node can listen for data using:

pythonProcess.stdout.on('data', (data) => {
    // Do something with the data returned from python script
});

Since this allows multiple arguments to be passed to a script using spawn, you can restructure a python script so that one of the arguments decides which function to call, and the other argument gets passed to that function, etc.

Hope this was clear. Let me know if something needs clarification.


回答 1

来自Python背景并希望将其机器学习模型集成到Node.js应用程序中的人员的:

它使用child_process核心模块:

const express = require('express')
const app = express()

app.get('/', (req, res) => {

    const { spawn } = require('child_process');
    const pyProg = spawn('python', ['./../pypy.py']);

    pyProg.stdout.on('data', function(data) {

        console.log(data.toString());
        res.write(data);
        res.end('end');
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))

不需要 sys在您的Python脚本中模块。

以下是使用以下命令执行任务的更模块化的方式Promise

const express = require('express')
const app = express()

let runPy = new Promise(function(success, nosuccess) {

    const { spawn } = require('child_process');
    const pyprog = spawn('python', ['./../pypy.py']);

    pyprog.stdout.on('data', function(data) {

        success(data);
    });

    pyprog.stderr.on('data', (data) => {

        nosuccess(data);
    });
});

app.get('/', (req, res) => {

    res.write('welcome\n');

    runPy.then(function(fromRunpy) {
        console.log(fromRunpy.toString());
        res.end(fromRunpy);
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))

Example for people who are from Python background and want to integrate their machine learning model in the Node.js application:

It uses the child_process core module:

const express = require('express')
const app = express()

app.get('/', (req, res) => {

    const { spawn } = require('child_process');
    const pyProg = spawn('python', ['./../pypy.py']);

    pyProg.stdout.on('data', function(data) {

        console.log(data.toString());
        res.write(data);
        res.end('end');
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))

It doesn’t require sys module in your Python script.

Below is a more modular way of performing the task using Promise:

const express = require('express')
const app = express()

let runPy = new Promise(function(success, nosuccess) {

    const { spawn } = require('child_process');
    const pyprog = spawn('python', ['./../pypy.py']);

    pyprog.stdout.on('data', function(data) {

        success(data);
    });

    pyprog.stderr.on('data', (data) => {

        nosuccess(data);
    });
});

app.get('/', (req, res) => {

    res.write('welcome\n');

    runPy.then(function(fromRunpy) {
        console.log(fromRunpy.toString());
        res.end(fromRunpy);
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))

回答 2

python-shell模块extrabacon是通过Node.js运行Python脚本的一种简单方法,它具有基本但有效的进程间通信和更好的错误处理能力。

安装: npm install python-shell

运行一个简单的Python脚本:

var PythonShell = require('python-shell');

PythonShell.run('my_script.py', function (err) {
  if (err) throw err;
  console.log('finished');
});

使用参数和选项运行Python脚本:

var PythonShell = require('python-shell');

var options = {
  mode: 'text',
  pythonPath: 'path/to/python',
  pythonOptions: ['-u'],
  scriptPath: 'path/to/my/scripts',
  args: ['value1', 'value2', 'value3']
};

PythonShell.run('my_script.py', options, function (err, results) {
  if (err) 
    throw err;
  // Results is an array consisting of messages collected during execution
  console.log('results: %j', results);
});

有关完整的文档和源代码,请查看https://github.com/extrabacon/python-shell

The python-shell module by extrabacon is a simple way to run Python scripts from Node.js with basic, but efficient inter-process communication and better error handling.

Installation: npm install python-shell.

Running a simple Python script:

var PythonShell = require('python-shell');

PythonShell.run('my_script.py', function (err) {
  if (err) throw err;
  console.log('finished');
});

Running a Python script with arguments and options:

var PythonShell = require('python-shell');

var options = {
  mode: 'text',
  pythonPath: 'path/to/python',
  pythonOptions: ['-u'],
  scriptPath: 'path/to/my/scripts',
  args: ['value1', 'value2', 'value3']
};

PythonShell.run('my_script.py', options, function (err, results) {
  if (err) 
    throw err;
  // Results is an array consisting of messages collected during execution
  console.log('results: %j', results);
});

For the full documentation and source code, check out https://github.com/extrabacon/python-shell


回答 3

现在,您可以使用支持Python和Javascript的RPC库,例如zerorpc

从他们的首页:

Node.js客户端

var zerorpc = require("zerorpc");

var client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");

client.invoke("hello", "RPC", function(error, res, more) {
    console.log(res);
});

Python服务器

import zerorpc

class HelloRPC(object):
    def hello(self, name):
        return "Hello, %s" % name

s = zerorpc.Server(HelloRPC())
s.bind("tcp://0.0.0.0:4242")
s.run()

You can now use RPC libraries that support Python and Javascript such as zerorpc

From their front page:

Node.js Client

var zerorpc = require("zerorpc");

var client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");

client.invoke("hello", "RPC", function(error, res, more) {
    console.log(res);
});

Python Server

import zerorpc

class HelloRPC(object):
    def hello(self, name):
        return "Hello, %s" % name

s = zerorpc.Server(HelloRPC())
s.bind("tcp://0.0.0.0:4242")
s.run()

回答 4

先前的大多数答案都将on(“ data”)中的promise称为成功,这不是正确的方法,因为如果您收到大量数据,您只会得到第一部分。相反,您必须在结束事件上执行此操作。

const { spawn } = require('child_process');
const pythonDir = (__dirname + "/../pythonCode/"); // Path of python script folder
const python = pythonDir + "pythonEnv/bin/python"; // Path of the Python interpreter

/** remove warning that you don't care about */
function cleanWarning(error) {
    return error.replace(/Detector is not able to detect the language reliably.\n/g,"");
}

function callPython(scriptName, args) {
    return new Promise(function(success, reject) {
        const script = pythonDir + scriptName;
        const pyArgs = [script, JSON.stringify(args) ]
        const pyprog = spawn(python, pyArgs );
        let result = "";
        let resultError = "";
        pyprog.stdout.on('data', function(data) {
            result += data.toString();
        });

        pyprog.stderr.on('data', (data) => {
            resultError += cleanWarning(data.toString());
        });

        pyprog.stdout.on("end", function(){
            if(resultError == "") {
                success(JSON.parse(result));
            }else{
                console.error(`Python error, you can reproduce the error with: \n${python} ${script} ${pyArgs.join(" ")}`);
                const error = new Error(resultError);
                console.error(error);
                reject(resultError);
            }
        })
   });
}
module.exports.callPython = callPython;

呼叫:

const pythonCaller = require("../core/pythonCaller");
const result = await pythonCaller.callPython("preprocessorSentiment.py", {"thekeyYouwant": value});

Python:

try:
    argu = json.loads(sys.argv[1])
except:
    raise Exception("error while loading argument")

Most of previous answers call the success of the promise in the on(“data”), it is not the proper way to do it because if you receive a lot of data you will only get the first part. Instead you have to do it on the end event.

const { spawn } = require('child_process');
const pythonDir = (__dirname + "/../pythonCode/"); // Path of python script folder
const python = pythonDir + "pythonEnv/bin/python"; // Path of the Python interpreter

/** remove warning that you don't care about */
function cleanWarning(error) {
    return error.replace(/Detector is not able to detect the language reliably.\n/g,"");
}

function callPython(scriptName, args) {
    return new Promise(function(success, reject) {
        const script = pythonDir + scriptName;
        const pyArgs = [script, JSON.stringify(args) ]
        const pyprog = spawn(python, pyArgs );
        let result = "";
        let resultError = "";
        pyprog.stdout.on('data', function(data) {
            result += data.toString();
        });

        pyprog.stderr.on('data', (data) => {
            resultError += cleanWarning(data.toString());
        });

        pyprog.stdout.on("end", function(){
            if(resultError == "") {
                success(JSON.parse(result));
            }else{
                console.error(`Python error, you can reproduce the error with: \n${python} ${script} ${pyArgs.join(" ")}`);
                const error = new Error(resultError);
                console.error(error);
                reject(resultError);
            }
        })
   });
}
module.exports.callPython = callPython;

Call:

const pythonCaller = require("../core/pythonCaller");
const result = await pythonCaller.callPython("preprocessorSentiment.py", {"thekeyYouwant": value});

python:

try:
    argu = json.loads(sys.argv[1])
except:
    raise Exception("error while loading argument")

回答 5

我在节点10和子进程上1.0.2。来自python的数据是一个字节数组,必须进行转换。这是在python中发出http请求的另一个快速示例。

节点

const process = spawn("python", ["services/request.py", "https://www.google.com"])

return new Promise((resolve, reject) =>{
    process.stdout.on("data", data =>{
        resolve(data.toString()); // <------------ by default converts to utf-8
    })
    process.stderr.on("data", reject)
})

request.py

import urllib.request
import sys

def karl_morrison_is_a_pedant():   
    response = urllib.request.urlopen(sys.argv[1])
    html = response.read()
    print(html)
    sys.stdout.flush()

karl_morrison_is_a_pedant()

ps不是一个人为的例子,因为节点的http模块不会加载我需要发出的一些请求

I’m on node 10 and child process 1.0.2. The data from python is a byte array and has to be converted. Just another quick example of making a http request in python.

node

const process = spawn("python", ["services/request.py", "https://www.google.com"])

return new Promise((resolve, reject) =>{
    process.stdout.on("data", data =>{
        resolve(data.toString()); // <------------ by default converts to utf-8
    })
    process.stderr.on("data", reject)
})

request.py

import urllib.request
import sys

def karl_morrison_is_a_pedant():   
    response = urllib.request.urlopen(sys.argv[1])
    html = response.read()
    print(html)
    sys.stdout.flush()

karl_morrison_is_a_pedant()

p.s. not a contrived example since node’s http module doesn’t load a few requests I need to make


回答 6

您可以将自己的python进行转换,然后像调用JavaScript一样对其进行调用。我已经成功完成了此步骤,甚至还可以在浏览器中运行la brython

You could take your python, transpile it, and then call it as if it were javascript. I have done this succesfully for screeps and even got it to run in the browser a la brython.


回答 7

/*eslint-env es6*/
/*global require*/
/*global console*/
var express = require('express'); 
var app = express();

// Creates a server which runs on port 3000 and  
// can be accessed through localhost:3000
app.listen(3000, function() { 
    console.log('server running on port 3000'); 
} ) 

app.get('/name', function(req, res) {

    console.log('Running');

    // Use child_process.spawn method from  
    // child_process module and assign it 
    // to variable spawn 
    var spawn = require("child_process").spawn;   
    // Parameters passed in spawn - 
    // 1. type_of_script 
    // 2. list containing Path of the script 
    //    and arguments for the script  

    // E.g : http://localhost:3000/name?firstname=Levente
    var process = spawn('python',['apiTest.py', 
                        req.query.firstname]);

    // Takes stdout data from script which executed 
    // with arguments and send this data to res object
    var output = '';
    process.stdout.on('data', function(data) {

        console.log("Sending Info")
        res.end(data.toString('utf8'));
    });

    console.log(output);
}); 

这对我有用。您的python.exe必须添加到此代码段的路径变量中。另外,请确保您的python脚本位于项目文件夹中。

/*eslint-env es6*/
/*global require*/
/*global console*/
var express = require('express'); 
var app = express();

// Creates a server which runs on port 3000 and  
// can be accessed through localhost:3000
app.listen(3000, function() { 
    console.log('server running on port 3000'); 
} ) 

app.get('/name', function(req, res) {

    console.log('Running');

    // Use child_process.spawn method from  
    // child_process module and assign it 
    // to variable spawn 
    var spawn = require("child_process").spawn;   
    // Parameters passed in spawn - 
    // 1. type_of_script 
    // 2. list containing Path of the script 
    //    and arguments for the script  

    // E.g : http://localhost:3000/name?firstname=Levente
    var process = spawn('python',['apiTest.py', 
                        req.query.firstname]);

    // Takes stdout data from script which executed 
    // with arguments and send this data to res object
    var output = '';
    process.stdout.on('data', function(data) {

        console.log("Sending Info")
        res.end(data.toString('utf8'));
    });

    console.log(output);
}); 

This worked for me. Your python.exe must be added to you path variables for this code snippet. Also, make sure your python script is in your project folder.


pip等同于`npm install package –save-dev`吗?

问题:pip等同于`npm install package –save-dev`吗?

在nodejs中,我可以npm install package --save-dev将已安装的软件包保存到软件包中。

如何在Python包管理器中实现同一目的pip?我想将软件包名称及其版本保存到,例如,requirements.pip使用来安装软件包之后pip install package --save-dev requirements.pip

In nodejs, I can do npm install package --save-dev to save the installed package into the package.

How do I achieve the same thing in Python package manager pip? I would like to save the package name and its version into, say, requirements.pip just after installing the package using something like pip install package --save-dev requirements.pip.


回答 0

没有与的等效项pip

最好的方法是 pip install package && pip freeze > requirements.txt

您可以在其文档页面上看到所有可用的选项。

如果确实让您感到困扰,那么编写一个自定义bash脚本(pips)会很困难,该脚本带有一个-s参数并requirements.txt自动冻结到您的文件中。

编辑1

自编写此书以来,提供--save-dev类似于NPM 的自动选项没有任何变化,但是Kenneth Reitz(requests及更多作者)发布了一些有关更好的点子工作流程以更好地处理pip更新的信息。

编辑2

从上面的“更好的点子工作流程”文章链接到现在,建议将其用于pipenv管理需求和虚拟环境。最近使用了很多,我想总结一下转换是多么简单:

安装pipenv(在Mac上)

brew install pipenv

pipenv创建并管理它自己的虚拟环境,因此在具有现有的项目中requirements.txt,安装所有要求(我使用Python3.7,但--three如果不这样做,则可以删除)就很简单:

pipenv --three install

激活virtualenv以运行命令也很容易

pipenv shell

安装要求将自动更新PipfilePipfile.lock

pipenv install <package>

还可以更新过期的软件包

pipenv update

我强烈建议您进行检查,尤其是来自npm背景时,因为它的感觉package.jsonpackage-lock.json

There isn’t an equivalent with pip.

Best way is to pip install package && pip freeze > requirements.txt

You can see all the available options on their documentation page.

If it really bothers you, it wouldn’t be too difficult to write a custom bash script (pips) that takes a -s argument and freezes to your requirements.txt file automatically.

Edit 1

Since writing this there has been no change in providing an auto --save-dev option similar to NPM however Kenneth Reitz (author of requests and many more) has released some more info about a better pip workflow to better handle pip updates.

Edit 2

Linked from the “better pip workflow” article above it is now recommended to use pipenv to manage requirements and virtual environments. Having used this a lot recently I would like to summarise how simple the transition is:

Install pipenv (on Mac)

brew install pipenv

pipenv creates and manages it’s own virtual environments so in a project with an existing requirements.txt, installing all requirements (I use Python3.7 but you can remove the --three if you do not) is as simple as:

pipenv --three install

Activating the virtualenv to run commands is also easy

pipenv shell

Installing requirements will automatically update the Pipfile and Pipfile.lock

pipenv install <package>

It’s also possible to update out-of-date packages

pipenv update

I highly recommend checking it out especially if coming from a npm background as it has a similar feel to package.json and package-lock.json


回答 1

这条简单的线是一个起点。您可以轻松构建一个bash命令来重用该行中的PACKAGE。

pip install PACKAGE && pip freeze | grep PACKAGE >> requirements.txt

感谢@devsnd提供了简单的bash函数示例:

function pip-install-save { 
    pip install $1 && pip freeze | grep $1 >> requirements.txt
}

要使用它,只需运行:

pip-install-save some-package

This simple line is a starting point. You can easily built a bash command to reuse the PACKAGE in the line.

pip install PACKAGE && pip freeze | grep PACKAGE >> requirements.txt

Thanks to @devsnd for the simple bash function example:

function pip-install-save { 
    pip install $1 && pip freeze | grep $1 >> requirements.txt
}

To use it, just run:

pip-install-save some-package

回答 2

我创建Python包,各地的实际包装pip称为PIPM。所有pip命令将按原样运行,并且它们将反映在需求文件中。与pip-save(我发现但无法使用的类似工具)不同,它可以处理许多文件和环境(测试,开发,生产等)。它还具有用于升级所有/任何依赖项的命令。

安装

pipm install pkg-name

安装为开发依赖项

pipm install pkg-name --dev

安装为测试依赖项

pipm install pkg-name --test

清除

pipm uninstall pkg-name

更新所有依赖

pipm update

从需求文件安装所有依赖项

pipm install

包括开发依赖

pipm install --dev

I’ve created python package that wraps around the actual pip called pipm. All pip commands will work as it is, plus they will be reflected in the requirements file. Unlike pip-save(similar tool I found and wasn’t able to use) it can handle many files and environments(test, dev, production, etc. ). It also has command to upgrade all/any of your dependencies.

installation

pipm install pkg-name

installation as development dependency

pipm install pkg-name --dev

installation as testing dependency

pipm install pkg-name --test

removal

pipm uninstall pkg-name

update all your dependencies

pipm update

install all your dependencies from the requirements file

pipm install

including development dependencies

pipm install --dev


回答 3

更新:显然,pipenv没有得到Python维护者的正式认可,并且以前链接的页面是由另一个组织拥有的。该工具各有利弊,但以下解决方案仍然可以达到OP所寻求的结果。

pipenv是一个依赖项管理工具,它包装pip并提供您所要求的内容:

https://pipenv.kennethreitz.org/en/latest/#example-pipenv-workflow

$ pipenv install <package>

如果不存在,这将创建一个Pipfile。如果存在,它将使用您提供的新软件包自动进行编辑。

A Pipfile直接等于package.json,而Pipfile.lock对应于package-lock.json

Update: apparently, pipenv is not officially endorsed by Python maintainers, and the previously-linked page is owned by a different organization. The tool has its pros and cons, but the below solution still achieves the result that the OP is seeking.

pipenv is a dependency management tool that wraps pip and, among other things, provides what you’re asking:

https://pipenv.kennethreitz.org/en/latest/#example-pipenv-workflow

$ pipenv install <package>

This will create a Pipfile if one doesn’t exist. If one does exist, it will automatically be edited with the new package your provided.

A Pipfile is a direct equivalent of package.json, while Pipfile.lock corresponds to package-lock.json.


回答 4

我快速pip添加--save了安装/卸载命令选项。

请查看我的博客以获取有关此黑客的更多信息:http : //blog.abhiomkar.in/2015/11/12/pip-save-npm-like-behaviour-to-pip/

安装(GitHub):https : //github.com/abhiomkar/pip-save

希望这可以帮助。

I made a quick hack on pip to add --save option to install/uninstall commands.

Please have a look at my blog for more information about this hack: http://blog.abhiomkar.in/2015/11/12/pip-save-npm-like-behaviour-to-pip/

Installation (GitHub): https://github.com/abhiomkar/pip-save

Hope this helps.


回答 5

您可以将其手动保存在Makefile(或文本文件中,然后导入到Makefile中):


PYTHON=.venv/bin/python # path to pyphon
PIP=.venv/bin/pip # path to pip
SOURCE_VENV=. .venv/bin/activate


install:
    virtualenv .venv
    $(SOURCE_VENV) && $(PIP) install -e PACKAGE
    $(SOURCE_VENV) && $(PIP) install -r requirements.txt # other required packages

然后运行 make install

you can manually save it in a Makefile (or a text file and then imported in your Makefile):


PYTHON=.venv/bin/python # path to pyphon
PIP=.venv/bin/pip # path to pip
SOURCE_VENV=. .venv/bin/activate


install:
    virtualenv .venv
    $(SOURCE_VENV) && $(PIP) install -e PACKAGE
    $(SOURCE_VENV) && $(PIP) install -r requirements.txt # other required packages

and then just run make install


回答 6

我正在使用此小命令行来安装软件包并将其版本保存在requirements.txtpkg=package && pip install $pkg && echo $(pip freeze | grep -i $pkg) >> requirements.txt

I am using this small command line to install a package and save its version in requirements.txt : pkg=package && pip install $pkg && echo $(pip freeze | grep -i $pkg) >> requirements.txt


回答 7

使shell函数执行此操作怎么样?将以下代码添加到您的~/.profile~/.bashrc

pips() {
    local pkg=$1

    if [ -z "$1" ]; then
        echo "usage: pips <pkg name>"
        return 1
    fi

    local _ins="pip install $pkg"
    eval $_ins
    pip freeze | grep $pkg -i >> requirements.txt
}

然后运行source ~/.profilesource ~/.bashrc将其导入到当前终端

例如,当您要安装&&保存软件包时,只需运行即可pips requests。安装软件包后,其版本将保存到requirements.txt您的当前目录中。

How about make a shell function to do this ? Add below code to your ~/.profile or ~/.bashrc

pips() {
    local pkg=$1

    if [ -z "$1" ]; then
        echo "usage: pips <pkg name>"
        return 1
    fi

    local _ins="pip install $pkg"
    eval $_ins
    pip freeze | grep $pkg -i >> requirements.txt
}

then run source ~/.profile or source ~/.bashrc to import it to your current terminal

when you want to install && save a package, just run, for example pips requests. after package was installed, its version will be save into requirements.txt in your current directory.


在Windows上运行Python以获取Node.js依赖项

问题:在Windows上运行Python以获取Node.js依赖项

我正在进入Node.js代码库,该代码库要求我通过NPM(即jQuery)下载一些依赖项。

在尝试运行时npm install jquery,我不断出现此错误:

Your environment has been set up for using Node.js 0.8.21 (x64) and NPM

C:\Users\Matt Cashatt>npm install jquery
npm http GET https://registry.npmjs.org/jquery
npm http 304 https://registry.npmjs.org/jquery
npm http GET https://registry.npmjs.org/jsdom
npm http GET https://registry.npmjs.org/xmlhttprequest
npm http GET https://registry.npmjs.org/htmlparser/1.7.6
npm http GET https://registry.npmjs.org/location/0.0.1
npm http GET https://registry.npmjs.org/navigator
npm http GET https://registry.npmjs.org/contextify
npm http 304 https://registry.npmjs.org/htmlparser/1.7.6
npm http 304 https://registry.npmjs.org/xmlhttprequest
npm http 304 https://registry.npmjs.org/location/0.0.1
npm http 304 https://registry.npmjs.org/navigator
npm http 304 https://registry.npmjs.org/jsdom
npm http 304 https://registry.npmjs.org/contextify
npm http GET https://registry.npmjs.org/bindings
npm http GET https://registry.npmjs.org/cssom
npm http GET https://registry.npmjs.org/cssstyle
npm http GET https://registry.npmjs.org/request
npm http 304 https://registry.npmjs.org/bindings

> contextify@0.1.4 install C:\Users\Matt Cashatt\node_modules\jquery\node_module
s\contextify
> node-gyp rebuild


C:\Users\Matt Cashatt\node_modules\jquery\node_modules\contextify>node "C:\Progr
am Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\b
in\node-gyp.js" rebuild
npm http 304 https://registry.npmjs.org/cssstyle
npm http 304 https://registry.npmjs.org/cssom
npm http 304 https://registry.npmjs.org/request
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT
HON env variable.
gyp ERR! stack     at failNoPython (C:\Program Files\nodejs\node_modules\npm\nod
e_modules\node-gyp\lib\configure.js:113:14)
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node
-gyp\lib\configure.js:82:11
gyp ERR! stack     at Object.oncomplete (fs.js:297:15)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "node" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modu
les\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\Matt Cashatt\node_modules\jquery\node_modules\contextify
gyp ERR! node -v v0.8.21
gyp ERR! node-gyp -v v0.8.4
gyp ERR! not ok
npm ERR! error rolling back Error: ENOTEMPTY, rmdir 'C:\Users\Matt Cashatt\node_
modules\jquery\node_modules\jsdom\node_modules\request\tests'
npm ERR! error rolling back  jquery@1.8.3 { [Error: ENOTEMPTY, rmdir 'C:\Users\M
att Cashatt\node_modules\jquery\node_modules\jsdom\node_modules\request\tests']
npm ERR! error rolling back   errno: 53,
npm ERR! error rolling back   code: 'ENOTEMPTY',
npm ERR! error rolling back   path: 'C:\\Users\\Matt Cashatt\\node_modules\\jque
ry\\node_modules\\jsdom\\node_modules\\request\\tests' }
npm ERR! contextify@0.1.4 install: `node-gyp rebuild`
npm ERR! `cmd "/c" "node-gyp rebuild"` failed with 1
npm ERR!
npm ERR! Failed at the contextify@0.1.4 install script.
npm ERR! This is most likely a problem with the contextify package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls contextify
npm ERR! There is likely additional logging output above.

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod
ejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "jquery"
npm ERR! cwd C:\Users\Matt Cashatt
npm ERR! node -v v0.8.21
npm ERR! npm -v 1.2.11
npm ERR! code ELIFECYCLE
npm ERR! Error: ENOENT, lstat 'C:\Users\Matt Cashatt\node_modules\jquery\node_mo
dules\jsdom\node_modules\request\tests\test-pipes.js'
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod
ejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "jquery"
npm ERR! cwd C:\Users\Matt Cashatt
npm ERR! node -v v0.8.21
npm ERR! npm -v 1.2.11
npm ERR! path C:\Users\Matt Cashatt\node_modules\jquery\node_modules\jsdom\node_
modules\request\tests\test-pipes.js
npm ERR! fstream_path C:\Users\Matt Cashatt\node_modules\jquery\node_modules\jsd
om\node_modules\request\tests\test-pipes.js
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR! fstream_stack C:\Program Files\nodejs\node_modules\npm\node_modules\fst
ream\lib\writer.js:284:26
npm ERR! fstream_stack Object.oncomplete (fs.js:297:15)
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     C:\Users\Matt Cashatt\npm-debug.log
npm ERR! not ok code 0

C:\Users\Matt Cashatt>

失败似乎是由于缺少Python安装导致的。好了,我已经安装了Python,设置了变量,然后重新启动,仍然是错误。

关于我所缺少的任何线索吗?

I am getting into a Node.js codebase which requires that I download a few dependencies via NPM, namely jQuery.

In attempting to run npm install jquery, I keep getting this error:

Your environment has been set up for using Node.js 0.8.21 (x64) and NPM

C:\Users\Matt Cashatt>npm install jquery
npm http GET https://registry.npmjs.org/jquery
npm http 304 https://registry.npmjs.org/jquery
npm http GET https://registry.npmjs.org/jsdom
npm http GET https://registry.npmjs.org/xmlhttprequest
npm http GET https://registry.npmjs.org/htmlparser/1.7.6
npm http GET https://registry.npmjs.org/location/0.0.1
npm http GET https://registry.npmjs.org/navigator
npm http GET https://registry.npmjs.org/contextify
npm http 304 https://registry.npmjs.org/htmlparser/1.7.6
npm http 304 https://registry.npmjs.org/xmlhttprequest
npm http 304 https://registry.npmjs.org/location/0.0.1
npm http 304 https://registry.npmjs.org/navigator
npm http 304 https://registry.npmjs.org/jsdom
npm http 304 https://registry.npmjs.org/contextify
npm http GET https://registry.npmjs.org/bindings
npm http GET https://registry.npmjs.org/cssom
npm http GET https://registry.npmjs.org/cssstyle
npm http GET https://registry.npmjs.org/request
npm http 304 https://registry.npmjs.org/bindings

> contextify@0.1.4 install C:\Users\Matt Cashatt\node_modules\jquery\node_module
s\contextify
> node-gyp rebuild


C:\Users\Matt Cashatt\node_modules\jquery\node_modules\contextify>node "C:\Progr
am Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\b
in\node-gyp.js" rebuild
npm http 304 https://registry.npmjs.org/cssstyle
npm http 304 https://registry.npmjs.org/cssom
npm http 304 https://registry.npmjs.org/request
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT
HON env variable.
gyp ERR! stack     at failNoPython (C:\Program Files\nodejs\node_modules\npm\nod
e_modules\node-gyp\lib\configure.js:113:14)
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node
-gyp\lib\configure.js:82:11
gyp ERR! stack     at Object.oncomplete (fs.js:297:15)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "node" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modu
les\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\Matt Cashatt\node_modules\jquery\node_modules\contextify
gyp ERR! node -v v0.8.21
gyp ERR! node-gyp -v v0.8.4
gyp ERR! not ok
npm ERR! error rolling back Error: ENOTEMPTY, rmdir 'C:\Users\Matt Cashatt\node_
modules\jquery\node_modules\jsdom\node_modules\request\tests'
npm ERR! error rolling back  jquery@1.8.3 { [Error: ENOTEMPTY, rmdir 'C:\Users\M
att Cashatt\node_modules\jquery\node_modules\jsdom\node_modules\request\tests']
npm ERR! error rolling back   errno: 53,
npm ERR! error rolling back   code: 'ENOTEMPTY',
npm ERR! error rolling back   path: 'C:\\Users\\Matt Cashatt\\node_modules\\jque
ry\\node_modules\\jsdom\\node_modules\\request\\tests' }
npm ERR! contextify@0.1.4 install: `node-gyp rebuild`
npm ERR! `cmd "/c" "node-gyp rebuild"` failed with 1
npm ERR!
npm ERR! Failed at the contextify@0.1.4 install script.
npm ERR! This is most likely a problem with the contextify package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls contextify
npm ERR! There is likely additional logging output above.

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod
ejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "jquery"
npm ERR! cwd C:\Users\Matt Cashatt
npm ERR! node -v v0.8.21
npm ERR! npm -v 1.2.11
npm ERR! code ELIFECYCLE
npm ERR! Error: ENOENT, lstat 'C:\Users\Matt Cashatt\node_modules\jquery\node_mo
dules\jsdom\node_modules\request\tests\test-pipes.js'
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod
ejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "jquery"
npm ERR! cwd C:\Users\Matt Cashatt
npm ERR! node -v v0.8.21
npm ERR! npm -v 1.2.11
npm ERR! path C:\Users\Matt Cashatt\node_modules\jquery\node_modules\jsdom\node_
modules\request\tests\test-pipes.js
npm ERR! fstream_path C:\Users\Matt Cashatt\node_modules\jquery\node_modules\jsd
om\node_modules\request\tests\test-pipes.js
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR! fstream_stack C:\Program Files\nodejs\node_modules\npm\node_modules\fst
ream\lib\writer.js:284:26
npm ERR! fstream_stack Object.oncomplete (fs.js:297:15)
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     C:\Users\Matt Cashatt\npm-debug.log
npm ERR! not ok code 0

C:\Users\Matt Cashatt>

It looks like the failure is due to a missing Python installation. Well, I have installed Python, set the variable, and rebooted and still the error.

Any clue as to what I am missing?


回答 0

您的问题是您没有设置环境变量。

该错误清楚地表明:

gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.

在评论中,您说您这样做:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

很好,但是没有设置PYTHON变量,而是设置了PYTHONPATH变量。


同时,仅使用set命令只会影响当前cmd会话。如果重新启动之后(如您所说的那样),最终将导致一个全新的cmd会话,其中未设置该变量。

有几种方法可以永久性地设置环境变量-最简单的方法是在XP的系统控制面板中,当然在Vista中有所不同,在7中又有所不同,在8中又有所不同,但是您可以用google搜索。

或者,只需setnpm命令前执行正确操作,而无需在两者之间重新引导。


您可以通过执行与配置脚本完全相同的操作来测试您是否正确完成了操作:在运行之前npm,请尝试运行%PYTHON%。如果做对了,您将获得一个Python解释器(您可以立即退出)。如果遇到错误,则说明您做错了。


这有两个问题:

set PYTHON=%PYTHON%;D:\Python

首先,您将设置PYTHON;D:\Python。多余的分号适用于以分号分隔的路径列表(例如PATHor)PYTHONPATH,但不适用于单个值(例如)PYTHON。同样,当您要向路径列表中添加另一个路径而不是为单个值添加新值时,则需要在现有值上添加一个新值。因此,您只需要set PYTHON=D:\Python

其次,D:\Python不是您的Python解释器的路径。就像D:\Python\Python.exeD:\Python\bin\Python.exe。找到正确的路径,确保它可以独立运行(例如,键入D:\Python\bin\Python.exe并确保您拥有Python解释器),然后设置变量并使用它。


所以:

set PYTHON=D:\Python\bin\Python.exe

或者,如果要使其永久不变,请在“控制面板”中执行等效操作。

Your problem is that you didn’t set the environment variable.

The error clearly says this:

gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.

And in your comment, you say you did this:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

That’s nice, but that doesn’t set the PYTHON variable, it sets the PYTHONPATH variable.


Meanwhile, just using the set command only affects the current cmd session. If you reboot after that, as you say you did, you end up with a whole new cmd session that doesn’t have that variable set in it.

There are a few ways to set environment variables permanently—the easiest is in the System Control Panel in XP, which is of course different in Vista, different again in 7, and different again in 8, but you can google for it.

Alternatively, just do the set right before the npm command, without rebooting in between.


You can test whether you’ve done things right by doing the exact same thing the config script is trying to do: Before running npm, try running %PYTHON%. If you’ve done it right, you’ll get a Python interpreter (which you can immediately quit). If you get an error, you haven’t done it right.


There are two problems with this:

set PYTHON=%PYTHON%;D:\Python

First, you’re setting PYTHON to ;D:\Python. That extra semicolon is fine for a semicolon-separated list of paths, like PATH or PYTHONPATH, but not for a single value like PYTHON. And likewise, adding a new value to the existing value is what you want when you want to add another path to a list of paths, but not for a single value. So, you just want set PYTHON=D:\Python.

Second, D:\Python is not the path to your Python interpreter. It’s something like D:\Python\Python.exe, or D:\Python\bin\Python.exe. Find the right path, make sure it works on its own (e.g., type D:\Python\bin\Python.exe and make sure you get a Python interpreter), then set the variable and use it.


So:

set PYTHON=D:\Python\bin\Python.exe

Or, if you want to make it permanent, do the equivalent in the Control Panel.


回答 1

如果您尚未安装python以及所有node-gyp依赖项,只需使用管理员权限打开Powershell或Git Bash并执行:

npm install --global --production windows-build-tools

然后安装该软件包:

npm install --global node-gyp

安装完成后,将下载所有的node-gyp依赖项,但仍需要环境变量。确实在正确的文件夹中找到了验证Python:

C:\Users\ben\.windows-build-tools\python27\python.exe 

注意-它使用python 2.7而不是3.x,因为它不受支持

如果没有抱怨,请继续创建您的(用户)环境变量:

setx PYTHON "%USERPROFILE%\.windows-build-tools\python27\python.exe"

重新启动cmd,并验证变量是否存在set PYTHON,应通过该变量返回变量

最后重新申请 npm install <module>

If you haven’t got python installed along with all the node-gyp dependencies, simply open Powershell or Git Bash with administrator privileges and execute:

npm install --global --production windows-build-tools

and then to install the package:

npm install --global node-gyp

once installed, you will have all the node-gyp dependencies downloaded, but you still need the environment variable. Validate Python is indeed found in the correct folder:

C:\Users\ben\.windows-build-tools\python27\python.exe 

Note – it uses python 2.7 not 3.x as it is not supported

If it doesn’t moan, go ahead and create your (user) environment variable:

setx PYTHON "%USERPROFILE%\.windows-build-tools\python27\python.exe"

restart cmd, and verify the variable exists via set PYTHON which should return the variable

Lastly re-apply npm install <module>


回答 2

对我来说,安装带有以下注释的Windows-build-tools之后

npm --add-python-to-path='true' --debug install --global windows-build-tools

运行下面的代码

npm config set python "%USERPROFILE%\.windows-build-tools\python27\python.exe"

工作了。

For me after installing windows-build-tools with the below comment

npm --add-python-to-path='true' --debug install --global windows-build-tools

running the code below

npm config set python "%USERPROFILE%\.windows-build-tools\python27\python.exe"

has worked.


回答 3

这是为我解决了许多这些问题的指南。

http://www.steveworkman.com/node-js/2012/installing-jsdom-on-windows/

我特别记得python版本很重要。确保安装2.7.3而不是3。

Here is a guide that resolved a lot of these issues for me.

http://www.steveworkman.com/node-js/2012/installing-jsdom-on-windows/

I remember in particular the python version as important. Make sure you install 2.7.3 instead of 3’s.


回答 4

其中一个和/或多个应该有助于:

  1. 添加C:\Python27\PATH变量中(考虑到此目录中已安装Python)
    如何设置环境PATH变量:http : //www.computerhope.com/issues/ch000549.htm
    设置变量后,重新启动控制台和/或Windows。

  2. 在与上述相同的部分(“环境变量”)中,添加具有名称PYTHON和值的新C:\Python27\python.exe
    变量。设置变量后,重新启动控制台和/或Windows。

  3. 在Admin模式下打开Windows命令行(cmd)。 将目录更改为您的Python安装路径: 进行某些安装需要符号链接:
    cd C:\Python27
    mklink python2.7.exe python.exe

请注意,您应该具有Python 2.x而非NOT 3.x来运行node-gyp基于基础的安装!

以下文字是关于Unix的,但Windows版本也需要Python 2.x:

You can install with npm:

$ npm install -g node-gyp
You will also need to install:

On Unix:
python (v2.7 recommended, v3.x.x is not supported)
make
A proper C/C++ compiler toolchain, like GCC

本文可能也有帮助:https : //github.com/nodejs/node-gyp#installation

One and/or multiple of those should help:

  1. Add C:\Python27\ to your PATH variable (considering you have Python installed in this directory)
    How to set PATH env variable: http://www.computerhope.com/issues/ch000549.htm
    Restart your console and/or Windows after setting variable.

  2. In the same section as above (“Environment Variables”), add new variable with name PYTHON and value C:\Python27\python.exe
    Restart your console and/or Windows after setting variable.

  3. Open Windows command line (cmd) in Admin mode.
    Change directory to your Python installation path: cd C:\Python27
    Make symlink needed for some installations: mklink python2.7.exe python.exe

Please note that you should have Python 2.x, NOT 3.x, to run node-gyp based installations!

The text below says about Unix, but Windows version also requires Python 2.x:

You can install with npm:

$ npm install -g node-gyp
You will also need to install:

On Unix:
python (v2.7 recommended, v3.x.x is not supported)
make
A proper C/C++ compiler toolchain, like GCC

This article may also help: https://github.com/nodejs/node-gyp#installation


回答 5

我遇到了同样的问题,这些答案都没有帮助。在我的情况下,PYTHON变量设置正确。但是python安装得太深,即路径太长。因此,我做了以下工作:

  1. 将python重新安装到c:\ python
  2. 将环境变量PYTHON设置为C:\ python \ python.exe

就是这样!

I had the same issue and none of these answers did help. In my case PYTHON variable was set correctly. However python was installed too deep, i.e. has too long path. So, I did the following:

  1. reinstalled python to c:\python
  2. set environmental variable PYTHON to C:\python\python.exe

And that’s it!


回答 6

这有所帮助:https : //www.npmjs.com/package/node-gyp

我遵循以下步骤:

npm install -g node-gyp

然后:

npm install --global --production windows-build-tools

This helped: https://www.npmjs.com/package/node-gyp

I followed these steps:

npm install -g node-gyp

then:

npm install --global --production windows-build-tools

回答 7

有一些解决此问题的方法:1)以“管理员”身份运行命令提示符。

如果第一个解决方案不能解决您的问题,请尝试以下方法:

2)在管理员粘贴以下代码行的情况下打开命令提示符,然后按Enter键:

npm install --global --production windows-build-tools

there are some solution to solve this issue : 1 ) run your command prompt as “administrator”.

if first solution doesn’t solve your problem try this one :

2 ) open a command prompt as administrator paste following line of code and hit enter :

npm install --global --production windows-build-tools

回答 8

TL; DR使用名称python2.7.exe复制python.exe或别名

我的python 2.7安装为

D:\ app \ Python27 \ python.exe

无论我如何设置(并验证)PYTHON env变量,我总是会收到此错误:

糟糕!错误:找不到Python可执行文件“ python2.7”,您可以设置PYTHON env变量。
糟糕!在failNoPython处堆栈(C:\ Program Files \ nodejs \ node_modules \ npm \ node_modules \ node-gyp \ lib \ configure.js:103:14)

原因是在node-gyp的configure.js中,python可执行文件的解析方式如下:

var python = gyp.opts.python || process.env.PYTHON || 'python'

结果发现gyp.opts.python的值是python2.7,因此覆盖了process.env.PYTHON。

我通过为名称为node-gyp的python.exe可执行文件创建别名来解决此问题:

D:\app\Python27>mklink python2.7.exe python.exe

您需要此操作的管理员权限。

TL;DR Make a copy or alias of your python.exe with name python2.7.exe

My python 2.7 was installed as

D:\app\Python27\python.exe

I always got this error no matter how I set (and verified) PYTHON env variable:

gyp ERR! stack Error: Can't find Python executable "python2.7", you can set the PYTHON env variable.
gyp ERR! stack     at failNoPython (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:103:14)

The reason for this was that in node-gyp’s configure.js the python executable was resolved like:

var python = gyp.opts.python || process.env.PYTHON || 'python'

And it turned out that gyp.opts.python had value ‘python2.7’ thus overriding process.env.PYTHON.

I resolved this by creating an alias for python.exe executable with name node-gyp was looking for:

D:\app\Python27>mklink python2.7.exe python.exe

You need admin rights for this operation.


回答 9

以下内容以管理员身份在命令行为我工作:

安装Windows-Build-tools(这可能需要15-20分钟):

 npm --add-python-to-path='true' --debug install --global windows-build-tools

添加/更新环境变量:

setx PYTHON "%USERPROFILE%\.windows-build-tools\python27\python.exe"

安装node-gyp:

npm install --global node-gyp

将exe文件的名称从Python更改为Python2.7。

C:\Users\username\.windows-build-tools\python27\Python2.7

npm install module_name --save

The following worked for me from the command line as admin:

Installing windows-build-tools (this can take 15-20 minutes):

 npm --add-python-to-path='true' --debug install --global windows-build-tools

Adding/updating the environment variable:

setx PYTHON "%USERPROFILE%\.windows-build-tools\python27\python.exe"

Installing node-gyp:

npm install --global node-gyp

Changing the name of the exe file from Python to Python2.7.

C:\Users\username\.windows-build-tools\python27\Python2.7

npm install module_name --save


回答 10

我忍不住提这个。如果您使用Python3和淋巴结GYP失败,那么我很伤心地告诉你节点GYP目前不支持python3。

这是给您的链接:https : //github.com/nodejs/node-gyp/issues/1268 https://github.com/nodejs/node-gyp/issues/193

i can’t help but to mention this. If you’re using Python3 and failing with node-gyp, then i’m sad to tell you node-gyp currently doesn’t support python3.

Here is a link for you: https://github.com/nodejs/node-gyp/issues/1268 https://github.com/nodejs/node-gyp/issues/193


回答 11

这是让NPM为您做所有事情的最简单方法

npm --add-python-to-path='true' --debug install --global windows-build-tools

This is most easiest way to let NPM do everything for you

npm --add-python-to-path='true' --debug install --global windows-build-tools

回答 12

正确的方法是1)从此处下载并安装python 2.7.14 。2)从这里为python设置环境变量。

完成!

注意:请相应地设置环境变量。我在这里为窗户回答。

The right way is 1) Download and Install python 2.7.14 from here. 2) Set environment variable for python from here.

done!

note: Please set environment variable accordingly. I answered here for windows.


回答 13

在尝试安装node-sass@4.9.4时遇到了同样的挑战。

在查看了当前的官方文档并阅读了上面的答案之后,我注意到您可能不一定必须安装node-gyp或Windows构建工具。这就是它所说的,关于在Windows上安装node-gyp。请记住,node-gyp参与了node-sass的安装过程。而且您实际上不必重新安装另一个python版本。

这是一个救星,在安装任何需要构建工具的软件包时配置“ npm”应查找的python路径。

C:\> npm config set python /Python36/python

我已经在Windows-7上安装了python3.6.3。

I met the same challenge while trying to install node-sass@4.9.4.

And after looking at the current official documentation, and having read the answers above, i noticed that you might not necessarily have to install node-gyp nor install windows-build tools. This is what it says, here about installing node-gyp on windows. Remember node-gyp is involved in the installation process of node-sass. And you don’t really have to re-install another python version.

This is the savior, configure the python path that “npm” should look for while installing any packages that require build-tools.

C:\> npm config set python /Python36/python

I had installed python3.6.3, on windows-7, there.


回答 14

为什么不在这里下载python安装程序?当您检查路径安装时,它将为您工作

Why not downloading the python installer here ? It make the work for you when you check the path installation


回答 15

对我来说,这些步骤解决了这个问题:

1-以管理员身份运行此cmd:

npm install --global --production windows-build-tools

2-然后npm rebuild在第一步完成后运行(尤其是完成python 2.7安装,这是问题的主要原因)

For me, these steps fixed the issue:

1- Running this cmd as admin:

npm install --global --production windows-build-tools

2- Then running npm rebuild after the 1st step is completed (especially completing the python 2.7 installation, which was the main cause of the issue)


回答 16

这是正确的命令:set path =%path%; C:\ Python34 [替换为正确的python安装路径]

我有同样的问题,我只是这样解决了。

正如其他人指出的那样,这是易失性配置,它仅适用于当前的cmd会话,并且(显然)您必须在运行npm install之前设置路径。

我希望这有帮助。

Here is the correct command: set path=%path%;C:\Python34 [Replace with the correct path of your python installation]

I had the same problem and I just solved this like that.

As some other people pointed out, this is volatile configuration, it only works for the current cmd session, and (obviously) you have to set your path before you run npm install.

I hope this helps.


回答 17

糟糕!配置错误gyp ERR!堆栈错误:找不到Python可执行文件“ python”,您可以设置PYT HON env变量。

无需重新安装,此异常由node-gyp脚本引发,然后尝试重新构建。设置环境变量就足够了,就像我所做的那样:

SET PYTHON=C:\work\_env\Python27\python.exe

gyp ERR! configure error gyp ERR! stack Error: Can’t find Python executable “python”, you can set the PYT HON env variable.

Not necessary to reinstall, this exception throw by node-gyp script, then try to rebuild. It’s enough setup environment variable like in my case I did:

SET PYTHON=C:\work\_env\Python27\python.exe

回答 18

如果您尝试在Cygwin上使用此功能,则需要按照答案中的说明进行操作。(这是Cygwin如何处理Windows符号链接的问题。)

If you’re trying to use this on Cygwin, then you need to follow the instructions in this answer. (It’s a problem how Cygwin treats Windows symlinks.)


回答 19

例子:pg_config不可执行/错误node-gyp

解决方案:在Windows上,只需尝试添加PATH Env-> C:\ Program Files \ PostgreSQL \ 12 \ bin

为我工作,现在我可以使用npm我pg-promise例如或其他依赖项。

Example : pg_config not executable / error node-gyp

Solution : On windows just try to add PATH Env -> C:\Program Files\PostgreSQL\12\bin

Work for me, Now i can use npm i pg-promise for example or other dependencies.


回答 20

对我来说,问题在于我使用的是节点的最新版本,而不是LTS稳定版本并建议大多数用户使用的版本。
使用LTS版本解决了该问题。
您可以从这里下载:

LTS版本

当前最新版本

For me, The issue was that i was using node’s latest version and not the LTS version which is the stable version and recommended for most users.
Using the LTS Version solved the issue.
You can download from here :

LTS Version

Current Latest Version


Caprover 可扩展的PaaS(自动Docker+nginx)

CapRover

适用于NodeJS、Python、PHP、Ruby、Go应用程序的最简单的应用程序/数据库部署平台和Web服务器软件包

不需要码头工人,nginx知识!



这是什么?

CapRover是一款极其易于使用的应用程序/数据库部署和Web服务器管理器,适用于NodeJS、Python、PHP、ASP.NET、Ruby、MySQL、MongoDB、Postgres、WordPress(等等)申请!

它的速度非常快,而且非常健壮,因为它在其简单易用的界面背后使用了Docker、nginx、LetsEncrypt和NetData

✔用于自动化和脚本编写的CLI

✔便于访问和方便的Web GUI

✔不能锁定!删除CapRover,您的应用程序将继续工作!

✔引擎盖下的码头工人蜂拥而至,进行集装箱化和集群化

✔Nginx(完全可定制的模板)在引擎盖下,用于负载均衡

✔让我们在幕后加密以获得免费的SSL(HTTPS)

我是认真的!谁应该关心CapRover?

  • 不喜欢花费数小时和数天时间设置服务器、构建工具、向服务器发送代码、构建服务器、获取SSL证书、安装证书、反复更新nginx的[web]开发人员
  • 开发人员使用昂贵的服务,如Heroku、Microsoft Azure等,并希望将其成本降低到原来的1/4(Heroku对其1 GB实例每月收费25美元,而同一服务器在Valltr上的收费是5美元!)
  • 喜欢写更多关于showResults(getUserList())而且不是很多$ apt-get install libstdc++6 > /dev/null
  • 喜欢在服务器上安装MySQL、MongoDB等的开发人员,方法是从下拉菜单中选择并单击Install!
  • 设置CapRover服务器需要多少服务器/坞站/Linux知识?答:复制粘贴知识!!有关要复制和粘贴的内容的信息,请转到“入门”;-)

了解更多信息!

有关更多详细信息和文档,请访问https://CapRover.com/

贡献者

这个项目的存在要归功于所有做出贡献的人。[Contribute]

支持者

感谢我们所有的支持者!🙏