In this article let's learn how to write a python script to run an operating system command line. Given the operating system Linux or Windows operating system, Python can execute on both the operating system types, let's use python script to execute the operating system command line.
Write A Python Script To Run Command Line
Let's import the required libraries to execute the operating system comment. We require the operating system (os) module present in the python library to execute the command.
import os
Take a new string variable named cmd, ask the user to enter the command using the input function call. take another variable named as op to store the result of the Executed command. use the os.system function call and provide the user entered combined as an input argument to the system function.
Once the command gets executed use the print statement to print the result/ return code of the command.
cmd = input("Enter Command : ")
op = os.system(cmd)
print("Return Status is : ", op)
Python Code Works on Both Windows and LINUX operating System
==================================
import os
cmd = input("Enter Command : ")
op = os.system(cmd)
print("Return Status is : ", op)
Output
====================
Enter Command : ls -l
Return Status is : 1
'ls' is not recognized as an internal or external command,
operable program or batch file.
Output
===============
Enter Command : dir
Volume in drive C is Windows
Volume Serial Number is CA91-5619
Directory of C:\Users\Public\Projects\vlogs
22-01-2023 17:34 <DIR> .
22-01-2023 17:34 <DIR> ..
22-01-2023 17:30 <DIR> .idea
07-01-2023 22:51 5,114 Iris.csv
22-01-2023 17:34 158 main.py
01-01-2023 22:38 <DIR> venv
2 File(s) 5,272 bytes
4 Dir(s) 368,666,619,904 bytes free
Return Status is : 0
Conclusion
=================
Execute the above python script both on Windows and LINUX operating systems, provide the different set of commands and note down the results.
Comment it down below if you have any suggestions to improve the above python program .
0 Comments