I'm having trouble running os.execl() with python 3

Viewed 609
import os
import sys

pid = os.fork()
print ("second test")
if pid == 0:
    print ("this is the child")
    print ("I'm going to exec another program now")
    os.execl("python", "test.py", * sys.argv)
else:
    print ("the child is pid %d" % pid)
    os.wait()

I've looked everywhere at examples, but for the life of me, I just can't understand it whatsoever. I thought this would work, but I get this error:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    os.execl("python", "test.py", * sys.argv)
  File "/usr/local/lib/python3.8/os.py", line 534, in execl
    execv(file, args)
FileNotFoundError: [Errno 2] No such file or directory
1 Answers

The first argument to os.execl() should be the path to the executable that you want to run. It won't search for it using $PATH.

You also need to repeat the name of the program as arg0.

os.execl('/usr/local/bin/python', 'python', "test.py", *sys.argv)

You can use os.execlp() to use $PATH to find the program automatically.

os.execlp('python', 'python', "test.py", *sys.argv)

BTW, sys.argv[0] will be the name of the original Python script. You might want to remove that when passing arguments along to another script, so you would use *sys.argv[1:].

And of course, most people use the subprocess module to execute other programs, rather than using fork and exec directly. This provides higher level abstractions to implement I/O redirection, waiting for the child process, etc.

Related