Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write output of terminal to file

Tags:

python

I want to save result of script to file. Example of script:

#!/usr/bin/env python
i=0
while i<10:
  a=raw_input('Write a number')
  print 'Result%s'%str(2*a)
  i+=1

And I want to save to file print value. I know that I can do that in script f=open()..., but I want to do that using output in terminal. I read that I can use module subprocess but I don't know it is correct.

like image 406
qwerty12345 Avatar asked Apr 29 '14 12:04

qwerty12345


3 Answers

IMO this is the correct pythonic way, with-out relying on the system shell:

import sys
f = open("test.out", 'w')
sys.stdout = f
print "test"
f.close()

In python you can change what is the default stdout object. You just need to assign whatever you want to sys.stdout. I think the object just need to have a write method defined (not absolutely sure, though).

This would do:

import sys
f = open("test.out", 'w')
sys.stdout = f

i=0
while i<10:
  a=raw_input('Write a number')
  print 'Result%s'%str(2*a)
  i+=1

f.close()

It's essentially the same what 0605002 suggests for systems that support syntax he uses, but realized in pure python and should be more portable.

Even more pythonic way, as per comment suggestion:

import sys

with open("test.out", 'w') as f:
  sys.stdout = f

  i=0
  while i<10:
    a=raw_input('Write a number')
    print 'Result%s'%str(2*a)
    i+=1

Of course you can refactor your "client code" and make it a function or something.

like image 60
luk32 Avatar answered Nov 26 '22 01:11

luk32


You can redirect the output to a file using > in terminal:

python your_script.py > output.txt
like image 26
Sufian Latif Avatar answered Nov 26 '22 02:11

Sufian Latif


python file.py &> out.txt

This will direct all the output including the errors to the out.txt.

like image 30
mohaghighat Avatar answered Nov 26 '22 03:11

mohaghighat