如何从python脚本安装npm包?

问题描述 投票:4回答:2

如何从python脚本安装npm包?

当我使用subprocess.Popen(["node", "app.js"])时,没关系。 当我使用subprocess.Popen(["npm", "install", "open"])时,它会抛出一个错误。

对不起,Google和DuckDuckGo今天不是我的朋友(

主要问题 - 自动本地安装需要我的小实用程序包,因为全局包在Windows中不起作用。

PS。我不得不问这个问题,因为我正在尝试为Sublime Text 2开发一个插件。

这是Sublime python控制台中的错误:

Reloading plugin …\stsync.py
Traceback (most recent call last):
  File ".\sublime_plugin.py", line 103, in create_application_commands
    cmds.append(class_())
  File ".\stsync.py", line 16, in __init__
  File ".\subprocess.py", line 633, in __init__
  File ".\subprocess.py", line 842, in _execute_child
WindowsError: [Error 2] 

第16行:subprocess.Popen(["node", "npm", "install", "open"])


如果我将第16行更改为subprocess.Popen([“node”,“npm”,“install”,“open”]),那么python脚本将成功调用nodejs终端,但随后它将失败并显示错误: cannot find npm module

python node.js sublimetext2 npm
2个回答
2
投票

shell参数设置为True

subprocess.Popen(["node", "npm", "install", "open"], shell=True)

0
投票

在Windows上,许多Node.js“二进制文件”实际上都是以.cmd文件扩展名为后缀,无论出于何种原因,在subprocess.Popen调用期间,它都不会扩展(即使PATHEXT可能包含.cmd)。

因此,对于正确的解决方案(不使用shell=True),请尝试将.cmd附加到所需的Node.js二进制文件:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.Popen(['npm.cmd', 'install'])
<subprocess.Popen object at 0x005E18B0>
>>> npm ERR! install Couldn't read dependencies

当然它会抛出一个错误,因为我在该目录中没有package.json。使用其他一些常用程序再试一次,例如webpack

>>> subprocess.Popen(['webpack'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
...
FileNotFoundError: [WinError 2] The system cannot find the file specified

哦对了,加上.cmd

>>> subprocess.Popen(['webpack.cmd'])
<subprocess.Popen object at 0x008A18B0>
>>> No configuration file found and no output filename configured via CLI option
© www.soinside.com 2019 - 2024. All rights reserved.