相关疑难解决方法(0)

如何防止C共享库在python中的stdout上打印?

我使用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)

python ctypes python-2.x

41
推荐指数
3
解决办法
1万
查看次数

C 扩展 - 如何将 printf 重定向到 python 记录器?

我有一个简单的 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)

logging stdout python-c-api python-3.x python-logging

7
推荐指数
1
解决办法
2601
查看次数

python中的dup,dup2,tmpfile和stdout

这是从一个跟进的问题在这里.


我想去哪里

我希望能够暂时将stdout重定向到临时文件,而python仍然可以打印到stdout.这将涉及以下步骤:

  1. 创建stdout(new)的副本
  2. 创建临时文件(tmp)
  3. 将stdout重定向到 tmp
  4. 告诉python使用newstdout
  5. 重定向tmp到"真正的"标准输出
  6. 告诉python再次使用"真正的"标准输出
  7. 阅读和关闭 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 stdout io-redirection dup2 dup

3
推荐指数
1
解决办法
8381
查看次数