使用 python buitin 命令写入文件 vs 使用 subprocess to 运行 similar shell 命令

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

如果我使用 python 命令,我必须打开一个文件,写入它,然后关闭它。

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

通过使用 subprocess.run,我可以 运行 一个 linux shell 命令 subprocess.call(['echo', 'blah', '>', 'foo']).

这发生在一个无限循环内,每隔一秒重复一次,因此应该尽可能减少时间。

问题是我应该使用哪种方法?

比你想象的还要糟糕!重定向是一个 shell 操作,因此您的命令不会有预期的结果。充其量,如果它能在 PATH 中找到 echo 命令,它会在标准输出上写入 blah > foo,更糟糕的是,它会因为找不到 echo 命令而失败。要使 subprocess 命令起作用,您必须添加一个 shell=True 参数。

然后在每次操作时你都会启动一个新的shell来执行回显命令。启动进程是一项昂贵的操作。如果你只是每秒循环一次,它可能甚至不会被注意到,但它比直接写入文件要昂贵得多。

但最 Pythonic 的方法是使用上下文管理器:

with open("file name", "w") as foo:
    foo.write('blah\n')