gpt4 book ai didi

python - C应该向Python call()返回什么?

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:28 25 4
gpt4 key购买 nike

Executing a C program in python? 继续我之前的问题;什么从 C 返回一个以在 Python 中获取可用数据??

目前我的程序返回这个:

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;
}

我读了一些关于结构和 Pythons'pack 的文章,但我还不能完全理解它,所以也许有人可以指出正确的方向。

最佳答案

将数据返回给 Python 的最简单方法是以某种合理的格式打印出来。您得到的那个还不错,但是简单的 CSV 会更容易一些。

然后您将使用 subprocess.Popen :

p = subprocess.Popen(["./spa", "args", "to", "spa"], stdout=subprocess.PIPE)
(stdout, stderr) = p.communicate()
data = parse_output(stdout.read())

并且,例如,如果输出为 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)

那么parse_output可以这样写:

def parse_output(datastr):
return [ float(value.strip()) for value in datastr.split(",")

现在,这确实做出了一系列假设……具体来说:

  • 您正在处理的数据数量相当少(Popen.communicate() 在将所有输出返回给您的程序之前将其存储在内存中)
  • 您不会太频繁地调用 ./spa(生成进程非常非常慢)

但如果没问题,这对你有用。

关于python - C应该向Python call()返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4378077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com