【问题标题】:Visual Studio Code Terminal keeps running Python script in PowershellVisual Studio Code Terminal 继续在 Powershell 中运行 Python 脚本
【发布时间】:2020-01-02 23:48:59
【问题描述】:

我最近安装了 Python 和 Visual Studio Code。上完介绍课后,我编写了一个基本脚本并在 Visual Studio Code 中运行它。那时我注意到在我的 Visual Studio 代码中设置 Python 的方式存在问题。 问题: 当我启动 Visual Studio Code 并打开一个 python 文件时,终端默​​认为“C:\Users\my_name\Documents Python”(这是我的 python 文件存储的文件夹)。据我了解,当您使用 Python 时,提示符应该是“>>>”。我能够运行我的脚本,但我无法在终端中运行任何其他 Python 代码(即像 z = 5 这样简单的代码)。如果我输入“Python”,我会收到“>>>”的提示,但无法再运行我的脚本。

我认为这是一个安装问题,所以我卸载并重新安装了 Python 和 Visual,但问题仍然存在。

我尝试在系统设置下将程序安装位置的 Python 文件路径添加到 Windows 环境中,并在重新安装 Python 时单击“添加到路径”,但这些解决方案似乎都不起作用。

当基本 python 代码(即 z=5)似乎不起作用但脚本运行良好时,我收到以下错误消息:

PS C:\Users\my_name\Documents\Python 2> z=5
z=5 : The term 'z=5' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ z=5
+ ~~~
    + CategoryInfo          : ObjectNotFound: (z=5:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

以下是我切换到 python 并尝试运行我的脚本后收到的错误消息

PS C:\Users\my_name\Documents\Python 2> python
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> & C:/Users/my_name/AppData/Local/Programs/Python/Python37-32/python.exe "c:/Users/my_name/Documents/Python 2/new2.py"
  File "<stdin>", line 1
    & C:/Users/my_name/AppData/Local/Programs/Python/Python37-32/python.exe "c:/Users/my_name/Documents/Python 2/new2.py"
    ^
SyntaxError: invalid syntax
>>>

【问题讨论】:

    标签: python python-3.x powershell visual-studio-code


    【解决方案1】:

    您的设置没有问题。看起来你错过了对执行 python 代码的不同方法的基本理解。

    VS Code 集成了终端。从那里您可以运行您的 python 脚本,即带有py 扩展名的文件,与您在终端/cmd/powershell 上的相同。这是编写和执行代码的常用方法。

    当您输入python 并按回车键时,您将启动python 交互式shell。那是当您收到&gt;&gt;&gt; 提示时。您的 python 解释器在您输入并按 Enter 时评估并执行每一行。如果您在 VS Code 之外的 cmd/powershell 中键入 python,也会发生同样的情况。交互模式或多或少用于实验、测试简单的想法、简单的代码示例等,但是一旦您通过&gt;&gt;&gt;exit()退出交互模式,您输入的代码就会丢失。

    您可以查看更多参考

    【讨论】:

    • 谢谢布兰。我仍然不明白为什么我不能输入像“z = 5”这样简单的东西并在运行脚本后在终端中测试简单的python代码。我的一个也在使用 Python 的朋友总是以“>>>”作为提示符,并且可以在使用终端测试代码的同时运行脚本。
    • 来自&gt;&gt;&gt;(即交互式提示)您无法运行脚本。在那里,您可以逐行输入和执行 python 代码。当您处于终端(不是 python 交互模式)时,您不能执行z = 5,因为它是未知命令。尝试在cmd 中运行它时,您将得到相同的错误。你检查了我分享的链接吗?
    • 我想到的唯一可能是您的朋友已经在 VSCode 中启动了 2(两个)集成终端并在它们之间切换(从终端右上角的下拉菜单中)。
    【解决方案2】:

    在阅读了上面的文档后,我在运行脚本后也遇到了类似的问题。我认为 VSC 在运行脚本后退出 python 并需要再次启动 python 终端。我想知道 VSC 在运行脚本后是否可以默认为 python 而不是退出到 powershell。

    【讨论】:

      【解决方案3】:

      我想出了问题所在。可视代码认为 Python 安装在我的 .py 文件保存的目录中,而不是程序文件下的实际位置。必须在设置下编辑路径。

      【讨论】:

      • 好的,但是你是怎么做的呢? (请显示代码)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 2023-03-10
      • 2016-01-01
      • 1970-01-01
      相关资源
      最近更新 更多