Using python buitin commands for writing to a file vs using subprocess to run similar shell command

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Using python buitin commands for writing to a file vs using subprocess to run similar shell command on this date .

If I use python commands, I have to open a file, write to it, then close it.

foo = open("file name", w+)
foo.write("blah")
foo.close() 

By using subprocess.run, I can run a linux shell command subprocess.call(['echo', 'blah', '>', 'foo']).

This happens inside an infinite loop repeats every one second, therefore is supposed to take minimum time as possible.

Question is which method should I use?

Answer

It is even worse that what you expect! Redirections are a shell operation, so your command will not have the expected result. At best, if it can find an echo command in the PATH, it will write blah > foo on standard output, at worse, it will fail for not finding the echo command. For the subprocess command to work, you will have to add a shell=True parameter.

Then on each operation you will start a new shell to execute the echo command. Starting a process is an expensive operation. If you only loop every second, it would probably not even be noticeable, but it is much more expensive than a direct write to a file.

But the most Pythonic way would be to use a context manager:

with open("file name", "w") as foo:
    foo.write('blahn')