【问题标题】:Why is the Python repl in Visual Studio Code telling me my objects are undefined?为什么 Visual Studio Code 中的 Python repl 告诉我我的对象未定义?
【发布时间】:2020-06-04 19:52:52
【问题描述】:

Test.py:

def test():
    print("Hello World")

test()

当我使用解释器(ctrl+shift+p > Python:选择解释器> 目标解释器)运行它时,它可以工作。

如果我尝试运行 repl (ctrl+shift+p > Python: Start REPL),我会看到 repl 在终端中启动:

PS C:\Development\personal\python\GettingStarted> & c:/Development/personal/python/GettingStarted/.venv/Scripts/python.exe
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 

但是,如果我尝试执行 repl 中定义的方法,我会得到一个未定义的错误:

>>> test() 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined

【问题讨论】:

  • 为什么这被否决了?是不是你只需要先从text.py 导入test 到你的repl 会话中?
  • 也许我需要在 repl 中进行导入?我试过import test(方法的名称)。这在repl中成功了。但是当我调用 test() 方法时,它抛出了一个 TypeError: 'module' object is not callable。我还尝试导入模块:import TestImport Test.py,它抛出了一个 ModuleNotFoundError: No module named 'Test'。最后,我尝试了import test from Testimport test from Test.py,它抛出了一个 SyntaxError: invalid syntax
  • 是的,我的意思是 test.py 不是 text.py,抱歉。试试from test import test。这应该可以解决问题。
  • 如果你已经完成了import test,那么你只需要做test.test()

标签: python visual-studio-code


【解决方案1】:

导入和使用的正确方法#1:

>>> import test
Hello World
>>> test.test()
Hello World

正确的方法#2导入和使用:

>>> from test import test
Hello World
>>> test()
Hello World

如果以上两种方式都得到ImportError,则说明您从错误的目录运行 Python REPL。

文件名和函数名相同,这有点令人困惑。

在文件末尾调用test() 也有点不寻常(导致函数在import 时被调用)。通常它像if __name__ == '__main__': test() 一样包装以避免在import 时间调用,但在从命令行作为脚本运行时进行调用。

Import test 不起作用,因为 Python 关键字是小写且区分大小写的。

from test import Test 不起作用,因为 Python 标识符(例如函数名)区分大小写。

import Test 可能适用于 Windows(但不适用于 macOS、Linux 和许多其他操作系统),因为 Windows 上的文件名不区分大小写。

import test.py 不起作用,因为不允许将 .py 扩展名作为导入模块名称的一部分。

import test from test 不起作用,因为from ... 必须在import ... 之前。

【讨论】:

  • 问题出在目录上。我没有注意VS Code没有在我的文件所在的目录中启动repl。谢谢。
  • 除了上面的回复之外,如果您打算在作为脚本运行时调用函数,您还应该保护if __name__ == '__main__': 块内的函数调用。这将保护导入期间的错误函数调用(如您所见,导入模块时调用了该函数,我确定您不希望这样的执行流程)
猜你喜欢
  • 2015-02-07
  • 1970-01-01
  • 2010-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多