如何在我的脚本所在的目录中使用 python 脚本安装 npm 模块

How to install npm modules using a python script in the directory where my script is located

文件结构应如下所示:

test.py

node_modules(包含已安装的 npm 模块的文件夹)

我已经试过了:

import subprocess
import os
dir_path = os.path.dirname(os.path.realpath(__file__)) #holds the directory where python script is located
directory where python script is located
os.chdir(dir_path)
subprocess.call(["npm","init"])
subprocess.call(["npm","install"])

错误

回溯(最后一次调用): 文件 "c:\Users\Alifreeze.vscode\extensions\ms-python.python-2020.1.58038\pythonFiles\ptvsd_launcher.py",第 43 行,位于 主要(ptvsdArgs) 文件 "c:\Users\Alifreeze.vscode\extensions\ms-python.python-2020.1.58038\pythonFiles\lib\python\old_ptvsd\ptvsd__main__.py",第 432 行,在 main
中 运行() 文件 "c:\Users\Alifreeze.vscode\extensions\ms-python.python-2020.1.58038\pythonFiles\lib\python\old_ptvsd\ptvsd__main__.py",第 316 行,在 run_file 中 runpy.run_path(目标, run_name='main') 文件 "C:\Users\Alifreeze\AppData\Local\Programs\Python\Python37-32\lib\runpy.py",第 263 行,在 run_path 中 pkg_name=pkg_name, script_name=fname) 文件 "C:\Users\Alifreeze\AppData\Local\Programs\Python\Python37-32\lib\runpy.py",第 96 行,在 _run_module_code 中 mod_name、mod_spec、pkg_name、script_name) 文件 "C:\Users\Alifreeze\AppData\Local\Programs\Python\Python37-32\lib\runpy.py",第 85 行,在 _run_code 中 执行(代码,run_globals) 文件 "c:\Users\Alifreeze\Desktop\ShellScripts\npm.py",第 6 行,位于 subprocess.call(["npm","init"]) 文件 "C:\Users\Alifreeze\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py",第 323 行,调用中 以 Popen(*popenargs, **kwargs) 作为 p: 文件 "C:\Users\Alifreeze\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py",第 775 行,在 init 中 restore_signals, start_new_session) 文件 "C:\Users\Alifreeze\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py",第 1178 行,在 _execute_child 中 启动信息) FileNotFoundError: [WinError 2] 系统找不到指定的文件

import subprocess
subprocess.call(["npm","init"])
subprocess.call(["npm","install"])

在 test.py 脚本中尝试此代码,package.json 应该出现在同一文件夹中,而 运行 python 脚本

这对我有用!

import subprocess
import os
dir_path = os.path.dirname(os.path.realpath(__file__)) #holds the directory where python script is located
os.chdir(dir_path)
subprocess.check_call('npm init', shell=True)