【发布时间】:2017-08-05 03:14:38
【问题描述】:
我需要使用 python3 将一个临时文件写入 n*x 机器,以便我可以从命令行读取它。
import tempfile
import subprocess
from os import path
string = 'hi *there*'
# run markdown server-side
tfile = tempfile.NamedTemporaryFile(mode='w+', suffix='.txt', prefix='prove-math-')
tfile.write(string)
fpath = tfile.name
markdown_path = path.join(LIB_DIR, 'Markdown.pl')
command = [markdown_path, fpath]
completed_process = subprocess.run(command, check=True, stdout=subprocess.PIPE)
string = completed_process.stdout.decode()
tfile.close()
print(string)
输出应该是'<p>hi <em>there</em></p>',但实际输出是'\n',这暗示我Markdown.pl将文件内容读取为'\n'。
【问题讨论】:
-
path.join ?路径在哪里?
-
@UbdusSamad 编辑:
from os import path在代码中,但我忘记在此处包含它。现已修复。 -
你试过 tfile.flush() 吗??
-
我对tempfile模块了解不多,但是像普通文件一样写入数据是不是需要flush或正确关闭?
-
来自
tempfile的文件句柄遵循与来自open(...的文件句柄相同的规则。
标签: python python-3.x file-writing temp file-read