Reputation: 6185
Continuing on my previous question at Executing a C program in python?; what returns one from C to get usable data in Python??
Currently my program returns this:
int main (int argc, char *argv[])
{
spa_data spa; //declare the SPA structure
int result;
float min, sec;
//enter required input values into SPA structure
spa.year = 2003;
spa.month = 10;
spa.day = 17;
spa.hour = 12;
spa.minute = 30;
spa.second = 30;
spa.timezone = -7.0;
spa.delta_t = 67;
spa.longitude = -105.1786;
spa.latitude = 39.742476;
spa.elevation = 1830.14;
spa.pressure = 820;
spa.temperature = 11;
spa.slope = 30;
spa.azm_rotation = -10;
spa.atmos_refract = 0.5667;
spa.function = SPA_ALL;
//call the SPA calculate function and pass the SPA structure
result = spa_calculate(&spa);
if (result == 0) //check for SPA errors
{
//display the results inside the SPA structure
printf("Julian Day: %.6f\n",spa.jd);
printf("L: %.6e degrees\n",spa.l);
printf("B: %.6e degrees\n",spa.b);
printf("R: %.6f AU\n",spa.r);
printf("H: %.6f degrees\n",spa.h);
printf("Delta Psi: %.6e degrees\n",spa.del_psi);
printf("Delta Epsilon: %.6e degrees\n",spa.del_epsilon);
printf("Epsilon: %.6f degrees\n",spa.epsilon);
printf("Zenith: %.6f degrees\n",spa.zenith);
printf("Azimuth: %.6f degrees\n",spa.azimuth);
printf("Incidence: %.6f degrees\n",spa.incidence);
min = 60.0*(spa.sunrise - (int)(spa.sunrise));
sec = 60.0*(min - (int)min);
printf("Sunrise: %02d:%02d:%02d Local Time\n", (int)(spa.sunrise), (int)min, (int)sec);
min = 60.0*(spa.sunset - (int)(spa.sunset));
sec = 60.0*(min - (int)min);
printf("Sunset: %02d:%02d:%02d Local Time\n", (int)(spa.sunset), (int)min, (int)sec);
} else printf("SPA Error Code: %d\n", result);
return 0;
}
I read some articles about structs and Pythons'pack, but I couldn't quite grasp it yet, so maybe somebody can point the right direction.
Upvotes: 1
Views: 273
Reputation: 154672
The simplest way to return data to Python would be to print it out in some sensible format. The one you've got there decent, but a simple CSV would be a bit easier.
Then you'll use subprocess.Popen:
p = subprocess.Popen(["./spa", "args", "to", "spa"], stdout=subprocess.PIPE)
(stdout, stderr) = p.communicate()
data = parse_output(stdout.read())
And, for example, if the output was CSV:
printf("%.6f, %.6e, %.6e, %.6f, %.6f, %.6e, %.6e, %.6f, %.6f, %.6f, %.6f\n",
spa.jd, spa.l, spa.b, spa.r, spa.h, spa.del_psi, spa.del_epsilon, spa.epsilon,
spa.zenith, spa.azimuth, spa.incidenc)
Then parse_output
could be written:
def parse_output(datastr):
return [ float(value.strip()) for value in datastr.split(",")
Now, this does make a bunch of assumptions… Specifically:
Popen.communicate()
stores all the output in memory before returning it to your program)./spa
too often (spawning a process is very, very slow)But if that's fine, this will work for you.
Upvotes: 2