如何捕获 subprocess.call 的输出

问题描述 投票:0回答:2

我制作了一个脚本来告诉我 Raspberry Pi 3 的温度,但该脚本有问题。结果输出是机器人说“您的 RPI3 温度当前为 0”。我的代码有什么问题吗?

@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)")

编辑:我知道想要运行任何命令。 当前脚本

@bot.command(pass_context=True) 异步 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")

我收到错误:

raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an 
 exception: CalledProcessError: Command 'vcgencmdmeasure_temp' returned 
  non-zero exit status 12
python python-3.x bots raspberry-pi3 discord.py
2个回答
3
投票

return_code
将有进程的返回码。当进程成功存在(没有错误)时,它会返回代码
0
。如果出错,它会返回
1
代码(或非零值)。如果您想要程序的输出(它打印到
stdout
),这是获取它的一种方法:

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))

注意:类似的方法适用于捕获错误和警告消息 - 您可以使用

stderr=subprocess.PIPE
参数对它们进行管道传输,然后使用
p.stderr.decode()
进行检索。


1
投票

您应该使用

subprocess.check_output
来获取命令的响应。

来自文档:

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

使用参数运行命令并将其输出作为字节字符串返回。

使用

call
给出返回码:

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, 外壳=假)

运行 args 描述的命令。等待命令 完成,然后返回returncode属性。

© www.soinside.com 2019 - 2024. All rights reserved.