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']
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With