Sublime Forum

Window loses focus when running subprocess

#1

I’m trying to implement python live coding as a plugin (https://donkirkby.github.io/live-py-plugin/). I’ve got a basic implementation working, however running into an issue where my window loses focus after a call to subprocess. To repro, create a plugin using the snippets below:

Main.sublime-menu

[
{
“id”: “test”,
“caption”: “Test”,
“children”: [
{
“command”: “test”,
“caption”: “Test”
}
]
}
]

test.py

import subprocess

import sublime, sublime_plugin

class TestCommand( sublime_plugin.WindowCommand ):

def run( self ):
    proc = subprocess.Popen( 
        'python', 
        stdin=subprocess.PIPE, 
        stdout=subprocess.PIPE, 
        stderr=subprocess.PIPE, 
        universal_newlines=True
    )
    out, err = proc.communicate()

To repro:

  • Open two windows side by side
  • Focus window on the left
  • Run the plugin code using Menu Test -> test
  • A python window should open then immediately close
  • Observe the cursor and focus moving to the window on the right

Is this expected behaviour? I would expect the window on the left to maintain focus, since I used the left window’s menu to start the process.

Platform: Windows 10
Version: 3.2.1
Build: 3207

0 Likes

#2

It’s because Windows runs gui-less console programs like python in the console host, which opens a console window in front of ST.

To avoid creating the console window you need to pass some flags to subprocess.POpen


    def run(the_file):
        startupinfo = None
        if WIN32:
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

        return subprocess.Popen(
            args=['python', '-u', te_file],
            startupinfo=startupinfo,
            stdin=subprocess.PIPE,   # python 3.3 bug on Win7
            stderr=subprocess.PIPE,
            stdout=subprocess.PIPE,
,           universal_newlines=True
        )
        out, err = proc.communicate()
0 Likes

#3

Thanks for the reply, deathaxe. I’ll test your solution but my original implementation does as you’ve suggested - it hides the console of the child process but I think the window focus is still switched when using two windows in sublime.

0 Likes

#4

You need to pass the startupinfo to hide the console window on Windows.

0 Likes