0

Hey I have been messing around on Python and I need to know if there is a way of testing if the output of a Python Script equals something. Heres what I have been trying:

a = """
print("Hey")
b = 5
print(str(b+5))
"""

if str(exec(a)) == "Hey\n10":
    print("True")

It just prints out the answer of executing 'a'.

What am I doing wrong?

Digbywood
  • 25
  • 5

2 Answers2

0

Try this:

Put the code you want to test in one python file:

myFile.py

a = """
print("Hey")
b = 5
print(str(b+5))
"""

exec(a)

Now, use a bash script to run that python script and store the result in another file (for comparisons)

test.sh

#!/bin/bash
python myFile.py > output.txt

Now, use a python script to call the bash script, and then test the outputs (read from that output file) as required:

test.py

import subprocess

subprocess.check_call("test.sh", shell=True)
with open('output.txt') as infile:
    output = infile.read()
if output == "Hey\n10":
    print("True")
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
0

Try replacing the default sys.stdout

import sys
from StringIO import StringIO

a = """
print("Hey")
b = 5
print(str(b+5))
"""


buffer = StringIO()
sys.stdout = buffer

exec (a)
#remember to restore the original stdout!
sys.stdout = sys.__stdout__

print buffer.getvalue()

This way you can store your exec output

Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47