WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Python · Intermediate · question 37 of 100

How do you use Python’s os and sys modules to interact with the operating system?

📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Python interview — then scores it.
📞 Practice Python — free 15 min
📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

All 100 Python questions · All topics