【发布时间】: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 Test和Import Test.py,它抛出了一个 ModuleNotFoundError: No module named 'Test'。最后,我尝试了import test from Test和import test from Test.py,它抛出了一个 SyntaxError: invalid syntax -
是的,我的意思是
test.py不是text.py,抱歉。试试from test import test。这应该可以解决问题。 -
如果你已经完成了
import test,那么你只需要做test.test()