TypeError: 'str' 对象无法被解释为整数,使用 pickle 时发生

0 投票
1 回答
57 浏览
提问于 2025-04-12 16:39

当我尝试打开这个pickle文件时,出现了这个错误:

Exception in thread Thread-1 (coinsv_thread):
Exception in thread Thread-2 (coinsv_thread):
Traceback (most recent call last):
Traceback (most recent call last):
  File "C:\Users\Gregory\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1073, in _bootstrap_inner
  File "C:\Users\Gregory\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1073, in _bootstrap_inner
    self.run()
  File "C:\Users\Gregory\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1010, in run
    self.run()
  File "C:\Users\Gregory\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1010, in run
    self._target(*self._args, **self._kwargs)
  File "c:\Users\Gregory\Desktop\Y7 Homework\Actual cOMPUTING ASESSMENT\Assesment-Y7\functionality.py", line 30, in coinsv_thread
    self._target(*self._args, **self._kwargs)
  File "c:\Users\Gregory\Desktop\Y7 Homework\Actual cOMPUTING ASESSMENT\Assesment-Y7\functionality.py", line 30, in coinsv_thread
    with open('rlog.pkl', 'rb') as handle:
         ^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'str' object cannot be interpreted as an integer
    with open('rlog.pkl', 'rb') as handle:
         ^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'str' object cannot be interpreted as an integer

这是我的代码:


def coinsv_thread(g):
    #try:
    if True:
        import pickle
        import webclient
        SERVER_URL = "http://gregglesthegreat.pythonanywhere.com/"
        with open('rlog.pkl', 'rb') as handle:
            a = pickle.load(handle)
            handle.close()
        if a[0] == 1:
            my_dict = webclient.get_variable(SERVER_URL, "d_pgp_LOGIN")
            my_user = my_dict.get(a[1])
            my_coins = my_user[1]
            my_new_coins = int(my_coins) + int(g)
            my_user[1] = my_new_coins
            my_dict[a[1]] = my_user
            webclient.update_variable(SERVER_URL, "d_pgp_LOGIN", my_dict)
        else:
            print("Not logged in.")
    #except Exception as e:
    #    print("Fail: ", e)

def coinsv(g):
    thread = threading.Thread(target=coinsv_thread, args=(g,))
    thread.start()

我试着在Python的命令行中打开这个文件,结果是可以的,我还在网上请AI帮忙。

1 个回答

1

这可能是因为一个很糟糕的做法,就是用 from 导入了 os 模块里的所有对象,这样就把内置的 open 函数给遮住了,变成了 os.open,而 os.open 的第二个参数需要是整数:

>>> from os import *
>>> open('flllf','ff')
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: an integer is required (got type str)

如果必须保留 from os import *,可以在导入后加上这个:

from os import *
del open

这样可以删除对 open 的引用,让内置的 open 函数再次可用。

不过,这样做会让代码变得难以阅读。推荐的解决方案是:

  • 去掉 from os import *
  • 在调用 os 模块的所有函数时,加上 os. 前缀(如果不加前缀,调用会失败,记得彻底测试脚本)

撰写回答