函数调用在其他 IDE 中有效,但在 VS Code 中无效

Function recall working in other IDEs but not VS Code

我写了一些非常简单的代码:

def yo():
    text = "hi there"
    print(text) 
    print(text) 
  
  
yo()

我运行这个在Spyder和在线编译器中没有错误。明明是吐出来的:

hi there
hi there

但是当我 运行 在 VS Code 终端中使用“终端中的 运行 Python 文件”播放按钮时,我得到

"SyntaxError: invalid syntax" 

第 1 行(def 行)。

当我在终端中输入 yo() 时,我得到了预期的输出:

hi there
hi there

为什么我得到的结果不同? 我在 VS Code 中使用“播放”按钮执行了 Python 的其他简单位,没有问题。不用说,我安装了 python 扩展和解释器。

更新:我重新启动了 VS Code,现在文件 运行s 没有问题。我想“你重启电脑了吗”有时确实能解决问题...

您的函数 - yo() 正在定义中,但是 Visual Studio 代码不知道如何 运行 它。要解决此问题,请尝试添加 if __name__ == '__main__': 子句。这是您的完整代码:

def yo():
    text = "hi there"
    print(text) 
    print(text) 

if __name__ == '__main__':
    yo()

Here 是关于 if __name__ == '__main__':

的更多信息

如果这不能解决问题,那么您一定有一些格式问题或 Visual Studio 代码的一些不同设置。您可以执行以下操作。

  1. 确保您运行正在使用正确的文件
  2. 删除所有代码并重新粘贴
  3. 重置您的 Visual Studio 代码设置
  • 确保 Tab 的设置为 4 个空格。
  • 在设置中禁用 terminal.integrated.inheritEnv

如果一切都失败了,试试这些:

您应该在终端中使用 exit() 命令结束 python 会话。然后重新运行看看是否有任何效果。

运行 您的代码使用 'Start without debugging'。