How to Run Python in Terminal

You can run any Python script in a command-line interface.
Ash Ash (362)
0

Python and associated Python scripts can be run using command-line interfaces. Windows users can use command prompt while Mac and Linux users can make use of Terminal. We'll cover how to run a Python script, open a Python shell, and how to run a Python one-liner.

Posted in these interests:
h/python67 guides
Command Prompt

Open Command Prompt. An easy way to reach Command Prompt is by opening the Start Menu and searching for cmd. Select Command Prompt from the list of applications.

How to run a Python script

By default, you will need to point Command Prompt to the Python installation location. Here's an example of what a command would look like when executing a Python script.

C:\Python27\python.exe C:\Users\YourUsernameHere\Desktop\script.py

If you don't want to type the full Python installation path, you can add an exception to your PATH environment variable for python.exe.

Using the Python shell

From the Command Prompt window, type python or python3 and press enter.

Python one-liners

This will as long as Python has been added to your PATH environment variable. Here's an example of a one-liner you can run from command prompt.

python -c "print('hello world')"

Mac users can run Python scripts using Terminal. Launch Terminal to begin.

There are two common ways to run a Python script from the command line. You can call the python program directly, and pass the name of the script to execute. Or you can make the script executable, and call it directly.

Run a script using python

Running a script using the python program is easy, and it's probably the method most people are familiar with. Simply call python and pass the name of your script, like this:

python myscript.py

# or 

python3 myscript.py

Making a Python script executable

If your Python script includes a “shebang” (#!/usr/bin/env python or #!/usr/bin/env python3). You can make your script executable, like this:

chmod +x myscript.py

and execute it like this:

./myscript.py

Using the Python shell

You can open a Python shell simply by typing python or python3 into a Terminal window. Then you can run Python commands directly in the shell.

Python one-liners

You can also execute Python directly on the cli using the -c option. Example:

python -c "print('hello world')"
Run Python scripts in command prompt without typing the whole path.
Ash Ash (362)
2 minutes

If you want to run Python scripts on the command prompt, you’ll need to type the full Python installation path every time.