Windows上的os.exec [英] os.exec on Windows
问题描述
我有一个脚本,该脚本将os.execvp
调用到另一个Python实例中.完成此操作后,我似乎将附加到cmd.exe
实例,而不是我刚刚创建的Python实例. Python实例会响应 Ctrl + C .
I have a script that calls os.execvp
into another Python instance. After doing this, I appear to be attached to a cmd.exe
instance, not the Python instance I just created. The Python instance responds to Ctrl+C however.
H:\bin>Python 3.2.1 (default, Jul 10 2011, 21:51:15) [MSC v.1500
32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print('hi')
Can't find file ('hi')
H:\bin>
H:\bin>
KeyboardInterrupt
>>> echo hi
hi
对exec
的呼叫:
from sys import argv
os.execvp('python', argv)
按照Linux上可能出现的行为,如何用新的Python实例替换原始的Python实例?
How do I replace the original Python instance with the new one, as per the behaviour one might see on Linux?
推荐答案
在Unix上,执行二进制文件分为两个阶段- fork(3)克隆当前进程并 exec(3)将可执行文件加载到地址空间.在Windows上,只有 CreateProcess 与fork + exec的功能相同.
On Unix executing binaries is split into two stages - fork(3) to clone current process and exec(3) to load executable into address space. On windows there is only CreateProcess which does the same thing as fork+exec.
对于可移植性,最好的选择是使用 subprocess.Popen (与os.*对应版本不同,它在Windows上也执行正确的文件名引用),如
For portability your best bet is to use subprocess.Popen (which also does proper filename quoting on Windows unlike os.* counterparts) as in http://docs.python.org/library/subprocess.html#replacing-the-os-spawn-family
这篇关于Windows上的os.exec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!