Teban
Teban

Reputation: 11

How to run a Python file in Visual Studio code from the terminal?

I have tried to run a pretty simple code

x = input("What's x? ")
y = input("What's y? ")

z= int(x) + int(y)

print (z)

But, when I try to run that code from the terminal writing "name_of_the_file.py", I find this error:

"The term "name_of_the_file.py" 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."

If a right click on where you write the code, and then click on "run python file in terminal", it runs!

I am taking the CS50P, and I see that this should be possible because the teacher is able to do that. What am I doing wrong guys?

Upvotes: 1

Views: 35187

Answers (5)

Bibin
Bibin

Reputation: 419

Use python filename.py.

This command should work.

If you're utilizing Python 3 and have both Python 2 and Python 3 installed on your system, you may need to use python3 instead of merely python:

python3 filename.py

Upvotes: 0

Pasha Abdul Khalid
Pasha Abdul Khalid

Reputation: 21

try this one:

  1. open terminal in vscode.

  2. check the directory in terminal, it must be same path to where you file is saved.

  3. run command in terminal :

    python3 name_of_the_file.py

Upvotes: 0

JialeDu
JialeDu

Reputation: 9915

Click the play button to run the code, watch the terminal and you can see that it is using the command & c:/WorkSpace/pytest11/.venv/Scripts/python.exe c:/WorkSpace/pytest11/main.py to run the code.

enter image description here

So if you need to manually type commands in the terminal to run the code. You can directly copy the above command.

If you use a virtual environment or have system environment variables configured, you can simplify the python path with the following command

python main.py

PS: main.py is my script file name, you need to modify it to your own file name.

enter image description here

Upvotes: 3

J.p
J.p

Reputation: 140

Do follow below steps

  1. Open terminal in VS code

  2. go to directory where you have .py file located using cd command

  3. run command in terminal (eg. python3 file_name.py

    Me@MyMacBook-Air string % python3 str_to_int.py

Hope this helps

Upvotes: 1

Andrea S.
Andrea S.

Reputation: 71

try to follow these steps:

  1. Create a folder where you want your script to run
  2. Open the folder using VS Code: File -> Open Folder
  3. Create your script and save it in the folder
  4. Open a new terminal: Terminal -> New Terminal
  5. Type the command: python name_of_the_file.py
  6. If it doesn't work, try: py name_of_the_file.py
  7. If you are using a python 3 version, try: python3 name_of_the_file.py

My output:

enter image description here

Upvotes: 0

Related Questions