Search code examples
pythonpython-3.xfile-writingtempfile-read

Write to temp file and read from command line


I need to write a temporary file to a n*x machine using python3 so that I can read it from the command line.

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)

The output should be '<p>hi <em>there</em></p>', but the actual output is '\n', which suggests to me that Markdown.pl read the contents of the file as '\n'.


Solution

  • Use,

    file_obj.flush()

    In your case, you'll have to use

    tfile.flush()
    

    It'll write to the file on being called upon!