How to Execute Python Shell Commands

5/5 - (15 votes)

This article shows you how to execute Python commands in the Shell.

ℹī¸ The Shell is known as a command-line interface because it interacts with the Operating System. In Windows, it is referred to as the Command Prompt. In Linux, the Terminal.


Let’s start learning how to use the Shell!

  1. Access the Shell
  2. Close the Shell
  3. Enter and Run Python Commands from the Shell
  4. Run a .bat File from the Shell using subprocess
  5. Execute Python Scripts using os.system()

Access the Shell

This section shows you how to access the Shell using the VSC IDE.

Open the VSC IDE. Then, navigate to View → Terminal, or use the key combination (CTRL+J).

Either of the above actions opens a Terminal window.

To start the Shell, type python at the prompt (similar to below) and press the <Enter> key.

The above action displays the command prompt (>>>).


Close the Python Shell

This section touches on various ways to close the Shell and terminate code execution.

Below outlines the four (4) available options to perform the above task:

  1. At the command prompt (>>>), enter the key combination CTRL+Z and press the <Enter> key. To terminate code execution, this is the best option.
  2. At the command prompt (>>>),, enter exit() and press the <Enter> key.
  3. At the command prompt (>>>), enter quit() and press the <Enter> key.
  4. In the terminal window, click the delete (trashcan) icon on the right-hand side.

Your IDE options may differ slightly.

💡 Note: To show/hide the Shell, click the CTRL+J key combination.


Enter and Run Python Code from the Shell

This section shows how to run Python code directly from the Shell.

Example 1: Perform Mathematical Operations

Not only can you run Python code, but you can also perform mathematical operations. From the command prompt (>>>), enter 5+7. Press the <Enter> key to execute.

If successful, 7 is output to the terminal window.


Example 2: Print a String

This example executes Python’s print() statement. From the command prompt (>>>), enter print('The Finxter Academy'). Press the <Enter> key to execute.

If successful, the string inside the print() statement is output to the terminal window.


Example 3: Iterate and Output Dictionary Keys

For this example, we have a Dictionary of employees saved to the variable staff. This code, when executed, outputs the key of each Dictionary entry to the terminal window.

To see this code in action, copy the code snippet below to the Windows clipboard. Navigate to the command prompt (>>>). Then right-mouse click to paste the code from the Windows clipboard to the terminal window.

staff = {'Amy': 55093, 'Joe': 44094, 'Sue': 3786}
for s in staff: 
   print(s)

In this example, the above action displays a pop-up box.

To prevent this pop-up from displaying, place a checkmark in the Do not show again checkbox. Click the Paste button to paste this code from the Windows clipboard to the terminal window.

Press the <Enter> key to execute.


Example 4: Determine Installed Library Version

This section outputs the currently installed version of the Pandas library to the terminal window. This library must be installed before running this code.

To see this code in action, copy the code snippet below to the Windows clipboard. Navigate to the command prompt (>>>). Right-mouse click to paste the code from the Windows clipboard to the terminal window.

import pandas
pandas.__version__

Press the <Enter> key to execute.

If successful, the currently installed version of the Pandas library is output to the terminal window.


Run a Batch (.bat) File from the Shell using subprocess()

This section shows how to execute a .bat script from the Shell using a subprocess.

For this example, a .bat (batch) file will be created and ran from the Shell.

First, create a Python file called counter.py. Copy and paste the contents of the code snippet below into this file and save it.

This code iterates through a while loop and outputs a string with the value of lift_off on each iteration and pauses for two (2) seconds. This continues until the value of lift_off is greater than zero (0).

from datetime import datetime
from time import sleep

lift_off = 5

while lift_off > 0:
    print (f'Lift Off in {lift_off} seconds!')
    sleep(2)
    lift_off -= 1

Next, create a file called counter.bat. Copy and paste the contents of the code snippet below into this file and save it. The first line hides any output (except for that in the counter.py file).

  • The first argument on the following line is the full path to python.exe.
  • The second argument is the full path to the .bat file.

Modify as needed.

@echo off
"C:\Python\python.exe" "C:\PYTHON_CODE\counter.py"

Next, navigate to the command prompt (>>>). Copy and paste the contents of the code snippet below to the terminal window. This snippet imports the subprocess library and passes the full path of the .bat file as an argument

import subprocess
subprocess.call([r'C:\\PYTHON_CODE\\P_TRAINING\\LEARN\\CHRIS\WORK\\counter.bat'])

ℹī¸ Python’s subprocess library runs applications by creating a process. This allows an application to execute by passing it as an argument, such as a .bat file or another application.

Press the <Enter> key to execute.

If successful, the following output displays.


Execute Commands using os

This section shows how to execute Python code using the os library.

To execute this code, navigate to the command prompt (>>>). Copy and paste the code snippet below into the terminal window.

This code imports the os library and calls the os.system() function. This calls and executes the counter.py file.

import os
os.system("python counter.py")

Press the <Enter> key to execute.

If successful, the following output displays.


Summary

This article has shown you how to work with the Shell in Python. To learn more about the Shell, click here.

Good Luck & Happy Coding!


Programming Humor

💡 Programming is 10% science, 20% ingenuity, and 70% getting the ingenuity to work with the science.

~~~

  • Question: Why do Java programmers wear glasses?
  • Answer: Because they cannot C# …!

Feel free to check out our blog article with more coding jokes. 😉