Prevent python windows from being focused

2020-02-26 09:17发布

问题:

I am running a Python script on windows 7 that opens a subprocess every few seconds. This subprocess opens a window and grabs focus, disrupting any attempt by the user to do normal work while the script is running. I do not have the ability to modify the subprocess code itself. Is there a way to designate all subprocesses opened by a python script as not-focused?

CLARIFICATION: I need the window to open and be viewable/selectable, just not immediately jump on top of everything else that is going on. In other words, it need to open in the background, not force itself into the foreground.

回答1:

Here is how I did this last

# Hide the cmd prompt window
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
p = subprocess.Popen(args, startupinfo=startupinfo)


回答2:

You can run processes with a variety of flags with subprocess.call

This sample executes the console app with no UI whatsoever:

>>> import shlex, subprocess
>>> subprocess.call("C:\Windows\some_console_app.exe", shell=True)