使用 Python subprocess.call() 时如何写入文件的开头?

How to write to the beginning of a file when using Python subprocess.call()?

我运行以下脚本:

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)

然而,cmd 变量被写入文件的末尾而不是开头(这是我所期待/希望的)。有人可以向我解释为什么以及如何防止这种情况发生吗?

操作系统执行缓冲,这可能导致输出以意外的顺序出现。要强制它,flush写入后的文件句柄。

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)

演示:https://ideone.com/U8RPBy

顺便说一句,你generally want to avoid shell=True;尝试

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

并且也许确保您的 PATH 是正确的而不是硬编码特定的 path