Home > Enterprise >  Is there a way to get line-by-line console output and print it in a separate script?
Is there a way to get line-by-line console output and print it in a separate script?

Time:11-01

In a script that runs a discord bot, I'd like to run other scripts when the user requests it (like /script2) and print line by line the console output that this called script is outputting, sending a new discord message with the contents every time there's a new output.

So far I've made the script recognize when the user wants to run a command by searching for the "/" at the start, but am having trouble finding the right way to run the requested script from within another program, and sending the console output in the discord channel.

Does anyone know how to help?

Source Code

import discord
from subprocess import run        #As of right now i'm using run to run the script, but it is simply the easiest way I managed to do it in.

TOKEN = 'TOKEN(Removed for the post)'

client = discord.Client()

@client.event
async def on_ready():
  print("Logged in as {0.user}".format(client))

@client.event
async def on_message(message):
  username = str(message.author).split("#")[0]
  usermsg = str(message.content)
  channel = str(message.channel.name)
  print(f'{username}, {usermsg}, {channel}')

if message.author == client.user:
    return

if message.channel.name == "test":
    if usermsg.startswith("/"):
        await message.channel.send(f'Executing your requested script, {username}')
        arg = str(usermsg[1:len(usermsg)])
        result = run(["python3", "Path/to/script", arg], capture_output=True)
        output = result.stdout  # At the moment, the second script doesn't output anything on the console, which is also not what I want. I would love if you could get both console output and send line-by-line output to discord, although I could live with the output only being sent to the discord channel.
        print(output)
        await message.channel.send(output)

client.run(TOKEN)

CodePudding user response:

There's no attribute as result.output, the attribute you're looking for is stdout, this however returns a bytes sequence, you can decode it to convert it to a string:

import sys

result = run([sys.executable, "Path/to/script", arg], capture_output=True)
output = result.stdout.decode("utf-8")
print(output)
  • Related