我使用python lib导入一个在stdout上打印的C共享库.我想要一个干净的输出,以便与管道一起使用或重定向文件.打印是在python之外的共享库中完成的.
一开始,我的方法是:
# file: test.py
import os
from ctypes import *
from tempfile import mktemp
libc = CDLL("libc.so.6")
print # That's here on purpose, otherwise hello word is always printed
tempfile = open(mktemp(),'w')
savestdout = os.dup(1)
os.close(1)
if os.dup(tempfile.fileno()) != 1:
assert False, "couldn't redirect stdout - dup() error"
# let's pretend this is a call to my library
libc.printf("hello world\n")
os.close(1)
os.dup(savestdout)
os.close(savestdout)
Run Code Online (Sandbox Code Playgroud)
第一种方法是半工作:
- 由于某种原因,它在移动stdout之前需要一个"print"语句,否则总是打印hello word.因此,它将打印一个空行而不是库通常输出的所有模糊.
- 更令人讨厌,重定向到文件时失败:
$python test.py > foo && cat foo
hello world …Run Code Online (Sandbox Code Playgroud) 我有一个简单的 C 扩展(参见下面的示例),有时使用 printf 函数进行打印。我正在寻找一种方法来包装对 C 扩展中的函数的调用,以便所有这些 printfs 将被重定向到我的 python 记录器。
你好ç:
#include <Python.h>
static PyObject* hello(PyObject* self)
{
printf("example print from a C code\n");
return Py_BuildValue("");
}
static char helloworld_docs[] =
"helloworld(): Any message you want to put here!!\n";
static PyMethodDef helloworld_funcs[] = {
{"hello", (PyCFunction)hello,
METH_NOARGS, helloworld_docs},
{NULL}
};
static struct PyModuleDef cModPyDem =
{
PyModuleDef_HEAD_INIT,
"helloworld",
"Extension module example!",
-1,
helloworld_funcs
};
PyMODINIT_FUNC PyInit_helloworld(void)
{
return PyModule_Create(&cModPyDem);
};
Run Code Online (Sandbox Code Playgroud)
设置.py:
from distutils.core import setup, Extension
setup(name = 'helloworld', …Run Code Online (Sandbox Code Playgroud) 这是从一个跟进的问题在这里.
我希望能够暂时将stdout重定向到临时文件,而python仍然可以打印到stdout.这将涉及以下步骤:
new)的副本tmp)tmpnewstdouttmp到"真正的"标准输出tmp我尝试通过以下方式实现上述方法:
import os
import subprocess
import sys
#A function that calls an external process to print to stdout as well as
#a python print to pythons stdout.
def Func(s, p = False):
subprocess.call('echo "{0}"'.format(s), shell = True)
if p:
print "print"
sil = list() # <-- Some list to store the content of the temp files
print …Run Code Online (Sandbox Code Playgroud) python ×2
stdout ×2
ctypes ×1
dup ×1
dup2 ×1
logging ×1
python-2.x ×1
python-3.x ×1
python-c-api ×1