subprocess.run 是否 运行 正确 pandoc

subprocess.run does run properly pandoc

如果你 运行 pandoc 直接用最小的例子没问题:

$ cat workfile.md 
This is a **test** see ![alt text](https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png)
$ pandoc workfile.md 
<p>This is a <strong>test</strong> see <img src="https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png" alt="alt text" /></p>

但是如果你通过subprocess.run调用它,那么它就会失败。这个最小的例子:

import subprocess, os

path = 'workfile.md'
contents = "This is a **test** see ![alt text](https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png)"

with open(path, 'w') as f:

    f.write(contents)
    pbody = subprocess.run(["pandoc", "{}".format(path)], check=True, stdout=subprocess.PIPE)
    print("**** pbody: ", pbody)

给我们

**** pbody:  CompletedProcess(args=['pandoc', 'workfile.md'], returncode=0, stdout=b'\n')

Python(以及所有其他编程语言)为提高常见操作的性能所做的其中一件事是为文件打印等操作维护缓冲区。根据您写入文件的数量,并非所有文件都会立即写入,这让该语言减少了它必须执行的(缓慢的)操作量,以便实际将内容写入磁盘。如果在 f.write(contents) 之后调用 f.flush(),您应该会看到 pandoc 获取文件的实际内容。

还有一个缓冲层也值得注意 - 您的操作系统可能在内存中有文件的更新版本,但可能没有实际将其写入磁盘。如果您正在编写服务器,您可能还想调用 os.fsync,这将强制 OS 将其写入磁盘。