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'
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 everyscanf
returns -1 and does not change the original value ofrhs[i]
which just happens to be0.
. Then it prints that on its stdout channel, that is 100.
double value if%f
format.And the Python script receives that byte string in its
stdout
variable. The initialb
is just the marker thatstdout
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.