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

送分小仙女□ 提交于 2019-11-29 23:40:36

问题


Is there a difference between os.execl() and os.execv() in python? I was using

os.execl(python, python, *sys.argv) 

to restart my script (from here). But it seems to start from where the previous script left.

I want the script to start from the beginning when it restarts. Will this

os.execv(__file__,sys.argv)

do the job? command and idea from here. I couldn't find difference between them from the python help/documentation. Is there a way do clean restart?

For a little more background on what I am trying to do please see my other question


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/31447442/difference-between-os-execl-and-os-execv-in-python

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