Home » Programming » Python » Python Os

The Python ‘os’ Library – What it is and How it’s Used

This article will give a short overview of the Python os (Operating System) module – and show some examples of how it is used.

What is the Python ‘os’ Library/Module?

The Python os library contains helpful tools and functions for interacting with the underlying Operating System being used to execute the running Python code.

It can be used to query information about the system environment – including operating system, disk space, memory information, and which path Python is being executed from.

The information available will differ depending on which operating system Python is running on.

The os library also includes the functions for reading and writing to files on the file system and navigating to different files and folders on disk.

THe os library also includes tools for starting and managing external processes – that is calling another program from within Python and working with the resulting output.

Using the Python ‘os’ Module

There are a lot of functions available in the Python os module. Some are incredibly useful, some less so.

I’ll stick to the most useful ones and provide some code examples of how they can be used.

Python ‘os’ Function Examples

The below examples show some of the commonly used os functions.

Before any of them can be used, make sure you import the os library by including the following at the top of your Python script:

import os

Process Parameters

os.environ

Syntax:

os.environ[KEY]

os.environ is an object which contains information about the system environment as key:value pairs. The below example will return the path to the HOME directory on supported platforms:

os.environ['HOME']

Environment variables can also be set from this object:

os.environ['FOO'] = 'BAR'

os.fspath()

Syntax:

os.fspath(PATH)

os.fspath() returns the string representation of a given path object. In the below example, the path object returned by os.cwd() is converted to a string:

os.fspath(os.cwd())

os.getenv()

Syntax:

os.getenv(KEY)

Similar to os.environ, but rather than an object containing environment information, this function retrieves the values:

os.getenv('HOME')

os.getlogin()

Syntax:

os.getlogin()

Returns the name of the system user executing the Python script.

os.getpid()

Syntax:

os.getpid()

Returns the Process ID of the current Python process.

os.putenv(key, value)

Syntax:

os.putenv(KEY, VAL)

Sets an environmental variable which can be read by os.getenv() or retrieved via os.environ.

os.unsetenv()

Syntax:

os.unsetenv(KEY)

Unsets/deletes an environmental variable.

os.uname()

Syntax:

os.uname()

Returns an object with the following system information as attributes:

  • sysname – operating system name
  • nodename – name of machine on network (implementation-defined)
  • release – operating system release
  • version – operating system version
  • machine – hardware identifier

File Descriptors & Operations

While the os library supports as number of file operations, most of them are focussed on low-level manipulation of the files and attributes.

For those just getting started I recommend using the open() function and the resulting file objects for file manipulation.

Terminal Information

If you’re building a command line app, you can use:

os.get_terminal_size()

… to get the column and line count of the terminal window Python is running in.

Checking File/Directory Permissions

We’ve got a whole article on using the os library to check file permissions here.

Changing the Current Working Directory with os.chdir()

Syntax:

?os.chdir(PATH)

Checking the Current Working Directory with os.getcwd()

Syntax:

os.getcwd()

Process Management

Exiting with os._exit()

Syntax:

os._exit(STATUS)

Exit the Python process with STATUS. Does not call cleanup handlers, flush STDIO buffers, etc.

Aborting with os.abort()

Syntax:

os.abort()

Immediately aborts the process with a SIGABRT signal. Will generate a core dump unless running on Windows where an exit code of 3 will be given.

Generating Random Numbers and Strings

The os library can be used to generate cryptographically safe random numbers and strings.

Generate Random Number

Syntax:

os.getrandom(SIZE)

Generates a random number up to a given SIZE of bytes. The number returned can be smaller in SIZE than requested.

Generate Random String

Syntax:

os.urandom(SIZE)

Generate a random string of bytes with length SIZE.

More Stuff!

I’ve only covered some basic usage in this article. The Python documentation for the os library is well structured and contains information about all of the available functions.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment