嵌入libPython时重定向stdout和stderr

时间:2014-04-19 16:30:54

标签: python ios

我在iOS应用中嵌入了libPython.a,我使用PyRun_SimpleFileEx运行脚本:

    Py_SetPythonHome((char *)[resourcePath UTF8String]);

    Py_Initialize();

    const char* argv[] = {
       …
       ">/dev/null"
    };
    PySys_SetArgv(sizeof(argv)/sizeof(char*), (char**)argv);

    PyEval_InitThreads();

    const char* prog = ...;

    FILE* fd = fopen(prog, "r");
    if (fd == NULL) {
        ret = 1;
    } else {
        ret = PyRun_SimpleFileEx(fd, prog, 1);
        if (ret != 0)
            NSLog(@"Application quit abnormally!");
    }

    Py_Finalize();

一切正常,但我还没有找到重定向stdout / stderr的方法,这样我就无法登录iOS控制台。

我尝试添加"> / dev / null"作为脚本的附加参数,但由于没有shell,它显然不起作用。

如何在这种情况下重定向stdout / stderr?或者,有一种方法可以拦截"所有Python输出调用?感谢。

1 个答案:

答案 0 :(得分:0)

以这种方式使用libpython时,# AWS Credentials client = boto3.client('athena',aws_access_key_id=aws_server_access_key, aws_secret_access_key=aws_server_secret_key,region_name='us-east-1') ba = boto3.client('s3',aws_access_key_id=aws_server_access_key, aws_secret_access_key=aws_server_secret_key,region_name='us-east-1') # Get latest modified file get_last_modified = lambda obj: int(obj['LastModified'].strftime('%s')) objs = ba.list_objects_v2(Bucket=BUCKET_NAME)['Contents'] last_added = [obj['Key'] for obj in sorted(objs, key=get_last_modified)][0] s3 = boto3.resource('s3', aws_access_key_id= aws_server_access_key,aws_secret_access_key= aws_server_secret_key) try: s3.Bucket(BUCKET_NAME).download_file(last_added, last_added) except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == "404": print("The object does not exist.") else: raise stdout是调用stderr的进程。你可以尝试

PyRun_SimpleFileEx

如果要在脚本运行后还原它们,则应查看freopen("/dev/null", "w", stdout); freopen("/dev/null", "w", stderr); 以首先获取原始值,然后还原它们。