Keep the subprocess run
<p>I have an exe file build from C++ to get the mouse shape in two states: hand or arrow. But in code it only detects one current time (run in only time and close), the output is state.
I call it in python to get the output in the Windows shell:</p>

<pre><code>output = subprocess.check_output([r'C:\Users\TomCang\Desktop\tim voi tu khoa\mouse_detect.exe'])
</code></pre>

<p>It runs 1 time, gives me the state and stops.<br>
I tried to make it run forever with:</p>

<pre><code>while(True):
    output = subprocess.check_output([r'C:\Users\TomCang\Desktop\tim voi tu khoa\mouse_detect.exe'])
    sleep(1)
    print(output)
</code></pre>

<p>Every second it checks once, but when called once is the one time the Windows shell appears. How can I call it only once and run as long as I want with only one Windows shell appearing?</p>

<p>P.S.: I can't edit my C++ function because I lost the source.</p>

<p>Yes you can. Instead of using the convenient function <code>check_output</code>, you would construct a <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen" rel="nofollow"><code>Popen</code> object</a>. This will start the process and let you control it while running. One possibility is to capture the output into a file object (usually known as "pipe" the output):</p>

<pre><code>program = r'C:\Users\TomCang\Desktop\tim voi tu khoa\mouse_detect.exe'
with subprocess.Popen([program], stdout=subprocess.PIPE, universal_newlines=True) as p:
    for line in p.stdout:
        print(line)
</code></pre>

<ul>
<li><code>stdout=subprocess.PIPE</code> â Pipe the stdout into the file object <code>p.stdout</code></li>
<li><code>universal_newlines=True</code> â Make the file be read as a text instead of binary</li>
</ul>

<p>The inner <code>for</code> loop will wait until there is output available from the program. So you don't need that <code>time.sleep(1)</code>.</p>

python cursor