0

I run the following script:

with open("logfile.txt", 'w') as log_file:
    cmd = path + '/somebinary'
    log_file.write("Running the command: %s\n" % cmd)
    subprocess.call(cmd, shell=True, stdout=log_file, stderr=log_file)

However, the cmd variable gets written to the end of the file and not to the beginning (which I was expecting / hoping for). Can somebody explain to me why and how to prevent this, please?

n1000
  • 5,058
  • 10
  • 37
  • 65

1 Answers1

1

The operating system performs buffering which can cause output to occur in unexpected order. To force it, flush the file handle after writing.

with open("logfile.txt", 'w') as log_file:
    cmd = path + '/somebinary'
    log_file.write("Running the command: %s\n" % cmd)
    log_file.flush()
    subprocess.call(cmd, shell=True, stdout=log_file, stderr=log_file)

Demo: https://ideone.com/U8RPBy

As an aside, you generally want to avoid shell=True; try

    cmd = [path + '/somebinary']
    ...
    subprocess.call(cmd, stdout=log_file, stderr=log_file)

and perhaps make sure your PATH is correct instead of hardcoding a specific path.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thank you so much! For some reason the my script will not work without `shell=True`. I will have to investigate. And I am not sure why you suggest to put the path into a list. – n1000 Dec 01 '21 at 07:00
  • The linked question about avoiding `shell=True` explains they why and the how of that. If you need a shell for some reason (like `somebinary` is not actually a binary at all) then of course that refactoring is not possible. – tripleee Dec 01 '21 at 07:21