Discover 15 advanced Python commands for interacting with the operating system to automate tasks and boost office productivity. Learn how to execute system commands, manage files, monitor changes, and schedule tasks effectively.
In an office environment, Python's power goes beyond data processing and analysis. It can also interact deeply with the operating system to automate tasks, significantly improving work efficiency. This article will guide you through 15 advanced commands in Python used for operating system interaction, helping you master these techniques with practical examples.
1. Using the os
module to execute system commands
The os
module provides many functions for interacting with the operating system, such as executing system commands.
import os # Execute system command result = os.system('ls -l') print(f'Command result: {result}')
2. Advanced command execution with the subprocess
module
The subprocess
module offers more flexible and powerful functionality for executing commands.
import subprocess # Execute command and get output result = subprocess.run(['ls', '-l'], capture_output=True, text=True) print(f'Command output: {result.stdout}')
3. File operations with the shutil
module
The shutil
module provides advanced functions for file operations, such as copying, moving, and deleting files.
import shutil # Copy file shutil.copy('source.txt', 'destination.txt')
4. Traversing directory trees
You can use os.walk
to traverse a directory tree.
import os for root, dirs, files in os.walk('/path/to/directory'): print(f'Root: {root}, Directories: {dirs}, Files: {files}')
5. File matching with the glob
module
The glob
module makes it easy to match file path patterns.
import glob # Match all .txt files for filename in glob.glob('*.txt'): print(filename)
6. Creating temporary files with the tempfile
module
The tempfile
module is used to create temporary files and directories.
import tempfile # Create temporary file with tempfile.NamedTemporaryFile(delete=False) as temp_file: temp_file.write(b'Hello, world!') print(f'Temp file created: {temp_file.name}')
7. Modern path operations with the pathlib
module
The pathlib
module provides object-oriented file system path operations.
from pathlib import Path # Create path object path = Path('/path/to/directory') # Get directory contents for file in path.iterdir(): print(file)
8. System information with the platform
module
The platform
module can be used to retrieve operating system information.
import platform print(f'System: {platform.system()}') print(f'Node Name: {platform.node()}') print(f'Release: {platform.release()}')
9. Monitoring system resources with the psutil
library
psutil
is a cross-platform library for retrieving system process and resource utilization information.
import psutil # Get CPU usage print(f'CPU Usage: {psutil.cpu_percent()}%')
10. Monitoring file system changes with the watchdog
library
The watchdog
library allows you to monitor file system changes, such as file creation, modification, and deletion.
from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler import time class MyHandler(FileSystemEventHandler): def on_modified(self, event): print(f'File {event.src_path} has been modified') # Create event handler and observer event_handler = MyHandler() observer = Observer() observer.schedule(event_handler, path='', recursive=False) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
11. SSH connection with the paramiko
library
The paramiko
library is used to connect to remote servers via SSH.
import paramiko # Create SSH client ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('hostname', username='username', password='password') # Execute command stdin, stdout, stderr = ssh.exec_command('ls -l') print(stdout.read().decode()) # Close connection ssh.close()
12. Simplifying SSH tasks with the fabric
library
fabric
is a Python library that simplifies the execution of SSH tasks.
from fabric import Connection c = Connection('hostname', user='username', connect_kwargs={'password': 'password'}) result = c.run('ls -l') print(result.stdout)
13. Handling cron expressions with the croniter
library
The croniter
library is used to parse and iterate over cron expressions.
from croniter import croniter from datetime import datetime cron = croniter('*/5 * * * *', datetime.now()) for _ in range(5): print(cron.get_next(datetime))
14. Scheduling tasks with the schedule
library
The schedule
library is used to schedule periodic tasks.
import schedule import time def job(): print('Job executed') # Schedule task to run every minute schedule.every(1).minutes.do(job) while True: schedule.run_pending() time.sleep(1)
15. Advanced task scheduling with the APScheduler
library
APScheduler is a powerful task scheduling library.
from apscheduler.schedulers.background import BackgroundScheduler import time def my_job(): print('Job executed') scheduler = BackgroundScheduler() scheduler.add_job(my_job, 'interval', seconds=5) scheduler.start() try: while True: time.sleep(2) except (KeyboardInterrupt, SystemExit): scheduler.shutdown()
Practical Case: Automatic Backup Script
Suppose you need to back up a directory to another location on a schedule. You can use shutil
and schedule
libraries to implement this.
import shutil import schedule import time from datetime import datetime def backup(source, destination): shutil.copytree(source, destination + '/' + datetime.now().strftime('%Y%m%d_%H%M%S')) print(f'Backup completed at {datetime.now()}') # Schedule backup task to run at 1 AM every day schedule.every().day.at('01:00').do(backup, '/path/to/source', '/path/to/destination') while True: schedule.run_pending() time.sleep(1)
In this script, shutil.copytree
is used to copy the entire directory tree, and schedule.every().day.at('01:00')
schedules the task to run at 1 AM every day. This way, you can automate the backup of important data without manual intervention.
Conclusion
In this article, we explored 15 advanced Python commands for interacting with the operating system, including executing system commands, file operations, monitoring file system changes, SSH connections, and task scheduling. These commands and libraries will help you automate office tasks and improve work efficiency.