问题
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 usedexecl()
?
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