gabriel belini gabriel belini - 4 months ago 15
Linux Question

How to redirect the output of my program into a .txt file using Linux

I need to redirect the output of a function into a .txt file.
I'm using the function printClassTree() from the library ontospy.
The code of my program is very simple:

import ontospy
g = ontospy.Graph("/home/gabsbelini/Documentos/ontologiaTeste.owl")
g.printClassTree()


I've tried:

python myprogram.py > file.txt


But it does not work.
I'm using Ubuntu 14.04
When I execute the command above it just creates the "file.txt" and shows the output in the terminal (I want that to be saved in file.txt)

Answer

try tee:

python myprogram.py | tee file.txt

or from python

with open('file.txt', 'w') as fh:
     fh.write(g.printClassTree())

EDIT In case is going to stderr you can try:

python myprogram.py 2>&1 | tee file.txt

EDIT2

 with open('file.txt', 'w') as fh:
      fh.write(str(g.printClassTree()))