Python 在subprocess.Popen中处理pthread_cond_wait

Python 在subprocess.Popen中处理pthread_cond_wait,python,pthreads,subprocess,Python,Pthreads,Subprocess,我有一个c代码,它使用pthread,特别是pthread_cond_wait。我的问题是,如果我使用subprocess.Popen从python代码中调用此c可执行文件,它将无法正常工作,看起来它是在缓冲数据,而不是实时打印。以下是我的c代码: #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h&g

我有一个c代码,它使用pthread,特别是pthread_cond_wait。我的问题是,如果我使用subprocess.Popen从python代码中调用此c可执行文件,它将无法正常工作,看起来它是在缓冲数据,而不是实时打印。以下是我的c代码:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <pthread.h>
#include "linux_nfc_api.h"

pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

nfcTagCallback_t g_TagCB;
nfc_tag_info_t g_tagInfos;

void onTagArrival(nfc_tag_info_t *pTagInfo){
    printf("Tag detected\n");
    int i = 0;
    for(i = 0x00; i < (*pTagInfo).uid_length; i++){
        printf("%02X ", (unsigned char) (*pTagInfo).uid[i]);
    }
    g_tagInfos = *pTagInfo;
    pthread_cond_signal(&condition);
}

void onTagDeparture(void){
    printf("Tag removed\n");
}

int main(int argc, char ** argv) {
    g_TagCB.onTagArrival = onTagArrival;
    g_TagCB.onTagDeparture = onTagDeparture;
    nfcManager_doInitialize();
    nfcManager_registerTagCallback(&g_TagCB);
    nfcManager_enableDiscovery(DEFAULT_NFA_TECH_MASK, 0x01, 0, 0);

    unsigned char page = 0x00;
    int i;
    int res = 0x00;
    unsigned char cmd_send[3] = {0x02, 0x20, 0x00};
    unsigned char cmd_response[255];
    printf("Waiting for tag...\n");
    do{
        pthread_cond_wait(&condition, &mutex); //problem

        memset(cmd_response, 0x00, 255);

        printf("SEND APDU: ");
        for(i=0; i < sizeof(cmd_send); i++){
            printf("%02X ",cmd_send[i]);
        }

        res = nfcTag_transceive(g_tagInfos.handle, cmd_send, 3, cmd_response, 255, 500);
        printf("RECV APDU (%d): ",res);
        for(i=0; i<res; i++){
            printf("%02X ",cmd_response[i]);
        }
    }while(1);
    nfcManager_doDeinitialize();
}
因此,考虑到我将无法更改我的c代码这一事实,有没有办法处理这种情况?

试试:

import sys
from subprocess import Popen, PIPE, call

proc = Popen(['App'], stdout=PIPE, stderr=PIPE)
output, errors = proc.communicate()
print output.decode()
原因:

请参阅python文档:

警告-使用communicate()而不是.stdin.write、.stdout.read或 .stderr.read以避免由于任何其他操作系统管道而导致死锁 缓冲区填满并阻塞子进程


这是由于条件变量还是管道是块缓冲的,并且只有在输出大量数据后才会将数据从子进程发送回您的读线?是的,管道是块缓冲的。
pty
模块,或者甚至可能是
pexpect
,如果您在类似linux的系统上,可能对您有效。我在linux。你能举个例子吗?这里公认的答案应该很容易适应
import sys
from subprocess import Popen, PIPE, call

proc = Popen(['App'], stdout=PIPE, stderr=PIPE)
output, errors = proc.communicate()
print output.decode()