Running Python Scripts from a Command Line

There are many ways to run Python code. Many learners begin with IDLE which comes bundled with the standard Python installation. You can go a long way with IDLE but eventually you will want to progress onto different environments.

A very common setup for small Python projects is the use of a text editor such as Notepad++ or Sublime Text, along with a command-line interface such as cmd, PowerShell or Bash.

In the linked video, I discuss various ways to run Python from a command line. I am using Windows 10 and Notepad++, but the process is very similar for other text editors and on Mac/Linux. Towards the end of the video I go into some specifics about setting up Notepd++ to run python scrips with a keyboard shortcut.

Advantages of running Python from a command line

As you become more familiar with running scripts from a command line, the advantages tend to reveal themselves. Here’s a few to start with:

  • It’s fast
  • It’s lightweight
  • You get access to console functionality such as clearing the screen or using colored fonts
  • You can pass arguments to you scripts
  • You can easily redirect output to other files

How to run Python scrips from the command line

The basic process for running Python scripts from the command line is similar regardless of the platform and terminal/editor you are using.

  • Open a command-line shell like cmd, PowerShell or Bash.
  • Navigate to the directory where your script is.
  • Type python followed by the script name. (python3 on Mac/Linux)
  • Hit Enter

and assuming you have python in your path, your script will run.

Check out these beginner Python books on Amazon

As an Amazon Associate I earn from qualifying purchases.

An example of running Python from a command line:

Here’s a script:

# hello.py

print("Hello World!")

Navigate to the containing folder and run the following from a command line:

python hello.py

>>>Hello World!

Finally here’s the command to open PowerShell and run the current python script from Notepad++:

powershell -noexit cd '$(CURRENT_DIRECTORY)'; python -i '$(FILE_NAME)'

I hope you enjoy running your Python scripts from a command line. Please feel free to comment below.

Sharing is caring!

Leave a Reply

Your email address will not be published. Required fields are marked *