Python IndexError: 元组索引超出范围。

8

非常希望能够得到有关这个问题的反馈意见。

import subprocess

def main():
'''
Here's where the whole thing starts.
'''
#Edit this constant to change the file name in the git log command.
FILE_NAME = 'file1.xml'

#Do the git describe command to get the tag names.
gitDescribe = 'git describe --tags `git rev-list --tags --max-count=2`'
print ('Invoking: {0}'.format(gitDescribe))
p1 = subprocess.Popen(gitDescribe, shell=True, stdout=subprocess.PIPE)
output = p1.stdout.read()

#Get the first 2 tags from the output.
parsedOutput = output.split('\n')
tag1 = parsedOutput[0]
tag2 = parsedOutput[1]

print('First revision: {0}'.format(tag1))
print('Second revision: {1}'.format(tag2))
#Do the git log command for the revision comparison.
gitLog = 'git log {0}..{1} --pretty=format:"%an %h %ad %d %s" --date=short --topo-order --no-merges {2}'.format(tag1, tag2, FILE_NAME)
print('Invoking: {0}'.format(gitLog))
p2 = subprocess.Popen(gitLog, shell=True, stdout=subprocess.PIPE)
output = p2.stdout.read()
print(output)

if __name__ == "__main__":
    main()

...

bash-3.2$ python pygit5.py 
Invoking: git describe --tags `git rev-list --tags --max-count=2`

First revision: 14.5.5.1
Traceback (most recent call last):
File "pygit5.py", line 31, in <module>
main()
File "pygit5.py", line 22, in main
print('Second revision: {1}'.format(tag2))
IndexError: tuple index out of range
2个回答

13
< p>tag2 是一个单一的值,就像tag1一样,所以你不能引用item[1]。毫无疑问,你的意思是

print('Second revision: {0}'.format(tag2))

7
或许tag2是一个元组,然后使用*tag2将元组展开为format调用的参数,{1}将使用元组中的第二个项目。 - Sean Perry

8

当您使用类似于这样的格式时,请记住在大多数编程语言中,计数从零开始。因此,由于tag2仅承载一个值,因此以下行:

print('Second revision: {1}'.format(tag2))

应该是:

print('Second revision: {0}'.format(tag2))

如果您使用的是 Python 2.7+,对于简单的脚本,也可以将其保留为空:

print('Second revision: {}'.format(tag2))

或者使用命名变量以任何顺序提供它们:

print('Second revision: {revisiontag}'.format(revisiontag=tag2))

在Python 2.6中,你必须在大括号中放置某种索引。空的大括号只适用于2.7+和3.x版本。 - Sean Perry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接