6

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

4

2 回答 2

8

在底层他们做同样的事情:他们用一个新进程替换正在运行的进程映像。

和之间的唯一区别是他们争论的方式。需要一个参数列表(第一个应该是可执行文件的名称),而需要一个变量的参数列表。execvexeclexecvexecl

因此,在本质上,execv(file, args)完全等价于execl(file, *args)


请注意,这sys.argv[0]已经是脚本名称。但是,这是传递给 Python 的脚本名称,可能不是程序正在运行的实际脚本名称。为了正确和安全,您传递给的参数列表exec*应该是

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

我刚刚使用以下内容测试了重启脚本:

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

这很好用。确保你没有忽略或默默地捕捉到任何错误execl——如果它无法执行,你最终会“从你离开的地方继续”。

于 2015-07-16T07:11:12.800 回答
0

根据Python 文档execv, and之间没有真正的功能区别execl

exec* 函数的“l”和“v”变体在传递命令行参数的方式上有所不同。如果在编写代码时参数的数量是固定的,那么“l”变体可能是最容易使用的;单个参数只是成为 execl*() 函数的附加参数。当参数的数量是可变的时,“v”变体很好,参数在列表或元组中作为 args 参数传递。在任何一种情况下,子进程的参数都应该以正在运行的命令的名称开头,但这不是强制的。

不知道为什么似乎要从中断的地方重新启动脚本,但我猜那是无关的。

于 2015-07-16T07:10:58.047 回答