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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.