Execute a Command Prompt Command from Python

Two methods to execute a Command Prompt command from Python:

(1) CMD /K – execute a command and then remain:

import os

os.system('cmd /k "Your Command Prompt Command"')

(2) CMD /C – execute a command and then terminate:

import os

os.system('cmd /c "Your Command Prompt Command"')

2 Methods to Execute a Command Prompt Command from Python

Method 1 (CMD /K): Execute a command and then remain

Let’s review a simple example where we’ll execute a simple command in Python to:

  • Display the current date in the Command Prompt
  • The Command Prompt will remain open following the execution of the command

You may then apply the following code in Python to achieve the above goals:

import os

os.system('cmd /k "date"') 

Once you run the code in Python, you’ll get the date in the command prompt:

The current date is: Sat 03/23/2024

Now what if you want to execute multiple command prompt commands from Python?

If that’s the case, you can insert the ‘&‘ symbol (or other symbols, such as ‘&&‘ for instance) in between the commands.

For example, what if you want to display all the characters in the command prompt in green and display the current date?

You can then use the following syntax in Python:

import os

os.system('cmd /k "color a & date"')

You’ll now see the current date displayed in green:

'The current date is: Sat 03/23/2024'

Note that for more complex commands, you may find it useful to run a batch file from Python.

Method 2 (CMD /C): Execute a command and then terminate

For this method, you can execute the same commands as reviewed under the first method, only this time the Command Prompt will be closed following the execution of the commands.

For example, you may apply the following code in Python to change the color of all characters to green:

import os

os.system('cmd /c "color a"')

In this case, the command will still get executed, but you may not be able to see it on your monitor.

In general, you can get a useful legend with further information by typing the command below in the Command Prompt:

cmd /?