我一直在研究一个非常简单的节点。带有一些路由的 Js 服务器。我尝试实现一条路由,该路由能够在每次到达时运行 python(3.6( 脚本,使用 Node Jschild-process
包。问题是:当我尝试这样做时,使用正确的命令行参数运行我的脚本,没有任何反应。
我已经尝试运行一个简单的命令,例如创建一个空文件或只是一个简单的pwd
一切正常。 其次,正如你在下面看到的,在我的 Python 脚本中,我使用logging
Python 包来跟踪工作流程。不幸的是,我的logfile.log
是空的。我还尝试从python中获取流并打印在标准输出中:什么都没有。脚本的路径是正确的,所以我真的不知道我手动执行脚本和 node.js 的有什么区别。
Node.js 代码:
app.get('/trigger',(req, res) => {
console.log('/trigger');
console.log(__dirname + "/../scripts/launcher.py")
var key = req.query['Key'];
const spawn = require('child_process').spawn;
const pythonProcess = spawn("python3.6", [__dirname + "/../scripts/launcher.py", key]);
console.log("process started with pid : " + pythonProcess.pid);
pythonProcess.stdout.on('data', (data) => {
console.log("child stdout")
console.log(`n${data}`);
});
res.status(200).send()
})
蟒蛇代码:
def init_logger():
# create logger with 'spam_application'
logger = logging.getLogger('spam_application')
logger.setLevel(logging.DEBUG)
# Load variable to env
load_dotenv()
# create file handler which logs even debug messages
fh = logging.FileHandler(dir_path + '/logfile.log')
fh.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter("%(asctime)s; %(levelname)s ; %(message)s",
"%d-%m-%Y %H:%M:%S ")
fh.setFormatter(formatter) # add formatter to ch
logger.addHandler(fh) # add ch to logger
return logger
def main():
logger = init_logger()
logger.info("logfile has been updated :D")
# Downloading mail before processing it
raw_mail = fetch_mail(sys.argv[1])
mailer = MailManager(logger)
if mailer.entry_point(raw_mail) == -1:
logger.error("Sender Not Authorized")
return -1
uploader = Uploader(logger)
uploader.initialize_warning_count()
result = mailer.get_mailobj()
uploader.entry_point(result)
return 0
最后是节点.js pm2 日志:
0|| 2019-09-23T12:29:55: /trigger
0|| 2019-09-23T12:29:55: my/path/to/script/launcher.py
0|| 2019-09-23T12:29:55: process started with pid : 19068
所以我有一个 PID,这意味着该命令运行良好(我不确定(。我希望能够将 python 的日志保存在日志文件中.log(就像我手动测试时一样(。有了这个日志,我将能够知道到底发生了什么。
谢谢大家,如果您需要有关我的问题的更多信息,请发表评论或自由编辑。
环境:python3.6,Ubuntu EC2实例中的节点v8.10.0。
当你使用 node 生成一个进程时,如果你想获得 stdio 输出,你需要把它作为一个选项传递,所以做这样的事情:
const pythonProcess = spawn("python3.6", [__dirname + "/../scripts/launcher.py", key], { stdio: 'inherit' });
检查: https://nodejs.org/api/child_process.html#child_process_options_stdio