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

被刻印的时光 ゝ 提交于 2021-02-10 06:32:29

问题


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?


回答1:


"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().



来源:https://stackoverflow.com/questions/61171536/why-am-i-getting-an-execvfile-args-error-when-using-execl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!