title: Python Script to run a C Program
body: <p>I have a C/C++ program which takes a set of arguments and displays a set of outputs to a command line (for my research).</p>
  
  <p>I would like to write a Python script to run this program multiple times for different inputs and write outputs to a file. I am planning to run the program with exhaustive inputs.</p>
  
  <p>However, I don't have any experience in writing scripts or programming in Python. So, I was wondering if I could get some pointers where to start.</p>
  
  <p>As an example, I would like to write a script for doing:</p>
  
  <pre><code>./program -flag1 [val1] -flag2 [val2] -arg1 -arg2 -arg3 ...
  Append the output to Output.txt
  ./program -flag1 [val1] -flag2 [val2] -arg1 -arg2 -arg4 ...
  Append the output to Output.txt
  ./program -flag1 [val1] -flag2 [val2] -arg1 -arg2 -arg5 ...
  Append the output to Output.txt
  ...
  ...
  ./program -flag1 [val1] -flag2 [val2] -arg1000 -arg1000 -arg1000 ...
  Append the output to Output.txt
  </code></pre>
  
  <p><strong>EDIT</strong>: I am running the program on Linux through command line, bash.</p>
  
  <p><strong>EDIT2 SLN</strong>: Just for a future reference to others who might be a beginner, doing something similar, the solution looks like following. I stripped all the parts that only affects my case.</p>
  
  <pre><code>import subprocess
  from subprocess import Popen, PIPE
  
  for commands in listArgs:
  
      # Build command through for loop in listArgs.
      # Details are omitted.
      cmd = ["./program", "-flag1", "val1", "-flag2", "val2", "-arg1", "-arg2", ... ]
  
      # Open/Create the output file
      outFile = open('/path/to/file/Output.txt', 'a+')
  
      result = subprocess.Popen(cmd, stdout=subprocess.PIPE)
      out = result.stdout.read()
  
      outFile.write(out)
      outFile.close()
  </code></pre>