API · Python

Python os.execl() Method

The os.execl() is an in-built Python function used to execute a program or a function.

On this page

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.