I have a python code that runs Linux top command using asyncio.create_subprocess_exec to get the real-time output and send it to a WebSocket connection.
The code works well when I run it in the bash shell, but it doesn't work when I run the code as a background service.
I get this error in the logs b'Error opening terminal: unknown.\r\n'.
I suspect that the backend service is not able to execute the Linux top command in the terminal.
My Question is
How do I make the background service access the tty (terminal) to execute the top command and read its output?
I am using python3.6, Asyncio, and aiohttp libraries.
code snippet
async def execute_top(self,request):
cmd = ['top']
line_count = 0
ws = request.pop('ws')
try:
async for res in self.run_commands(cmd):
await ws.send_str(res)
except Exception as e:
self.log.error("{}".format(e))
async def run_commands(self,command):
master, slave = pty.openpty()
self.log.info("tty status : {}".format(sys.stdout.isatty()))
process = await asyncio.create_subprocess_exec(*command, stdout=slave, start_new_session=True)
yield os.read(master, 1000)