Running a process in pythonw with Popen without a

2019-01-03 06:39发布

I have a program with a GUI that runs an external program through a Popen call:

p = subprocess.Popen("<commands>" , stdout=subprocess.PIPE , stderr=subprocess.PIPE , cwd=os.getcwd())
p.communicate()

But a console pops up, regardless of what I do (I've also tried passing it NUL for the file handle). Is there any way to do that without getting the binary I call to free its console?

5条回答
疯言疯语
2楼-- · 2019-01-03 07:07

According to Python 2.7 documentation and Python 3.7 documentation, you can influence how Popen creates the process by setting creationflags. In particular, the CREATE_NO_WINDOW flag would be useful to you.

variable = subprocess.Popen(
   "CMD COMMAND", 
   stdout = subprocess.PIPE, creationflags = subprocess.CREATE_NO_WINDOW
)
查看更多
一夜七次
3楼-- · 2019-01-03 07:08

just do subprocess.Popen([command], shell=True)

查看更多
ら.Afraid
4楼-- · 2019-01-03 07:12

You might be able to just do subprocess.Popen([command], shell=False).

That's what I use anyways. Saves you all the nonsense of setting flags and whatnot. Once named as a .pyw or run with pythonw it shouldn't open a console.

查看更多
啃猪蹄的小仙女
5楼-- · 2019-01-03 07:19

From here:

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楼-- · 2019-01-03 07:22

This works nicely in the win32api. The other solutions were not working for me.

import win32api
chrome = "\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe\""
args = "https://stackoverflow.com"

win32api.WinExec(chrome + " " + args)
查看更多
登录 后发表回答