Daniel Standage
Daniel Standage

Reputation: 8304

Issue system call from Python, get filename for output

I am writing a Python program that calls a library (GenomeTools) via its C API. There is a function in GenomeTools that takes a filename as input and processes the file's contents in a single pass.

I am wondering if there is a way I can issue a system call from Python and have that C function process the output of the system call. I typically use the subprocess module when I want to issue system calls in Python, but this is different since the C function takes a filename as input. Is there a way I can assign a filename to the output of the system call?

Upvotes: 0

Views: 100

Answers (1)

tdelaney
tdelaney

Reputation: 77347

You can pipe the system call output to a temporary file and then use its filename for your C call. Wit hany luck, you delete the file before it even gets out of the RAM cache onto the disk.

import tempfile
import subprocess as subp
import os

tempfp = tempfile.NamedTemporaryFile(delete=False)
try:
    proc = subp.Popen(['somecommand'], stdout=tempfp)
    tempfp.close()
    proc.wait()
    some_c_function(tempfp.name)
finally:
    tempfp.close()
    os.remove(tempfp.name)

Upvotes: 2

Related Questions