user2957951 user2957951 - 4 months ago 32
Python Question

How to execute a python script and write output to txt file?

I'm executing a .py file, which spits out a give string. This command works fine

execfile ('file.py')

But I want the output (in addition to it being shown in the shell) written into a text file.

I tried this, but it's not working :(

execfile ('file.py') > ('output.txt')

All I get is this:

tugsjs6555

False

I guess "False" is referring to the output file not being successfully written :(

Thanks for your help

Answer

what your doing is checking the output of execfile('file.py') against the string 'output.txt'

you can do what you want to do with subprocess

#!/usr/bin/env python
import subprocess
with open("output.txt", "w+") as output:
    subprocess.call(["python", "./script.py"], stdout=output);