python - 无法将字符串转换为 float

标签 python python-3.x

我需要从服务器获取 GPU-Power。 这应该通过 nvidia-smi 来完成。

  def getGpuPower(self):
      splitedGpuPower = os.popen("nvidia-smi --query-gpu=power.draw --format=csv,noheader,nounits").read().replace("\n", ",").split(",")
      for x in range(4):
        self.gpuPower += float(splitedGpuPower[x])
      return self.gpuPower

我需要一个像 250,00 这样的 float

我真的明白了

(  File "test1.py", line 22, in getGpuPower
    self.gpuPower += float(splitedGpuPower[x])
ValueError: could not convert string to float:)

输出看起来像这样

$ nvidia-smi --query-gpu=power.draw --format=csv,noheader,nounits

8.50
7.43
11.04

最佳答案

假设 os.popen("nvidia-smi --query-gpu=power.draw --format=csv,noheader,nounits").read() 的输出是 8.50\n7.43\n11.04,以下应该可以工作。

def getGpuPower():
      #Split on newline
      splitedGpuPower = "8.50\n7.43\n11.04".split("\n")
      gpuPower = 0
      #Iterate through the list
      for power in splitedGpuPower:
          #If string is non empty, convert to float and add
          if power.strip() != '':
              gpuPower += float(power)
      print(gpuPower)

输出将是

getGpuPower()
#26.97

关于python - 无法将字符串转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55806434/

相关文章:

python - 在 Bokeh 图中添加可点击的圆圈

python-3.x - 我如何在 ReadTheDocs 中将 matplotlib 的 plot-directive 与 python-3 一起使用?

python - 使用 anaconda python 3.52 导入 sklearn 错误

Python解释器与脚本的关系

python - 计算文本文件中的每个单词并输出成本

python - 异步服务调用 Python

python-3.x - 无法获取缺少的 termios 模块。我如何正确获得它?

python-3.x - python如何获得多列下所有行对之间的差异

java - 在云数据库上使用 Apache Beam 更改文件元数据?

Python 扩展了一个空列表错误?