![]() |
Using the Use Linux Command In Python Using os.systemBelow are examples of using Linux commands in Python using the os.system function. Table of Content Listing Files in a Directory Using System.Os in PythonThe below example uses the os.system function to execute the ‘ls‘ command, which is a Linux command for listing files in the current directory. When run, this script prints the names of files and directories present in the script’s working directory to the console, providing a quick way to view the contents of the current folder within a Python script. Python3
Output: file1.txt file2.txt directory1 directory2 Creating a New Directory Using System.Os in PythonThe below example le uses the os.system function to execute the ‘mkdir‘ command, which is a Linux command for creating directories. When run, this script creates a new directory, you can further use the ‘ls‘ command to see the created directory. Python3
Output: Checking Disk Space Using System.Os in PythonThe below example uses the os.system function to execute the ‘df -h‘ command. When run, this script will display details about the disk space on the partition where the root directory is located. Python3
Output: Pinging a host Using System.Os in PythonThe below example uses the os.system function to execute the ‘ping‘ command which is a Linux command used to test the reachability of a host. When run, this script will ping the specified host 4 times and display the round-trip time for each packet. Python3
Output: ConclusionIn conclusion, using the os.system function in Python enables seamless integration of Linux commands into scripts, providing a convenient way to automate diverse tasks. The presented examples showcase the versatility of this approach, from listing files and creating directories to checking disk space and pinging hosts. By incorporating Linux commands, Python scripts gain robust functionality for tasks involving file manipulation, system administration, and more. |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |