3
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 
2
  • 1
    execl doesn't do path lookup. Commented Mar 11, 2020 at 17:57
  • Unless this is just a simplified example, use subprocess instead if you are forking just to call execl in the child process. Commented Mar 11, 2020 at 17:59

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.