The os and sys modules in Python provide a way to interact with the operating system and perform various system-level operations, such as working with files and directories, managing processes, and accessing environment variables.
Here are some examples of how to use the os and sys modules in Python:
Working with files and directories
import os
# get the current working directory
cwd = os.getcwd()
print(cwd)
# create a new directory
os.mkdir('new_dir')
# rename a file or directory
os.rename('old_file.txt', 'new_file.txt')
# remove a file or directory
os.remove('file.txt')
os.rmdir('empty_dir')
os.rmtree('nonempty_dir')
Managing processes
import os
import sys
# get the process ID of the current process
pid = os.getpid()
print(pid)
# fork a new process
if sys.platform == 'linux':
child_pid = os.fork()
if child_pid == 0:
# this is the child process
print('Child process')
else:
# this is the parent process
print('Parent process')
else:
print('fork is not supported on this platform')
Accessing environment variables python Copy code import os
# get the value of an environment variable path = os.environ[’PATH’] print(path)
# set the value of an environment variable os.environ[’MY_VAR’] = ’my_value’
# unset an environment variable os.environ.pop(’MY_VAR’, None)
In summary, the os and sys modules in Python provide a way to interact with the operating system and perform various system-level operations. The os module provides functions for working with files and directories, managing processes, and accessing environment variables. The sys module provides access to system-specific parameters and functions, such as the command line arguments and the standard input and output streams. These modules are useful for developing cross-platform applications and performing system-level tasks in Python.