好吧,我知道关于这个主题有很多问题,我阅读了其中的大部分,但没有任何帮助。
我正在尝试让 Node 服务器定期运行 python 脚本。为此,我有以下代码:
const
{ exec } = require('child_process');
const fs = require('fs');
let config = [
{
"title": "My Python Script",
"description": "A script that can scrape website data",
"command": "python3 collect_data.py",
"dir": "../file_folder",
"minutesBetweenExecution": 60
}
];
const intervals = [];
function startCronjobs() {
while (intervals.length > 0) {
clearInterval(intervals.pop());
}
console.log("Starting cronjobs...")
for (let i = 0; i < config.length; i++) {
const cron = config[i];
const func = () => {
exec(cron.command, { cwd: cron.dir, timeout: 40 * 60000 }, (err, stdout, stderr) => {
if (err) {
// node couldn't execute the command
console.error('Command could not be executed. Error: ', err, ' cron entry: ', cron.title);
return;
}
console.log('Output after ', cron.title);
// the *entire* stdout and stderr (buffered)
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
};
intervals.push(setInterval(func, parseInt(cron.minutesBetweenExecution) * 60000));
console.log('Started Cronjob', cron.title);
func();
}
}
startCronjobs();
如您所见,该脚本仅使用指定的命令和工作目录运行 exec。
然而,当尝试执行 func()
Node 时,会抛出上面指定的错误。
我尝试解决此问题的方法:
- 使用工作目录的绝对路径
- 检查
python3
是否在 PATH 中:which python3
返回/usr/bin/python3
- 使用
sudo
运行 Node 服务器 - 调试记录
process.env.PATH
:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin :/usr/games:/usr/local/games
奇怪的是:当我尝试在本地 Linux 机器上运行它时,它运行得很好。然而,在我的远程服务器上却没有。我错过了什么?
最佳答案
好吧,我是个白痴。
我本地计算机上的文件夹的命名与 git 存储库的命名不同,因此服务器上的文件夹的命名也不同,因为我只是 git 克隆了它。
修复:将工作目录中的 _
更改为 -
并且它可以工作...
关于python - 远程服务器上的 Node 错误 spawn/bin/sh ENOENT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52613897/