【问题标题】:return output from terminal从终端返回输出
【发布时间】:2019-12-05 21:45:49
【问题描述】:

我想问一下有没有办法从终端返回一个终止的值给python?例如,我使用os.system 将此行写入 ubuntu 终端

 cat /sys/devices/virtual/thermal/thermal_zone*/temp

返回几个值,我希望能够在 python 代码中再次访问这些值,这可能吗?

【问题讨论】:

  • 你应该检查模块psutilpsutil.sensors_temperatures()

标签: python python-3.x ubuntu operating-system


【解决方案1】:

os.system 已被弃用,或至少被subprocess 取代

您可以使用subprocess.run 轻松捕获输出

result = subprocess.run(['cat', '/sys/devices/virtual/thermal/thermal_zone*/temp'], capture_output=True)
print(result.stdout)

【讨论】:

  • 我试过了,但它说unexpected keyword argument 'capture_output'所以我搜索并找到stdout=PIPE, stderr=PIPE insted of capture_output,但这个只返回b' '
【解决方案2】:

因为你在命令中有*,所以你必须使用shell=True,shell 会用全名代替*

import subprocess

process = subprocess.run('cat /sys/devices/virtual/thermal/thermal_zone*/temp', shell=True, capture_output=True)

print(process.stdout.decode())

我的 Linux Mint 上的结果:

66000
47000

【讨论】:

  • 谢谢!这个有效。没有外壳,它输入“*”不是“全部”而是“x”?
【解决方案3】:

我认为您正在寻找这样的东西:Retrieving the output of subprocess.call()

示例:

p = Popen(['ls', '-l'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate(b"input data that is passed to subprocess' stdin")
rc = p.returncode

【讨论】:

    【解决方案4】:

    如果您使用的是旧版本的 Python(

    from subprocess import check_output
    result = check_output(["cat", "/sys/devices/virtual/thermal/thermal_zone*/temp"])
    print(result)
    

    【讨论】:

    • 对不起,我是 3.6 :(
    猜你喜欢
    • 2013-08-18
    • 2019-10-19
    • 2015-02-12
    • 1970-01-01
    • 2021-03-29
    • 2018-08-19
    • 2012-01-12
    • 1970-01-01
    • 2019-04-10
    相关资源
    最近更新 更多