Run line in Python terminal not working after Run file in terminal. Visual Studio Code

Question:

I just started using VSC. I have created a .py file with the line print('Hola mundo'). When I run the line (Mayus+Intro in Linux at least), it works fine.

>>> print('Hola mundo') Hola mundo

But then I try to Run the file (with the play button), and this errors raises:

>>> /home/tidop/anaconda3/envs/snappy/bin/python /home/tidop/Documentos/vs_folder/Hello_World.py
  File "<stdin>", line 1
    /home/tidop/anaconda3/envs/snappy/bin/python /home/tidop/Documentos/vs_folder/Hello_World.py
    ^
SyntaxError: invalid syntax

I have enter exit() in that terminal, so a normal linux terminal is used now. Here, I use the Run file button without problems.

(snappy) tidop@tidop-System-Product-Name:~/Documentos/vs_folder$ /home/tidop/anaconda3/envs/snappy/bin/python /home/tidop/Documentos/vs_folder/Hello_World.py Hola mundo

But now I can’t run just a line in here, cause it causes a bash error.

Question: How can I run indifferently lines and files in VSC?

I use Spyder and this problem does not exist…

Asked By: geofisue

||

Answers:

EDIT:

This comment under the answer addresses the OP’s question.

If you mean directly run a line or lines in the script file instead of typing code in the terminal. Right mouse button –> Run Selection/Line in Interactive Window, this opens an interactive window to run the selected portion of code. Here is a GIF. As you can see, there is a conflict between the shortcut keys. If you want to use shortcut keys, please delete other commands bound by Shift + Enter first, or change new shortcut keys for Run Selection/Line in Interactive Window.


You need to distinguish two concepts: the system terminal and the python interactive terminal.

The integrated terminal in vscode uses the system terminal. When you type python or py in the terminal, this is a command that will make the system terminal open the python interactive terminal.

enter image description here

In the python interactive terminal, you can directly type python code and run it.

enter image description here

But if you type a system command, such as C:/Users/Admin/AppData/Local/Programs/Python/Python310/python.exe c:/WorkSpace/pytest11/demo4.py, which is the command for vscode to run the python script (that is, the command for you to click the play button to run the code), then the python interactive terminal will report an error. Since this is not python code it tells you syntax error.

enter image description here

If you want to use both at the same time, you just need to open both integrated terminals at the same time.

enter image description here

Answered By: JialeDu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.