-1

I want to print the output from a python.py file into a txt so i use this code:

python program.py > output.txt

that goes on the command line.

The problem is : it only print the 90% of the outputs, it seems that the program is too long so anyway, is there a way to print all the output in the txt ? something like:

python program.py > output.txt 1000 lines

THATS THE CODE : http://pastebin.com/2bSiGKx8

THATS WHAT IT PRINTS : http://pastebin.com/r00JteMG

tshepang
  • 12,111
  • 21
  • 91
  • 136

3 Answers3

1

Within the program you can re-direct sys.stdout to a file object:

import sys
orig_sys = sys.stdout
with open('output.txt','w') as out:
    sys.stdout = out
    #your code here
    print "foo"
    print "bar"

or pass the file name from command line arguments:

#run this as: python program.py output.txt
import sys
filename = sys.argv[1]
orig_sys = sys.stdout
with open(filename,'w') as out:
    sys.stdout = out
    #your code here

But python program.py > output.txt is also fine, may be there's something wrong with your code.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

Probably the problem that you're running into is that program.py is printing things both to stdout (which works for going into output.txt using '>') and to stderr (which would not go into the output.txt file using '>', but would go into it if you used '2>' instead). See this question on answers to what you're trying to do: How can I redirect and append both stdout and stderr to a file with Bash?

Community
  • 1
  • 1
crouleau
  • 156
  • 1
  • 1
  • 6
0

try to flush output buffer

import sys
sys.stdout.flush()

If it didn't work, instead of using print you can try logging though I guess there is not much big difference!

import logging
logging.basicConfig(format='%(message)s', filename='example.log',level=logging.DEBUG)
logging.debug('what you want to right in your file')
Moh Zah
  • 262
  • 1
  • 2
  • 9