【问题标题】:unsupported operand type(s) for %: 'NoneType' and 'int' [duplicate]% 不支持的操作数类型:“NoneType”和“int”[重复]
【发布时间】:2016-09-15 15:16:29
【问题描述】:

我正在从事一个项目,我在网上找到了一个简单的 IP 地址,以便在谷歌地图对话中找到一个简单的汽车跟踪过程的位置。总共有 4 个文件,但我被困在 main.py 脚本上。我一直试图让它工作好几天。我取得了进展,但现在出现错误:

TypeError: %: 'NoneType' 和 'int' 的操作数类型不受支持

这是脚本:

#!/usr/bin/python
import sys,time,geolocation,publisher
from subprocess import call

SleepTime = 10 # seconds
_lat = 0.00
_lon = 0.00

def maintain():
    global _lat
    global _lon
(lat,lon,accuracy) = geolocation.getLocation()
if(lat != _lat or lon !=_lon):
    data = str(lat) + "," + str(lon) + "," + str(accuracy)
    print ("publishing") , data
    publisher.publishtoInternet(data)
    _lat = lat
    _lon = lon
else:
    print ("no change in coordinates")

print ("program begins")
while True:
try:
    maintain()
except Exception as inst:
    print (type)(inst), ('exception captured')
    print (inst)
    sys.stdout.flush()
    #file = open('/tmp/loctracker.error.log','a')
    #file.write('exception occured, trying to reboot')
    #file.close()
    #call(["sudo","reboot"])
#break
for i in range(0,SleepTime):
    sys.stdout.write ("\restarting in %d seconds ") % (SleepTime-i)
    sys.stdout.flush()
    time.sleep(1)

任何帮助将不胜感激!

问候

【问题讨论】:

  • 你能修复你的缩进吗?
  • 你能显示完整的回溯吗?
  • 我不同意关于 TypeError 的问题是关于 AttributeError 的问题的重复,即使不正确的分组导致了两者。

标签: python int nonetype


【解决方案1】:

在一行

sys.stdout.write ("\restarting in %d seconds ") % (SleepTime-i)

Python 认为您正在使用 mod 运算符对 sys.stdout.write(即None)和SleepTime - i(即 int)的结果进行数学运算。这是因为你有一个早期的括号。你想要的是打印整个结果:

sys.stdout.write ("restarting in %d seconds " % (SleepTime-i))

附带说明一下,在 Python 中,用于格式化的 % 是 frowned upon,而不是 string.format。

【讨论】:

    【解决方案2】:

    在这一行:

    sys.stdout.write ("\restarting in %d seconds ") % (SleepTime-i)
    

    您使用了不正确的分组。这是它正在做的事情,用更多的括号来说明:

    (sys.stdout.write ("\restarting in %d seconds ")) % (SleepTime-i)
    

    sys.stdout.write() 返回None,而你正在做None % integer。您需要将SleepTime-i 放在调用中,因此它适用于字符串而不是函数调用:

    sys.stdout.write("\restarting in %d seconds " % (SleepTime-i))
    

    【讨论】:

      猜你喜欢
      • 2016-09-07
      • 2018-04-16
      • 2017-12-27
      • 2014-03-31
      • 2021-05-23
      • 2015-10-15
      • 1970-01-01
      • 1970-01-01
      • 2014-11-15
      相关资源
      最近更新 更多