我导入ctypes时不知道为什么会出错

时间:2017-09-09 10:10:33

标签: python ctypes built-in

我更改了内置函数len的定义,然后我尝试导入ctypes模块。但是我不知道为什么在我这样做时会出现错误。这是我的代码:

import builtins

def func(obj):
    print("Length: %d" % len(obj))
builtins.len = lambda obj: "Bad!!!"

import ctypes

然后这是错误的跟踪:

Traceback (most recent call last):


  File "<stdin>", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 661, in exec_module
  File "<frozen importlib._bootstrap_external>", line 772, in get_code
  File "<frozen importlib._bootstrap_external>", line 491, in _code_to_bytecode
  File "<frozen importlib._bootstrap_external>", line 42, in _w_long
ValueError: invalid literal for int() with base 10: 'Bad!!!'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 53, in apport_excepthook
    if not enabled():
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 24, in enabled
    import re
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 661, in exec_module
  File "<frozen importlib._bootstrap_external>", line 772, in get_code
  File "<frozen importlib._bootstrap_external>", line 491, in _code_to_bytecode
  File "<frozen importlib._bootstrap_external>", line 42, in _w_long
ValueError: invalid literal for int() with base 10: 'Bad!!!'

Original exception was:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 661, in exec_module
  File "<frozen importlib._bootstrap_external>", line 772, in get_code
  File "<frozen importlibbootstrap_external>", line 491, in _code_to_bytecode
  File "<frozen importlib._bootstrap_external>", line 42, in _w_long
ValueError: invalid literal for int() with base 10: 'Bad!!!'

这让我很困惑。非常感谢有人可以帮助我!

1 个答案:

答案 0 :(得分:1)

因为len函数返回非整数字符串。

您刚刚采用了与此相同的行为:

>>> int("I should know playing with builtins is always a bad thing")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'lol'

尝试更新您的代码,如:

builtins.len = lambda obj: "123"

要看到它。