Issue with passing array to subprocess module whil

2019-08-25 10:11发布

I am using this code to call a C script from Python:

subprocess.check_output(["./s_cg",str(10),str(bb)])

The C script has code:

int main(int argc, char *argv[])
{
int order;
int i,j;
order = atoi(argv[1]);

double* rhs = malloc(order * sizeof(double));
for (i = 0; i < order; i++) {
              scanf("%lf", &rhs[i])

          }


 for(i=0;i<order;i++)
  {
    printf("%lf",rhs[i]);
  }

    return 0;

}

The actual array bb passed is: array([1., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

But the printed array is:

b'0.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.000000'

标签: python c
1条回答
乱世女痞
2楼-- · 2019-08-25 11:14

The only channels between a process and its subprocess are pipes, that is simple streams of bytes.

The C programs receives an empty stdin stream through communicate, which is the same as reading from an empty file. It reads 10 values from that (and finds nothing) so every scanf returns -1 and does not change the original value of rhs[i] which just happens to be 0.. Then it prints that on its stdout channel, that is 10 0. double value if %f format.

And the Python script receives that byte string in its stdout variable. The initial b is just the marker that stdout is a byte string and not an unicode string.

If that matters, there is no way to pass complex objects between a process and its subprocess: everything must be serialized at a string of bytes by the sender and deserialized by the receiver. The Python struct module is specifically good at serializing simple types in a portable way so that they can be easily deserialized in C.

查看更多
登录 后发表回答