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?

0

2 Answers 2

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")
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.