为了账号安全,请及时绑定邮箱和手机立即绑定

在没有控制台的情况下使用Popen在pythonw中运行进程

在没有控制台的情况下使用Popen在pythonw中运行进程

GCT1015 2019-11-02 10:14:08
我有一个带有GUI的程序,该程序可通过Popen调用运行外部程序:p = subprocess.Popen("<commands>" , stdout=subprocess.PIPE , stderr=subprocess.PIPE , cwd=os.getcwd())p.communicate()但是无论我做什么,都会弹出一个控制台(我也尝试过将NUL传递给文件句柄)。有什么方法可以做到而无需获取我调用的二进制文件来释放其控制台?
查看完整描述

3 回答

?
月关宝盒

TA贡献1772条经验 获得超5个赞

从这里:


import subprocess


def launchWithoutConsole(command, args):

    """Launches 'command' windowless and waits until finished"""

    startupinfo = subprocess.STARTUPINFO()

    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

    return subprocess.Popen([command] + args, startupinfo=startupinfo).wait()


if __name__ == "__main__":

    # test with "pythonw.exe"

    launchWithoutConsole("d:\\bin\\gzip.exe", ["-d", "myfile.gz"])

请注意,有时抑制控制台会使子流程调用失败,并显示“错误6:无效的句柄”。一种快速修复是重定向stdin,如此处所述:以Windows服务运行的Python:OSError:[WinError 6]句柄无效


查看完整回答
反对 回复 2019-11-02
?
侃侃无极

TA贡献2051条经验 获得超10个赞

根据Python 2.7文档和Python 3.7文档,您可以Popen通过设置影响创建过程的方式creationflags。该CREATE_NO_WINDOW标志尤其对您有用。


variable = subprocess.Popen(

   "CMD COMMAND", 

   stdout = subprocess.PIPE, creationflags = subprocess.CREATE_NO_WINDOW

)


查看完整回答
反对 回复 2019-11-02
  • 3 回答
  • 0 关注
  • 747 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信