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 print
command. Here's some simple examples
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)'
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,
>>> print(prog_1)
h=9
h=h+6
print(h)
>>> print(prog_2)
h=8
h-=2
print(h)
>>> print(prog_3)
c=7
c=c+4
print(c)
I want to execute them from inside my program, (which generates them), and capture the output, (i.e. the output of the print
) as a variable, but I'm stuck how to do it?
Something like
import os
output = os.popen("python -c " + prog_1).read()
would be great but I get this error?
/bin/sh: 3: Syntax error: word unexpected (expecting ")")
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??
python -c "'h=9\nh=h+6\nprint(h)'"
Thanks a lot for your help :)