title: Running three commands in the same process with Python
body: <p>I need to run those three commands for profiling/code coverage reporting on Win32.</p>
  
  <pre><code>vsperfcmd /start:coverage /output:run.coverage
  helloclass
  vsperfcmd /shutdown
  </code></pre>
  
  <p>I can't run one command by one because the helloclass executable should be profiled in the same process of vsperfcmd. </p>
  
  <p>What I think of is to make a batch file to run those three commands, and run the batch file in Python. However, I think python should have a way to do the equivalent action of launching a shell and run commands. </p>
  
  <ul>
  <li>Q : How can I run the commands in the same process in Python?</li>
  <li>Q : Or, how can I launch command shell and run commands in Python?</li>
  </ul>
  
  <h2>SOLVED</h2>
  
  <pre><code>import subprocess
  cmdline = ["cmd", "/q", "/k", "echo off"]
  cmd = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
  batch = b"""\
  rem vsinstr -coverage helloclass.exe /exclude:std::*
  vsperfcmd /start:coverage /output:run.coverage
  helloclass
  vsperfcmd /shutdown
  exit
  """
  cmd.stdin.write(batch)
  cmd.stdin.flush() # Must include this to ensure data is passed to child process
  result = cmd.stdout.read()
  print(result)
  </code></pre>