Execute a Command Prompt Command from Python

Need to execute a Command Prompt command from Python?

If so, depending on your needs, you may use either of the two methods below to a 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"')

Still not sure how to apply the above methods in Python?

Let’s then review few examples to better understand how to execute a Command Prompt command from Python.

Methods to Execute a Command Prompt Command from Python

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

To see how to apply the first method in practice, 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 opened 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: Fri 06/25/2021
Enter the new date: (mm-dd-yy)

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: Fri 06/25/2021
Enter the new date: (mm-dd-yy)

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 /?