2017-08-05 77 views
2

我需要使用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'

+0

path.join?路在哪里? –

+0

@UbdusSamad编辑:'从os导入路径'是在代码中,但我忘记了在这里包括它。现在修复。 – mareoraft

+1

你试过tfile.flush()吗? –

回答

0

使用,

file_obj.flush()

在你的情况,你将不得不使用

tfile.flush() 

它会写入到文件上被称为当!

+0

阅读评论,我建议他也关闭它,但是,无论他为他工作的是我的朋友的回答! –

+1

@SergeBallesta我相信'tfile.close()'不起作用,因为'tempfile'在关闭后删除文件 – mareoraft

+1

@SergeBallesta另外,如果列出哪些操作系统会给出问题,这只是有用的信息。[tempfile](https://docs.python.org/3.5/library/tempfile.html?highlight=tempfile# module-tempfile)文档只提到Windows NT或更高版本会出现问题。 – mareoraft