0
with open('pf_d.txt', 'w+') as outputfile:
        rc = subprocess.call([pf, 'disable'], shell=True, stdout=outputfile, stderr=outputfile)
        print outputfile.readlines()

output.readlines() is returning [] even though the file is written with some data. Something is wrong here.

looks like subprocess.call() is not blocking and the file is being written after the read function. How do i solve this?

Nick
  • 1,692
  • 3
  • 21
  • 35

1 Answers1

3

The with open('pf_d.txt', 'w+') as outputfile: construct is called context manager. In this case, the resource is a file represented by the handle/file object outputfile. The context manager makes sure that the file is closed when the context is left. Closing implicates flushing, and re-opening the file after that will show you all its contents. So, one option to solve your issue is to read your file after it has been closed:

with open('pf_d.txt', 'w+') as outputfile:
    rc = subprocess.call(...)

with open('pf_d.txt', 'r') as outputfile:
    print outputfile.readlines()

Another option is to re-use the same file object, after flushing and seeking:

with open('pf_d.txt', 'w+') as outputfile:
    rc = subprocess.call(...)
    outputfile.flush()
    outputfile.seek(0)
    print outputfile.readlines()

A file handle is always represented by a file pointer, indicating the current position in the file. write() forwards this pointer to the end of the file. seek(0) moves it back to the beginning, so that a subsequent read() startes from the beginning of the file.

Dr. Jan-Philip Gehrcke
  • 33,287
  • 14
  • 85
  • 130
  • Of all languages I would expect Python to follow a consistent memory model, especially in a sequential program. – Nick Feb 09 '15 at 21:54
  • What are you saying? What is not consistent here? File pointer arithmetics are the same everywhere, be it in C or in any high-level programming language, which usually provide a quite thin wrapper around OS file handles. A handle corresponds to a pointer, and if this pointer is at the end of the file, you have no luck getting contents of the file. Re-wind the pointer to the beginning, and start reading. No magic involved. – Dr. Jan-Philip Gehrcke Feb 09 '15 at 21:56
  • Actually, I think we are both on the wrong track. In your case, the child process *inherits* the file handle to the `outputfile`, so the file pointer in your parent process should stay at position 0. That is, a read should provide all contents if the subprocess really terminated. Try the first method I propose in my answer and let me know if that works, please. – Dr. Jan-Philip Gehrcke Feb 09 '15 at 22:01
  • I have managed to get it working with Popen and communicate(). I decided against writing to files as subprocess.call couldnot be guarenteed. – Nick Feb 09 '15 at 22:51
  • I am quite sure it would have worked with the first method I proposed. Did you try? – Dr. Jan-Philip Gehrcke Feb 10 '15 at 18:18