我正在尝试从正在监听Unix域套接字的python进程中接收数据,但是每次我启动节点应用程序时,它都会在片刻后退出。我试图在没有节点的情况下执行python脚本,它可以正常工作。我还阅读了节点文档https://nodejs.org/api/child_process.html和几篇文章,以查看我是否做错了什么,但仍然没有任何线索。我使用的节点脚本如下:
const { spawn } = require("child_process");
console.log("Spawing process");
let listener = spawn('python', ['./app_connection/dc_socket.py']);
listener.on('error', (err) => {
console.log(err);
});
listener.stdout.on('data', (data) => {
console.log(data.toString('utf8'));
});
并且python脚本是:
import socket
import logging
import os
import sys
REL_DEBUG_PATH = '../logs'
DEBUG_FILE_NAME = 'dc_socket.log'
BASE_PATH = os.path.dirname(__file__)
DEBUG_PATH = os.path.join(BASE_PATH, REL_DEBUG_PATH, DEBUG_FILE_NAME)
socket_logger = logging.getLogger(__name__)
debug_handler = logging.FileHandler(DEBUG_PATH)
debug_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
debug_handler.setFormatter(debug_format)
socket_logger.addHandler(debug_handler)
socket_logger.setLevel(logging.DEBUG)
# Datachannel messages will be intercepted by UV4L and will be published
# on the unix socket defined below
socket_path = '/tmp/uv4l.socket'
socket_logger.debug("Socket path: {}".format(socket_path))
try:
os.unlink(socket_path)
except OSError:
if os.path.exists(socket_path):
socket_logger.error("Could not create socket.")
raise
MESSAGE_SIZE = 1024 # bytes
# But we must create the socket in order to allow UV4L to send messages
socket_logger.debug("Initializing socket.")
with socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) as dc_socket:
dc_socket.bind(socket_path)
dc_socket.listen(1)
socket_logger.debug("Listening on {}".format(socket_path))
connection, address = dc_socket.accept()
with connection:
socket_logger.debug("Connected with {}".format(address))
while True:
message = connection.recv(MESSAGE_SIZE)
if not message:
break
print(message) # Send message to parent process through stdout
socket_logger.debug("Message: {}".format(message.decode('utf-8')))
sys.stdout.flush()
当我使用node gateway.js
运行该应用程序时,我得到的是以下信息:
$ node gateway.js
Spawing process
$
Python脚本的日志文件如下所示:
2020-04-16 21:25:28,229 - __main__ - DEBUG - socket path: /tmp/uv4l.socket
2020-04-16 21:25:28,257 - __main__ - DEBUG - Initializing socket.
还没有建立与套接字的连接,有什么线索在发生什么?我花了很多时间试图弄清楚,但还没有。