How to capture output of subprocess.call

最后都变了- 提交于 2021-02-10 05:15:10

问题


I have made a script that tells me the temperature of my Raspberry Pi 3, but there is a problem with the script. The result output is the bot saying "Your RPI3 temp is currently 0". What is wrong with my code?

@bot.command(pass_context=True)
async def vcgencmdmeasure_temp(ctx):
    if ctx.message.author.id == "412372079242117123":
        await bot.say("OK....")
        return_code = subprocess.call("vcgencmd measure_temp", shell=True)
        await bot.say("KK done")
        await bot.say("Your RPI3 temp is currently: {}".format(return_code))
    else:
        await bot.say("Error user lacks perms(only bot owner can run this)")

EDIT: i know want to run any command. Current script

@bot.command(pass_context=True) async def rpicmd(ctx, *args):

if ctx.message.author.id == "412372079242117123":
    mesg = ''.join(args)
    mesg = str(mesg)
    command_output = subprocess.check_output(mesg, shell=True, universal_newlines=True)
    await bot.say(command_output)
else:
    await bot.say("No noob")

and i get the error:

raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an 
 exception: CalledProcessError: Command 'vcgencmdmeasure_temp' returned 
  non-zero exit status 12

回答1:


return_code will have the return code of the process. When a process exists successfully (without error), it returns a code of 0. If it errors, it returns a code of 1 (or something non-zero). If you want the output of the program (that it prints to stdout), this is one way to get it:

p = subprocess.run("vcgencmd measure_temp", shell=True,stdout=subprocess.PIPE)
result = p.stdout.decode()
await bot.say("Your RPI3 temp is currently: {}".format(result))



回答2:


You should use subprocess.check_output to get the response from your command.

From the docs:

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

Run command with arguments and return its output as a byte string.

Using call gives the returncode:

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

Run the command described by args. Wait for command to complete, then return the returncode attribute.



来源:https://stackoverflow.com/questions/50474995/how-to-capture-output-of-subprocess-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!