python 打开新cmd窗口并运行exe 您所在的位置:网站首页 python命令行运行python文件 python 打开新cmd窗口并运行exe

python 打开新cmd窗口并运行exe

2023-06-02 07:40| 来源: 网络整理| 查看: 265

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有效



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有