Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dumping subprcess output in a file in append mode

I have to dump the output of a subprocess to a file opened in appended mode

from subprocess import Popen

fh1 = open("abc.txt", "a+") # this should have worked as per my understanding

# fh1.readlines() # Adding this solves the problem 

p = Popen(["dir", "/b"], stdout = fh1, shell=True)

print p.communicate()[0]
fh1.close()

The above code however overwrites my file abc.txt which i don't want, un-commenting fh1.readlines() will move the cursor to appropriate position, which is a temporary solution

Is there anything basic i m missing.

In [18]: fh1 = open("abc.txt",'a')

In [19]: fh1.tell() # This should be at the end of the file
Out[19]: 0L

In [20]: fh1 = open("abc.txt",'r')

In [21]: print fh1.readlines()
['1\n', '2\n', '3\n', '4\n', '5\n']
like image 696
avasal Avatar asked Jan 15 '13 06:01

avasal


People also ask

What is Popen in subprocess?

The subprocess module defines one class, Popen and a few wrapper functions that use that class. The constructor for Popen takes arguments to set up the new process so the parent can communicate with it via pipes. It provides all of the functionality of the other modules and functions it replaces, and more.

What does subprocess check call do?

Return Value of the Call() Method from Subprocess in Python The Python subprocess call() function returns the executed code of the program. If there is no program output, the function will return the code that it executed successfully. It may also raise a CalledProcessError exception.


1 Answers

A simple, easy way of puting the cursor at the end of the file, without reading it is using:

fh1.seek(2)
# .seek(offset, [whence]) >> if offset = 2 it will put the cursor in the given position relatively
# to the end of the file. default 'whence' position is 0, so at the very end
like image 176
RGS Avatar answered Oct 22 '22 21:10

RGS