Andy
Andy

Reputation: 7

Why am I getting an "execv(file, args)" error when using execl()?

I am trying to use execl() to execute a new program but it keeps returning an execv() error saying that arg2 must not be empty.

if pid == 0:
    print("This is a child process")
    print("Using exec to another program")
    os.execl("example_prg_02.py")

Why would this be the case when using execl()? Does execl() require args too?

Upvotes: 1

Views: 887

Answers (1)

MarianD
MarianD

Reputation: 14141

"example_prg_02.py" is not a path to executable file, you have to specify

  • a path to executable file as a 1st parameter,
  • the name of executable as a 2nd one,
  • parameter(s) as 3rd (4th, 5th, ...)

So instead of your

os.execl("example_prg_02.py")

use

os.execl(sys.executable, "python", "example_prg_02.py")

(you have first import sys, of course).

sys.executable is the absolute path of the executable binary for the Python interpreter.


Addendum (from my comment):

Why error from execv(), when I used execl()?

Both execv() and execl() do the same thing, they differ in how command-line arguments are passed:

  • if the last letter is v (variable number of arguments), you have to provide a list or tuple for argv (i.e. arguments),

  • if the last letter is l (it probably means list them — for constant number of them), you have to provide argv as individual arguments.

execl() is only a “syntactical sugar” — it calls internally execv(), so you obtained the error from execv().

Upvotes: 2

Related Questions