简体   繁体   English

为什么在 Visual Studio Code 上运行 Python 3 脚本时会出现 SyntaxError?

[英]Why do I get SyntaxError when running a Python 3 script on Visual Studio Code?

I was progressing through the exercises on Zed Shaw's Learn Python 3 the Hard Way but then on Exercise 6, I encountered a syntax error, which I am not able to figure out.我正在完成Zed Shaw 的 Learn Python 3 the Hard Way的练习,但在练习 6 中,我遇到了一个语法错误,我无法弄清楚。 I tried searching on Google, StackOverflow (other posts), but none of the solutions mentioned work for me.我尝试在 Google、StackOverflow(其他帖子)上进行搜索,但没有提到的解决方案对我有用。

The snippet of the code that is throwing this error is:引发此错误的代码片段是:

types_of_people = 10
x = f"There are {types_of_people} types of people."
print(x)

I am using Visual Studio Code 1.38.1, with Python 3.7.4 64-bit on macOS Mojave 10.14.6.我在 macOS Mojave 10.14.6 上使用 Visual Studio Code 1.38.1,Python 3.7.4 64 位。

Surprisingly, I executed the code three different ways, and two of the methods showed the same error, but a third method actually executed the code successfully.令人惊讶的是,我以三种不同的方式执行代码,其中两种方法显示相同的错误,但第三种方法实际上成功地执行了代码。 I am trying to understand why VSCode is not able to execute the python script.我试图了解为什么 VSCode 无法执行 python 脚本。 Any help would be highly appreciated.任何帮助将不胜感激。

Method 1方法一

Used the standard way to execute python script in VSCode:使用标准方式在 VSCode 中执行 python 脚本:

This method gave the SyntaxError.这个方法给出了 SyntaxError。 The error output is:错误 output 是:

[Running] python -u "/Users/e139177/Documents/Programming/Learn-Programming/tempCodeRunnerFile.py"
File "/Users/e139177/Documents/Programming/Learn-Programming/tempCodeRunnerFile.py", line 2
x = f"There are {types_of_people} types of people."
SyntaxError: invalid syntax
[Done] exited with code=1 in 0.035 seconds

Screenshot 1 shows the error in VS Code.屏幕截图 1 显示了 VS Code 中的错误。

VSCode 标准运行命令

Method 2方法二

Used "Run Python file in terminal" option in VS Code.在 VS Code 中使用了“在终端中运行 Python 文件”选项。

This method executed the script successfully, and the output generated is:该方法执行脚本成功,生成的output为:

KENMACC02XG4AEJHD2:Learn-Programminge139177$/usr/local/bin/python3/Users/e139177/Documents/Programming/Learn-Programming/Exercise6.py
There are 10 types of people.
KENMACC02XG4AEJHD2:Learn-Programming e139177$

Screenshot 2 shows the successfully executed script in VS Code terminal.屏幕截图 2 显示了在 VS Code 终端中成功执行的脚本。

VSCode 终端输出

Method 3方法三

Used MacOS terminal to directly execute the python script, without using VSCode.使用MacOS终端直接执行python脚本,不使用VSCode。

This method also gave the same SyntaxError.这个方法也给出了相同的 SyntaxError。 The error output is:错误 output 是:

 KENMACC02XG4AEJHD2:Learn-Programming e139177$ python Exercise6.py
  File "Exercise6.py", line 2
    x = f"There are {types_of_people} types of people."
                                                      ^
SyntaxError: invalid syntax
KENMACC02XG4AEJHD2:Learn-Programming e139177$

Screenshot 3 shows the successfully executed script in VS Code terminal.屏幕截图 3 显示了在 VS Code 终端中成功执行的脚本。

MacOS 终端输出

I am not sure why the script executes successfully when run within the VSCode terminal, but it does not do so when executed using VSCode's "Run" command, or when executed within the macOS terminal directly.我不确定为什么脚本在 VSCode 终端中运行时会成功执行,但是在使用 VSCode 的“运行”命令执行时,或者直接在 macOS 终端中执行时,它不会这样做。

In Method 1 you are using the Code Runner extension, not the Python extension and so it is simply using python and not the Python interpreter you have selected for the Python extension. In Method 1 you are using the Code Runner extension, not the Python extension and so it is simply using python and not the Python interpreter you have selected for the Python extension. Method 3 fails because python is traditionally Python 2 unless you have an activated virtual environment and macOS only comes with Python 2 installed by default.方法 3 失败,因为python传统上是 Python 2 ,除非您有激活的虚拟环境,并且 macOS 仅默认安装 Python 2 。

To solve Method 1 you will have to set up Code Runner appropriately.要解决方法 1,您必须适当地设置 Code Runner。 for Method 3 you can use a virtual environment for Python 3 and when that's activated you will get what you expect when running python .对于方法 3,您可以为 Python 3 使用虚拟环境,当它被激活时,您将在运行python时得到您所期望的。

The main problem with Method 1 and Method 3 is that you are using Python 2.7 to run your app, and f-strings are only available starting on Python 3.6.方法 1方法 3的主要问题是您使用 Python 2.7 来运行您的应用程序,并且f 字符串仅从 Python 3.6 开始可用。

Basically, you need to make sure you are using a Python 3.6+ interpreter.基本上,您需要确保您使用的是 Python 3.6+ 解释器。 The answer from Brett Cannon pretty much summarizes how to do that, but here is the expanded form of that answer. Brett Cannon 的答案几乎总结了如何做到这一点,但这是该答案的扩展形式。


Method 1: Code Runner方法 1:代码运行器

The "[Running]" part of the terminal output indicates you are using Code Runner (notice the screenshots of the extension page also show "[Running]" ).终端 output 的"[Running]"部分表示您正在使用Code Runner (请注意扩展页面的屏幕截图也显示"[Running]" )。 Code Runner has an Executor Map , which sets how it runs the code for different languages: Code Runner 有一个Executor Map ,它设置了它如何运行不同语言的代码:

Configuration配置

Make sure the executor PATH of each language is set in the environment variable.确保在环境变量中设置了每种语言的执行程序 PATH。 You could also add entry into code-runner.executorMap to set the executor PATH .您还可以在code-runner.executorMap中添加条目以设置执行程序PATH eg To set the executor PATH for ruby, php and HTML:例如,为 ruby、php 和 HTML 设置执行程序PATH

 { "code-runner.executorMap": { "javascript": "node", "php": "C:\\php\\php.exe", "python": "python", "perl": "perl", "ruby": "C:\\Ruby23-x64\\bin\\ruby.exe", "go": "go run", "html": "\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe\"", "java": "cd $dir && javac $fileName && java $fileNameWithoutExt", "c": "cd $dir && gcc $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt" } }

By default, it just uses python , which, depending on your system, can be Python 2 or some other version that is not the correct version you want to use.默认情况下,它只使用python ,根据您的系统,它可以是 Python 2 或其他一些不是您想要使用的正确版本的版本。

You'll need to change it in the settings.您需要在设置中更改它。

设置代码运行器

On clicking "Edit in settings.json", find the entry for python :单击“在 settings.json 中编辑”,找到python的条目:

    "code-runner.executorMap": {
        ...
        "python": "python -u",
        ...

And change it to the correct Python version:并将其更改为正确的 Python 版本:

    "code-runner.executorMap": {
        ...
        "python": "/usr/local/opt/python@3.8/bin/python3 -u",

In the example above, I set it to the Python3.8 installed with Homebrew:在上面的示例中,我将其设置为随 Homebrew 一起安装的 Python3.8:

$ brew info python@3.8
...
Python has been installed as
  /usr/local/opt/python@3.8/bin/python3

Then check that Code Runner now uses the correct path:然后检查 Code Runner 现在是否使用正确的路径:

[Running] /usr/local/opt/python@3.8/bin/python3 -u "/path/to/test.py"
There are 10 types of people.

Used the standard way to execute python script in VSCode使用标准方式在 VSCode 中执行 python 脚本

Actually, using Code Runner isn't the " standard way ".实际上,使用 Code Runner 并不是“标准方式”。 You don't actually need it.你实际上并不需要它。 The VS Code docs on Python in Visual Studio Code does not tell you to install it. Visual Studio Code 中 Python上的 VS Code 文档并没有告诉您安装它。 As long as you select the correct Python environment , which you can check from the status bar at the bottom, you can just click on the green play button or use "Run Python File in Terminal", and it should use the correct version.只要你select 正确的 Python 环境,你可以从底部的状态栏检查,你只需点击绿色的播放按钮或使用“在终端中运行 ZA7F5F35426B9274117FC9231B563”,它应该是正确的版本。

与代码

It's the reason why Method 2 ran successfully.这就是方法2成功运行的原因。

Method 3: From Terminal方法3:从终端

I am using... with Python 3.7.4 64-bit on MacOS Mojave 10.14.6.我在 MacOS Mojave 10.14.6 上使用...与 Python 3.7.4 64 位。

Mac OS comes with Python 2.7 as a built-in, and it is the one used when you use python : Mac OS 内置了 Python 2.7,它是您使用python时使用的一个:

Q$ python -V
Python 2.7.16

Q$ python test.py
  File "test.py", line 2
    x = f"There are {types_of_people} types of people."
                                                      ^
SyntaxError: invalid syntax

You need to use python3 or whichever is the correct interpreter depending on you how installed Python 3.x.您需要使用python3或任何正确的解释器,具体取决于您如何安装 Python 3.x。 If you are Homebrew's Python 3.x :如果您是Homebrew 的 Python 3.x

The executables are organised as follows:可执行文件的组织如下:

  • python3 points to Homebrew's Python 3.x (if installed) python3指向 Homebrew 的 Python 3.x(如果已安装)
  • pip3 points to Homebrew's Python 3.x's pip (if installed) pip3指向 Homebrew 的 Python 3.x 的 pip(如果已安装)

If you have multiple versions, it's a good idea to alias them:如果您有多个版本,最好给它们起别名:

Q$ alias python3.7=/usr/local/opt/python@3.7/bin/python3
Q$ alias python3.8=/usr/local/opt/python@3.8/bin/python3
Q$ alias python3.9=/usr/local/opt/python@3.9/bin/python3

Q$ python3.7 -V
Python 3.7.9
Q$ python3.8 -V
Python 3.8.6
Q$ python3.9 -V
Python 3.9.1

Q$ python3.7 test.py
There are 10 types of people.
Q$ python3.8 test.py
There are 10 types of people.
Q$ python3.9 test.py
There are 10 types of people.

Using virtual environments is also a best practice approach:使用虚拟环境也是一种最佳实践方法:

Q$ python3.8 -m venv myvenv
Q$ source ./myvenv/bin/activate
(myvenv) Q$ python -V
Python 3.8.6
(myvenv) Q$ python test.py
There are 10 types of people.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Visual Studio Code编写Python代码时,为什么会收到2条错误消息? - Why do I get 2 error messages when writing Python code using Visual Studio Code? 在 Visual Studio Code 中运行 python 脚本; 如何让 `input ()` 工作? - Running python script in Visual Studio Code; how to get `input ()` to work? 运行python时如何简化visual studio代码中的输出路径 - How do I simplify the outputed path in visual studio code when running python 如何获取 Python 脚本以在 Adobe Illustrator 和 Visual Studio Code 中绘制简单的线条 - How do I get Python Script to draw a simple line in Adobe Illustrator and Visual Studio Code (Visual Studio代码上的Python)SyntaxError:语法无效 - (Python on Visual Studio Code) SyntaxError: invalid syntax 为什么在 MacOS 上运行 python 脚本时出现 MKL 错误 - Why do I get an MKL error when running my python script on MacOS Visual Studio Code 终端在 Powershell 中继续运行 Python 脚本 - Visual Studio Code Terminal keeps running Python script in Powershell Python计划脚本在IDLE中运行,但不在Visual Studio Code中运行 - Python schedule script running in IDLE but not in Visual Studio Code 为什么在 Python 中使用 `match` 时出现“SyntaxError: invalid syntax”? - Why do I get "SyntaxError: invalid syntax" when using `match` in Python? Python EXE 文件:为什么运行时出现 ImportError 错误? - Python EXE file: Why do I get an ImportError when running it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM