1
3

More than 5 years have passed since last update.

Python 2とPython 3 > C実装の標準出力を受けて標準出力する

Last updated at Posted at 2018-08-01
Raspberry Pi 2 Model B (以下RPi)
Raspbian Jessie
Python 2.7.9
Python 3.4.2
gcc (Raspbian 4.9.2-10) 4.9.2

概要

  • C実装で1秒おきに標準出力される
  • その標準出力を受けて、Pythonで標準出力する

CでI2C通信を実装して、その結果をpySerialを使ってPythonでRS-232Cに送信しようと考えている。
そのための予備調査。

実装

C > 1秒おきの標準出力

tickTime_180801.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <time.h>

static void printTime_clock_gettime(bool addLF)
{
    struct timespec tvToday; // for msec
    struct tm *ptm; // for date and time

    clock_gettime(CLOCK_REALTIME_COARSE, &tvToday);
    ptm = localtime(&tvToday.tv_sec);

    // date and time
    printf("%04d/%02d/%02d,%02d:%02d:%02d,",
        ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday,
        ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
    // msec
    printf("%03d,", (uint16_t)(tvToday.tv_nsec / 1000000));

    if (addLF) {
        printf("\n");
    }
}

int main(void)
{
    struct timespec req;    
    int loop;

    req.tv_sec = 1;
    req.tv_nsec = 0;

    for(loop=0; loop<5; loop++) {
        printTime_clock_gettime(/*addLF=*/true);
        fflush(stdout);
        nanosleep(&req, NULL);
    }
}

Python 2 > 標準出力を受けて標準出力する

redirect_180801.py
# v0.1 Aug. 01, 2018
#   - break when [EOFError]
#   - read using raw_input()

# on Python 2.7.9

while True:
    try:
        res = raw_input()
        print(res)
    except EOFError:
        break

コンパイルと実行

$ gcc tickTime_180801.c -o tickTime_180801
$ ./tickTime_180801 | python2 -u redirect_180801.py 
2018/08/01,18:06:11,972,
2018/08/01,18:06:12,982,
2018/08/01,18:06:13,982,
2018/08/01,18:06:14,982,
2018/08/01,18:06:15,982,

標準出力は1秒おきに実施される。

注記: raw_input()はPython 2で使います

備考

  • sys.stdinでは希望の動作にはならなかった

Python 3 > 標準出力を受けて標準出力する

Python3ではraw_input()でなくinput()を使う。

  • 参考: 科学技術計算のためのPython入門 by 中久喜健司様
    • p14の表1.4 Python 2系列とPython 3系列の違いの例
redirect_py3_180801.py
# v0.1 Aug. 01, 2018
#   - break when [EOFError]
#   - read using raw_input()

# on Python 3.4.2

while True:
    try:
        res = input()
        print(res)
    except EOFError:
        break

run
$ ./tickTime_180801 | python3 -u redirect_py3_180801.py 
2018/08/01,18:37:13,143,
2018/08/01,18:37:14,153,
2018/08/01,18:37:15,153,
2018/08/01,18:37:16,153,
2018/08/01,18:37:17,163,
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3