Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

python - os.exec on Windows

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:in>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:in>

H:in>
KeyboardInterrupt
>>> echo hi
hi

The call to exec:

from sys import argv
os.execvp('python', argv)

How do I replace the original Python instance with the new one, as per the behaviour one might see on Linux?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...