Python os.execl() Method

Musfirah Waseem Jan 30, 2023
  1. Syntax of Python os.execl() Method
  2. Example 1: Use the os.execl() Method in Python
  3. Example 2: Understanding the os.execl() Method in Python
Python os.execl() Method

Python os.execl() method is an efficient way of causing the current process to be terminated and replaced by the program passed as the argument to the os.execl() method.

Syntax of Python os.execl() Method

os.execl(path, arg1, arg2...)

Parameters

path It is an address object of the first file system path or a symlink. The object can either be an str or bytes.
arg1 It is the argument of any process we want to execute.

Return

There is no return type for this method.

Example 1: Use the os.execl() Method in Python

import os

import sys

enter = input("Do you want to restart the current program? Enter 'y' for yes. ")

if enter == "y":
    print("The program has restarted.")

    os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)
else:
    print("The program has been closed.")

    sys.exit(0)

Output:

Do you want to restart the current program? Enter 'y' for yes. y
The program has restarted.
Do you want to restart the current program? Enter 'y' for yes. n
The program has been closed.

Note that Unix OS’s new executable function replaces the current process but will still have the same process id as the caller.

Example 2: Understanding the os.execl() Method in Python

import os

import sys

if len(sys.argv) >= 2 and sys.argv[1] == "exec":

    os.execl("/usr/rand/python", "key", sys.argv[0])

    print("The current process has been replaced.")
else:

    print("The current process has not been terminated.")

    print(sys.executable)

Output:

The current process has not been terminated.
/usr/bin/python3

The method os.execl() causes the new processes to inherit the environment of the currently running process.

Musfirah Waseem avatar Musfirah Waseem avatar

Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.

LinkedIn

Related Article - Python OS