Difference between os.execl() and os.execv() in python

点点圈 提交于 2019-11-30 16:43:30

At the low level they do the same thing: they replace the running process image with a new process.

The only difference between execv and execl is the way they take arguments. execv expects a single list of arguments (the first of which should be the name of the executable), while execl expects a variable list of arguments.

Thus, in essence, execv(file, *args) is exactly equivalent to execl(file, args).


Note that sys.argv[0] is already the script name. However, this is the script name as passed into Python, and may not be the actual script name that the program is running under. To be correct and safe, your argument list passed to exec* should be

['python', __file__] + sys.argv[1:]

I have just tested a restart script with the following:

os.execl(sys.executable, 'python', __file__, *sys.argv[1:])

and this works fine. Be sure you're not ignoring or silently catching any errors from execl - if it fails to execute, you'll end up "continuing where you left off".

According to the Python documentation there's no real functional difference between execv and execl:

The “l” and “v” variants of the exec* functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the execl*() functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process should start with the name of the command being run, but this is not enforced.

No idea why one seems to restart the script where it left off but I'd guess that that is unrelated.

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