2

I'm testing subprocess option in Python. I wrote simple code in C and I want run it by subprocess in Python. This is how it looks :

C code example.c (first I execute code and then in subprocess I'm using executable file) :

#include <stdio.h>

int main(int argc, char *argv[]) {
    int number= 2110;

    while (1==1)
    {
        printf("%d",number);
        printf(" return number: ")
        return number;

    }
    return 0;
}

Python Code :

def subTest():
    while True:
        numberS = subprocess.call('./example')
        print (numberS)

Output which I should have after run python code :

2110 return number: 2110

Output which I get :

2110 return number: 62

I test it on some 'numbers' and proper values I get up to 255 then 256 -> 0 etc why's that ? Why it gives 8bit values and how to do it to return proper values ?

BengBeng
  • 127
  • 2
  • 8

1 Answers1

3

This isn't a problem with Python, but actually a feature of Linux. Looking at this answer:

At the present time, most Unix-based systems only support 8-bit return values. Windows supports (at least) a 32-bit return value.

So, assuming you are on Unix, then even though you have int main(), the return value is constrained from 0 to 255. Also from the linked question:

int main(void){
return 256;
}
echo $? ;  # out 0

You'll have to find another way to return the value - perhaps print it out? This answer shows how to do it:

run = subprocess.Popen('./example', stdout = subprocess.PIPE,
                        stderr = subprocess.PIPE, env={'LANG':'C++'})
data, error = run.communicate()
numberS = int(data)
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
  • Yup I'm on Raspbian, crazy thing about this returning only 8 bit values. Any way if I for example have `long long int main()` there is the same problem. But I use your code and it gives mi this error : `ValueError: invalid literal for int() with base 10: b''` – BengBeng Sep 20 '17 at 06:38
  • Your code should have a `printf("%d", number);` as you indicate in your question. It looks as if you are not printing anything out. – Ken Y-N Sep 20 '17 at 06:51