-
-
Save theladyjaye/442d176a93b65c644f14 to your computer and use it in GitHub Desktop.
Redirecting embedded Python’s I/O
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Redirecting embedded Python’s I/O | |
Posted on 2012-4-13 by mvasilkov | |
When using Python for application scripting, more often than not you want to redirect interpreter’s input/output to the embedding program. This is how it’s done with the Python/C API: | |
PyObject *sys = PyImport_ImportModule("sys"); | |
PyObject *out = PyFile_FromString("python_out", "w+"); | |
PyObject_SetAttrString(sys, "stdout", out); | |
Pretty intuitive, right? Now embedded Python’s stdout points to the newly created file, python_out. Working with the script’s output from C is also trivial: | |
FILE *output = PyFile_AsFile(out); | |
rewind(output); | |
int c = fgetc(output); | |
/* fgets(), fread(), any function that takes (FILE*) */ | |
The output stream can be reset to the initial (empty) state like this: | |
ftruncate(fileno(output), 0); | |
Redirecting stdin is left as an exercise to the reader. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment