#python #programming #question #advanced #osoperations
Write a Python program that demonstrates advanced operating system interactions with the following requirements:
1. List all files and directories in the current directory with detailed information (size, modification time).
2. Create a new directory and move a file into it.
3. Execute a system command to list processes and capture its output.
4. Get the current user's home directory and environment variables.
5. Check if a process is running by name.
6. Set and get environment variables.
7. Create a temporary file and clean it up after use.
By: @DataScienceQ 🚀
Write a Python program that demonstrates advanced operating system interactions with the following requirements:
1. List all files and directories in the current directory with detailed information (size, modification time).
2. Create a new directory and move a file into it.
3. Execute a system command to list processes and capture its output.
4. Get the current user's home directory and environment variables.
5. Check if a process is running by name.
6. Set and get environment variables.
7. Create a temporary file and clean it up after use.
import os
import subprocess
import shutil
import tempfile
import psutil
from pathlib import Path
import sys
# 1. List files and directories with detailed information
def list_directory_details():
print("Directory contents with details:")
for entry in os.scandir('.'):
try:
stat = entry.stat()
print(f"{entry.name:<20} {stat.st_size:>8} bytes, "
f"modified: {stat.st_mtime}")
except Exception as e:
print(f"{entry.name}: Error - {e}")
# 2. Create directory and move file
def create_and_move_file():
# Create new directory
new_dir = "test_directory"
os.makedirs(new_dir, exist_ok=True)
# Create a test file
test_file = "test_file.txt"
with open(test_file, 'w') as f:
f.write("This is a test file.")
# Move file to new directory
destination = os.path.join(new_dir, test_file)
shutil.move(test_file, destination)
print(f"Moved {test_file} to {destination}")
# 3. Execute system command and capture output
def execute_system_command():
# List processes using ps command
result = subprocess.run(['ps', '-eo', 'pid,comm'],
capture_output=True, text=True)
print("\nRunning processes:")
print(result.stdout)
# 4. Get user information
def get_user_info():
print(f"\nCurrent user: {os.getlogin()}")
print(f"Home directory: {os.path.expanduser('~')}")
print(f"Current working directory: {os.getcwd()}")
# 5. Check if process is running
def check_process_running(process_name):
for proc in psutil.process_iter(['name']):
try:
if process_name.lower() in proc.info['name'].lower():
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return False
# 6. Environment variables
def manage_environment_variables():
# Get environment variables
print(f"\nPATH variable: {os.environ.get('PATH')}")
print(f"HOME variable: {os.environ.get('HOME')}")
# Set a new environment variable
os.environ['TEST_VAR'] = 'Hello from Python'
print(f"Set TEST_VAR: {os.environ.get('TEST_VAR')}")
# 7. Temporary files
def use_temporary_files():
# Create temporary file
with tempfile.NamedTemporaryFile(delete=False) as temp:
temp.write(b"This is a temporary file.")
temp_path = temp.name
print(f"Created temporary file: {temp_path}")
# Clean up
os.unlink(temp_path)
print("Temporary file deleted.")
# Main function to demonstrate all techniques
def main():
print("=== Operating System Operations Demo ===\n")
# 1. List directory details
list_directory_details()
# 2. Create directory and move file
create_and_move_file()
# 3. Execute system command
execute_system_command()
# 4. Get user info
get_user_info()
# 5. Check if process is running
print(f"\nIs Python running? {check_process_running('python')}")
# 6. Manage environment variables
manage_environment_variables()
# 7. Use temporary files
use_temporary_files()
print("\nAll operations completed successfully.")
if __name__ == "__main__":
main()
By: @DataScienceQ 🚀
👍2