title: Executing Python multi-line statements from command-line, while inside python
body: <p>I've got thousands of small multi-line python3 programs to run, which are generated as strings. They all have a similar structure, and end with a <code>print</code> command. Here's some simple examples </p>
  
  <pre><code>prog_1 = 'h=9\nh=h+6\nprint(h)'
  prog_2 = 'h=8\nh-=2\nprint(h)'
  prog_3 = 'c=7\nc=c+4\nprint(c)'
  </code></pre>
  
  <p>They should all be executable if you were to run them from the interpreter. What I mean is, they look like small normal programs when you print them, </p>
  
  <pre><code>&gt;&gt;&gt; print(prog_1)
  h=9
  h=h+6
  print(h)
  
  
  &gt;&gt;&gt; print(prog_2)
  h=8
  h-=2
  print(h)
  
  
  &gt;&gt;&gt; print(prog_3)
  c=7
  c=c+4
  print(c)
  </code></pre>
  
  <p>I want to execute them from inside my program, (which generates them), and capture the output, (i.e. the output of the <code>print</code>) as a variable, but I'm stuck how to do it? </p>
  
  <p>Something like</p>
  
  <pre><code>import os
  output = os.popen("python -c " +  prog_1).read()
  </code></pre>
  
  <p>would be great but I get this error?</p>
  
  <pre><code>/bin/sh: 3: Syntax error: word unexpected (expecting ")")
  </code></pre>
  
  <p>I think the problem is I don't know how to execute the small programs from the command line? This line executes, but does not print out??</p>
  
  <pre><code>python -c "'h=9\nh=h+6\nprint(h)'"
  </code></pre>
  
  <p>Thanks a lot for your help :)</p>