【问题标题】:Have a Python index error on splitlines function分割线函数出现 Python 索引错误
【发布时间】:2020-05-26 12:03:31
【问题描述】:

以下 Python 代码在第 17 行给我一个索引错误,version = result[marker:].splitlines()[0]:

import os, math, sys

#OS_bit = (round(math.log(sys.maxint,2)+1)) # get the bit

os.system("sudo apt-get install python-pip && sudo apt-get install tor") # installing dependencies
os.system("pip install -U selenium")
os.system("pip install Pysocks")
os.system("pip install pyvirtualdisplay && apt-get install xvfb")

#print("\n \n {} \n \n".format(OS_bit))

os.system('firefox -v > tmp') 
result = open('tmp', 'r').read()
print (result)
marker = result.find('Firefox') + 8 
print (marker)
version = result[marker:].splitlines()[0] 
print (version)
a,b,c = version.split(".") 
os.remove('tmp') 

版本 = 结果[标记:].splitlines()[0]

IndexError: 列表索引超出范围

不知道如何解决。有什么可以分享的快速课程吗?谢谢。

【问题讨论】:

  • prints 对于每个组件的输出是什么? (markerresult
  • result 不输出任何内容,而 marker 给出 7。我假设由于 result 为空,因此标记索引超出范围。但是,我不知道为什么结果为空。
  • @Abagnale 如果 result 没有打印任何内容,这意味着没有什么可以继续进行的,并且在 result 索引将引发错误。由于 result.find('Firefox') 返回 -1,因此标记也给出 7 作为输出。第一步检查您尝试阅读的文件、约定等
  • 是的,tmp 是空的,但不确定为什么 firefox -v 没有向 tmp 传递任何东西。

标签: python python-3.x syntax index-error


【解决方案1】:

问题在于结果,结果不是一个列表,它只是一个赋值变量,这就是为什么你会看到 IndexError: list index out of range

【讨论】:

    【解决方案2】:

    Splitlines 返回一个列表,您正在访问此列表中的第一个元素。您的错误的原因是 string.splitlines() 返回一个空列表。

    >>> string = ""
    >>> string.splitlines()
    []
    >>> string.splitlines()[0]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: list index out of range
    

    【讨论】:

    • 在他的评论中他说print(result) 没有输出任何东西。 @SauravJoshi 提到 find() 返回 -1 表示结果为空
    • true,但是您不能索引 -1,这不是 list 或可以通过执行 [marker:] 进行索引的东西,所以错误在于 result,因为它在它
    • 是的,为什么 firefox -v 没有向 tmp 传递任何东西?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 2016-11-15
    • 2017-06-09
    • 2013-02-22
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多