Issue
I run the jar like this:
import subprocess
subprocess.call([java8_path, '-jar', core_path])
and everything works and the logs of the jar file are output to the console, but I cannot specify one thing
I need the logs from the jar file not to be output directly to the console, but to be sent to me by the tg bot
from aiogram import types
async def send_logs(jar_log_text: str):
await bot.send_message(0000000, jar_log_text)
but I don't know threads and subprocesses and don't understand how to do it.
Solution
Instead of subprocess.call()
use subprocess.Popen
with PIPE
. This snippet runs your jar file and sends it's output as string to your send_log
function continuously.
(Until your process is alive, the value of p.poll()
is None
so the while loop stops whenever the process ends.)
Since there is no poll
method in asyncio
, I use this method (is_running
)
import contextlib
import asyncio
async def is_running(proc):
with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(proc.wait(), 1e-6)
return proc.returncode is None
async def main():
global proc
server_path = '../servers_community/cree'
proc = await asyncio.create_subprocess_exec(*[JAVA8_PATH, '-jar', 'spigot-1.12.2.jar'], stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, cwd=server_path)
while await is_running(proc):
text = (await proc.stdout.readline()).decode("cp866")
if text:
await bot.send_message(0000000, text)
asyncio.run(main())
Answered By - Ali Ent
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.