Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><a href="https://docs.python.org/3/library/subprocess.html?highlight=subprocess#subprocess.Popen.communicate" rel="noreferrer"><code>Popen.communicate()</code></a> documentation:</p> <blockquote> <p>Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.</p> <p><strong>Replacing os.popen*</strong></p> </blockquote> <pre><code> pipe = os.popen(cmd, 'w', bufsize) # ==&gt; pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin </code></pre> <blockquote> <p><strong>Warning</strong> Use communicate() rather than stdin.write(), stdout.read() or stderr.read() to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.</p> </blockquote> <p>So your example could be written as follows:</p> <pre><code>from subprocess import Popen, PIPE, STDOUT p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0] print(grep_stdout.decode()) # -&gt; four # -&gt; five # -&gt; </code></pre> <hr> <p>On the current Python 3 version, you could use <a href="https://docs.python.org/3/library/subprocess.html#subprocess.run" rel="noreferrer"><code>subprocess.run</code></a>, to pass input as a string to an external command and get its exit status, and its output as a string back in one call:</p> <pre><code>#!/usr/bin/env python3 from subprocess import run, PIPE p = run(['grep', 'f'], stdout=PIPE, input='one\ntwo\nthree\nfour\nfive\nsix\n', encoding='ascii') print(p.returncode) # -&gt; 0 print(p.stdout) # -&gt; four # -&gt; five # -&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload