How to use subprocess.Popen with built-in command on Windows
<p>In my old python script, I use the following code to show the result for Windows cmd command:</p>

<pre><code>print(os.popen("dir c:\\").read())
</code></pre>

<p>As the python 2.7 document said <code>os.popen</code> is obsolete and <code>subprocess</code> is recommended. I follow the documentation as:</p>

<pre><code>result = subprocess.Popen("dir c:\\").stdout
</code></pre>

<p>And I got error message:</p>

<pre><code>WindowsError: [Error 2] The system cannot find the file specified
</code></pre>

<p>Can you tell me the correct way to use the <code>subprocess</code> module?</p>

<p>Try:</p>

<pre><code>p = subprocess.Popen(["dir", "c:\\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
outputs = p.communicate()
</code></pre>

<p>Note that <code>communicate()</code> returns a tuple <code>(stdoutdata, stderrdata)</code>, therefore <code>outputs[0]</code> is the <code>stdout</code> messages and <code>outputs[1]</code> is the <code>stderr</code> messages.</p>

python windows python-2.7 command-line subprocess