2015-10-12 32 views
0

目前我遇到了問題,我被迫將我的項目拆分爲python和C++腳本,因爲它們有我需要的硬件指定庫。作爲我的項目的一部分,C++腳本爲我的led燈條創建rgb數據,python腳本將它們上傳到led。因此,我需要在計劃之間進行信息交流,因爲領導者必須始終進行更新,這導致我們面臨主要問題。 C++腳本將數據寫入.txt文件並寫入trigger2.txt文件。 python腳本一直在等待觸發文件,直到它顯示出來纔開始。 Python腳本完成後,它還會創建一個trigger.txt文件,以便C++腳本知道它可以重新啓動。 當我運行我的程序時,它會上傳一次rgb數據,但是會停止。看起來,在C++腳本啓動python腳本並且已經上傳rgb數據後,C++無法繼續,因爲python腳本在while循環中要求trigger2.txt。就像C++腳本正在等待Python腳本完成的進程列表中的第二個腳本一樣。同時運行C++和python腳本導致出現問題

這裏是C++腳本:

int main(){ 
int counter = 0; 
int a; 

while(1){ 

a=0; 
    if (counter>0){     //If counter==0 it's the first time an no trigger is needed 
    while(a<1){ 
     std::ifstream FileTest("trigger.txt"); //If the trigger file exists the script can start again 
     if(FileTest){ 
      a++; 
      system("sudo rm trigger.txt");  //cleaning the folder 
      } 
     else 
      std::cout << "Can't find trigger.txt" << std::endl; 
    } 
    } 
if (a==1||counter==0){ 

/////The rgb data is generated here 

    std::fstream file;    //Writing the .txt to transfer the rgb data 
    file.open("rgb.txt", std::ios::out); 
    for (int i = 0; i < 3;i++) 
      file << rgbmatrix[i]<< std::endl; 
    file.close(); 
    system("sudo touch trigger2.txt");  //The Python script can start now to refresh the led's 

    if (counter==0){    //The first time led.py will be started manually 
    system("sudo python led.py"); 
    zaehler++; 
    } 
} 
} 
    return 0; 
} 

這是python腳本:

rgb = [1,2,3] 
i=0 
import time 
import sys 
import os 

while 1: 
    if (os.path.exists('/home/pi/rgbwired_v2/trigger2.txt')): 
    os.system("sudo rm trigger2.txt") 
    file = open("rgb.txt","r") 
    rgb = file.readlines() 
    file.close() 
    rgb = [int(i) for i in rgb] 

    #RGB data will be uploaded here 

    sys.stdout.write('led printed') 
    os.system("sudo rm rgb.txt") 
    os.system("sudo touch trigger.txt") 

    else: 
    sys.stdout.write('File not found') 
    time.sleep(1) 

我感謝所有的幫助。謝謝。 (我正在與Raspberry Pi合作)

+0

會是調用C的一個問題++從Python腳本內的程序?因爲如果沒有,你可以嘗試。 – wastl

+0

謝謝你的回答,它沒有解決問題,但現在我確信我的懷疑是正確的。現在,我改變了我的代碼後,它只是運行我的C++腳本的while循環。看起來好像腳本不能交替。我能做些什麼:/? – Darxyde

回答

0

爲了讓C++程序完成它必須做的工作,您可以從您的Python腳本中調用它,讀取其輸出並在需要時輸出一些輸入一些更多的工作。爲了達到這個目的,你可以使用由python提供的subprocess庫。

然後,您的C++代碼需要等待一些特殊輸入(例如換行符'\ n'或類似的東西),然後計算需要進行計算的內容,然後將數據寫入stdout,然後寫入表示該數據集的最後一行(如簡單的寫「端」,或者一個空行)

Python代碼會是這個樣子:

import subprocess 

#Start the c++ program 
process = subprocess.Popen(['<path to the c++ executable>', <arg1>, <arg2], stdin=subprocess.PIPE) 
#Grab its output 
p_out = process.stdout 
#Grab its input 
P_in = p.stdin 

while True: 
    p_in.write('\n') 
    lines = [] 
    line = p_out.readline().decode("utf-8").strip() 
    while line: 
     <process the read data> 
     line = p_out.readline().decode("utf-8").strip() 
+0

我並不不熟悉這個子過程,但是當你說它等待C++程序的終止時,你的意思是它完全完成了嗎?由於C++程序的初始化花費了太多時間,我無法一次又一次地啓動它。完全終止是不可能的,這就是爲什麼我使用while循環。 – Darxyde

+0

我編輯了我的答案,所以你只需要啓動一次C++程序。 – wastl

相關問題