- Execute Shell Command and Get Output in Python
- Execute CMD Commands From a Python Script and Get Output Using os.system()
- Execute CMD Commands From a Python Script and Get Output Using the Subprocess Module
- 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
- Method 2 (CMD /C): Execute a command and then terminate
Execute Shell Command and Get Output in Python
- Execute CMD Commands From a Python Script and Get Output Using os.system()
- Execute CMD Commands From a Python Script and Get Output Using the Subprocess Module
In this article, we will learn how to execute cmd commands from a Python script with the help of os.system() . We will also learn how we can execute cmd commands from the script in an easier way with the help of the subprocess module in Python.
Execute CMD Commands From a Python Script and Get Output Using os.system()
We execute terminal commands in command prompt or any other terminal for different purposes. But, sometimes, running a particular command inside the script is necessary.
We will see how we can execute them directly inside the Python script. It is handy when we work with server configuration.
First, let us show you some commands that work in the terminal, such as dir , cd , or md .
Now, we will see how we can include the same ones in the Python script. To do that, we will import a module called os .
The os module will help us to interact with our operating system. The os module has extensive support for operating system tasks such as files and folder management.
Let’s jump into the code. The system() is a method that executes the command in the like shell, so if we give it any command, it will go ahead and execute them the way we would execute them in the terminal.
The system function can also execute a bunch of commands. It executes every command that you can run in the terminal.
We will use the try block, and inside this block, we will use the system() method, which will help us to interact with the operating system using the terminal. If the try block does not execute the specified command, we will go onto the except block.
Inside the system() method, we have to pass our commands, but the command type is cmd . For that, we use /k , and inside a single or double quotation, we have to type our command.
import os try: os.system('cmd /k "date"') except: print('Could not execute command')
Let’s run and see whether this gives us the exact output.
The current date is: 24/08/2022 Enter the new date: (dd-mm-yy)
We can see the output is the same as the command prompt gives.
There are lots of commands you can execute. You can open Notepad or Calculator, or you can see your system information and much more.
If you want to get the content of what the command returns, you can get it using the popen() function of the os module. Inside this function, we can pass the command and use the readlines() method to get its content.
We can use many methods to get clean data. It depends on you.
import os DATA=os.popen('help').readlines()[5].strip('\n') print(DATA)
We can use these commands anywhere, like class, loops, and function. This will properly work as it does without wrapping it in a function.
import os def CMD_Com(): DATA=os.popen('help').readlines()[5].strip('\n') print(DATA) CMD_Com()
CACLS Displays or modifies access control lists (ACLs) of files.
Execute CMD Commands From a Python Script and Get Output Using the Subprocess Module
Interacting with subprocesses is an essential skill to have. Using the os module is not recommended to execute a terminal command inside the Python script.
Using os.system() to execute the terminal command is a very simplified way of running a command in Python.
The os.system() has limited functionality; the proper way is to use a module called subprocess , which makes it not too challenging to execute terminal commands. Using the subprocess module, we can run all the operating system commands on which we are currently working.
This is how we can run all existing commands in an operating system, like opening Notepad or checking the current working directory, or any other operation we can execute using the subprocess module.
import subprocess # subprocess.Popen('notepad') # subprocess.Popen('systeminfo') subprocess.Popen("dir", shell=True)
Directory of C:\Users\Dell\Downloads\demo 24/08/2022 07:01 pm . 24/08/2022 07:01 pm .. 25/08/2022 01:47 am 460 demo.py 1 File(s) 460 bytes 2 Dir(s) 32,532,512,768 bytes free
You can learn more about the subprocess module from here.
Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.
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:
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:
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: