好的,我知道有很多关于这个主题的问题,我阅读了大部分,但没有什么帮助。
我正在尝试让一个Node服务器定期运行一个Python脚本。为此,我有以下代码:
如您所见,该脚本只是在指定的命令和工作目录下运行exec。然而,当尝试执行func()时,节点会抛出上面指定的错误。
我尝试过的解决方法:
我正在尝试让一个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()时,节点会抛出上面指定的错误。
我尝试过的解决方法:
- 使用工作目录的绝对路径
- 检查python3是否在PATH中:which python3返回/usr/bin/python3
- 用sudo运行节点服务器
- 调试记录process.env.PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
/bin/sh
,所以我想它不是一个常规的Linux服务器。 - robertklep/bin/sh
吗?你可以尝试使用child_process.exec
的shell
选项,使其直接指向Python可执行文件,但是一个普通的Linux服务器没有/bin/sh
似乎很奇怪。 - robertklep/bin/sh -c ls
显示文件夹内容,所以它确实存在。 - Taxelcwd
,但你已经排除了这个可能性。所以还是很奇怪。 - robertklep