如何在python脚本中修复“以10为底的int <>的无效文字”错误

时间:2019-02-05 15:58:33

标签: python python-2.7

我正在运行一个脚本来转换一些媒体文件,当我这样做时,脚本将返回错误invalid literal for int<> with base 10: line 132。这不是我的脚本,也不是作者支持的,这就是为什么我在这里寻求帮助。

# Make time human-readable
def humanize_time(secs): ## Line:132
    if secs != "N/A":
        mins, secs = divmod(int(secs), 60)
        hours, mins = divmod(mins, 60)
        return '%02d:%02d:%02d' % (hours, mins, secs)
    else:
        mins, secs = divmod(30, 60)
        hours, mins = divmod(mins, 60)
        return '%02d:%02d:%02d' % (hours, mins, secs)


Traceback (most recent call last):
File "C:\conv2mp4-py.py", line 415, in <module>
codec_discovery()
File "C:\conv2mp4-py.py", line 165, in codec_discover
get_duration_temp = humanize_time(head)
File "C:\conv2mp4-py.py", line 132, in humanize_time
mins, secs = divmod(int(secs), 60)
ValueError: invalid literal for int() with base 10: ''

脚本:https://github.com/BrianDMG/conv2mp4-py/blob/master/conv2mp4-py.py

2 个答案:

答案 0 :(得分:0)

也许secs变量为空或其中包含空格。检查字符串是否为空,是否可以保证secs的值不包含空格。

# Make time human-readable
Line:132 def humanize_time(secs):
    if secs != "":
        mins, secs = divmod(int(secs), 60)
        hours, mins = divmod(mins, 60)
        return '%02d:%02d:%02d' % (hours, mins, secs)
    else:
        mins, secs = divmod(30, 60)
        hours, mins = divmod(mins, 60)
        return '%02d:%02d:%02d' % (hours, mins, secs)

答案 1 :(得分:0)

实现此类功能的正确方法是:

def humanize_time(secs=30):
    mins, secs = divmod(int(secs), 60)
    hours, mins = divmod(mins, 60)
    return '%02d:%02d:%02d' % (hours, mins, secs)

但是在这种情况下,您必须注意传递给它的参数。

如果您无法控制输入,则必须实施异常管理:

def humanize_time(secs=30):
    try: 
        mins, secs = divmod(int(secs), 60)
        hours, mins = divmod(mins, 60)
        return '%02d:%02d:%02d' % (hours, mins, secs)
    except (TypeError, ValueError) as e:
        raise ValueError("Invalid value for 'secs': '" + str(secs) + "'")

print humanize_time(12)  #>> 00:00:12
print humanize_time("a")   #>> ValueError: Invalid value for 'secs': 'a'