2010-12-07 24 views
1

繼續我的上一個問題Executing a C program in python?;什麼從C返回一個獲得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一些文章,但我不能完全把握它,所以也許有人可以指向正確的方向。

+0

查看C代碼後,使用它可能會很容易生成一個模塊,而不必調用它。 – 2010-12-07 15:20:51

+0

感謝您的回覆;你能詳細解釋一下嗎? – 2010-12-07 15:35:01

回答

2

將數據返回給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(",") 

現在,這確實產生了一堆假設......具體來說:

  • 那你所面對的是相當少的數據
  • ,你將不會被調用./spa過於頻繁(Popen.communicate()在內存中存儲的所有輸出返回給程序前)(產卵的過程是非常非常慢)

但是,如果這沒關係,這將爲你工作。

相關問題