python 打开新cmd窗口并运行exe

stackoverFlow上有答案
https://stackoverflow.com/a/20470713/19932275
根据这个答案,我写了个python程序,这个程序每1秒输出1,输出100次,并打包为exe,作为测试用。
现在他说有如下两种办法、
In Windows, you need to declare optional variable shell=True and use start:

subprocess.Popen('start executable.exe', shell=True)

or if you want to kill the shell after running the executable:

subprocess.Popen('start cmd /C executable.exe', shell=True)

没看懂什么意思???
直接实践出真知。

from time import sleep
import subprocess

if __name__ == '__main__':
    p = subprocess.Popen('start test.exe', shell=True)
    p.wait()
    print('lol')

运行,在test.exe还没运行结束前,或者说刚运行一瞬间,lol就被打印了出来,wait了个寂寞!

换成第二种办法:

from time import sleep
import subprocess

if __name__ == '__main__':
    p = subprocess.Popen('start cmd /C test.exe', shell=True)
    p.wait()
    print('lol')

运行,在test.exe还没运行结束前,或者说刚运行一瞬间,lol就被打印了出来,wait了个寂寞!
这不符合我的预期,我希望wait是有效的。

找到解答
The problem with using start is that is spawns a new process and does not wait for it to finish. I.e., the returned Popen object’s wait() method returns immediately and there is no direct way to know when the process finishes. If you want to start the process in the new console and still be able to correctly wait for process to finish, use Popen normally (no ‘start’, ‘cmd’, shell=True), but just pass the additional creationflags=subprocess.CREATE_NEW_CONSOLE parameter). Details: stackoverflow.com/a/20612529/23715 –
Alex Che
Apr 10, 2018 at 9:48
https://stackoverflow.com/a/20612529/19932275

from time import sleep
from subprocess import Popen, CREATE_NEW_CONSOLE

if __name__ == '__main__':
    p = Popen('test.exe', creationflags=CREATE_NEW_CONSOLE)
    print('k')
    p.wait()
    print('lol')

运行,在新窗口打开了test.exe并瞬间输出k,而lol并没有输出,wait有效

猜你喜欢

转载自blog.csdn.net/weixin_45518621/article/details/130890522