Skip to content

How to run Python in terminal?

  • by
  • 3 min read

Python is one of the easiest programming languages to pick up and learn. All you need is some basic knowledge of syntax and a text editor to work with. 

There’s no need to install big, heavy IDEs or compilers or anything like that. If you’re on a Linux based system, chances are you probably already have Python installed, and all it takes to run a script is one command.

In this article, we’re going over how you can execute Python scripts in the terminal. 

Also read: How to create a list in Python?


Running Python scripts in the terminal on Linux/macOS

If you’re on a Linux or macOS system, there’s no need to set any file paths or do any other configurations. Once you’ve installed Python on your machine, and chances are it’s already there, all you have to do is navigate to the directory where you’ve saved your script and type python followed by the script name. 

For example, if you’re trying to run a script named test.py in the Linux home directory, you’d type the following command.

python test.py

If you’ve got Python 2 and Python 3 installed on your machine simultaneously, you can run the script in either version by using these commands.

For Python 3:

python3 test.py

For Python 2:

python2 test.py

Providing command-line arguments

If your script requires command-line arguments, you can type them after the script’s name as follows.

python test.py arguement1 arg2 arg3

Redirecting script outputs to a separate file

Generally, when you run a script in the terminal, the output is printed onto the terminal itself. However, if you’d like, you can redirect or pipe the script’s output to a particular file using the following command. 

python test.py > output.txt

This will create a text file named output that will contain whatever it is that your script outputted. 

Also read: How to use the Python range() function?


Running Python scripts in the Windows Command Prompt

If you’re programming on Windows, you can still run Python scripts in the command prompt provided you’ve set the environment variables correctly during installation. 

Usually, the Python installer will do it for you. However, you can always check this by typing python in the command prompt and checking for any errors. You can run python scripts on recent versions of Windows by simply mentioning the file name.

test.py

Also read: How to concatenate strings in Python?

Yadullah Abidi

Yadullah Abidi

Yadullah is a Computer Science graduate who writes/edits/shoots/codes all things cybersecurity, gaming, and tech hardware. When he's not, he streams himself racing virtual cars. He's been writing and reporting on tech and cybersecurity with websites like Candid.Technology and MakeUseOf since 2018. You can contact him here: yadullahabidi@pm.me.

>