如何使用Java程序检索Python脚本的输出

时间:2014-04-05 17:26:54

标签: java python raspberry-pi

我的代码出现问题。我有一个java类,它调用获取gps数据的python脚本。问题是我可以调用脚本,但我想将数据返回到java端的字符串,以便稍后在数组中使用它。所以我基本上只想从python脚本获取数据并将其作为字符串传递给java并将其放入数组中。

python代码

    #! /usr/bin/python
     import os
     from gps import *
     from time import *
     import time
     import threading

     gpsd = None #seting the global variable

     os.system('clear') #clear the terminal (optional)

     class GpsPoller(threading.Thread):
      def __init__(self):
      threading.Thread.__init__(self)
      global gpsd #bring it in scope
      gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info
      self.current_value = None
      self.running = True #setting the thread running to true

 def run(self):
   global gpsd
  while gpsp.running:
  gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the     buffer

if __name__ == '__main__':
 gpsp = GpsPoller() # create the thread
try:
  gpsp.start() # start it up
  while True:
    #It may take a second or two to get good data
    #print gpsd.fix.latitude,', ',gpsd.fix.longitude,'  Time: ',gpsd.utc

    os.system('clear')

    print
    print ' GPS reading'
    print '----------------------------------------'
    print 'latitude    ' , gpsd.fix.latitude
    print 'longitude   ' , gpsd.fix.longitude     

    time.sleep(5) #set to whatever

except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
  print "\nKilling Thread..."
  gpsp.running = False
  gpsp.join() # wait for the thread to finish what it's doing
print "Done.\nExiting."

java代码

                   Process p4 = null;
                  //String commands4="sudo python test1.py";



                   // provision gpio pin #01 as an output pin and turn on



                    try {




                         p4 = Runtime.getRuntime().exec("sudo python test1.py");
                         InputStream is = p4.getInputStream();
                         int i = 0;
                         while( (i = is.read() ) != -1) {
                             System.out.print((char)i);
                             lat
                             break;
                         }

1 个答案:

答案 0 :(得分:0)

您可能想要检查p4.exitCode()以查看是否成功调用了python脚本,然后如果它不成功,您可以检查p4.getErrorStream()以查看原因。

无论哪种方式,代码通常都应该处理不同的退出代码,因为你可能永远不会100%确信调用python脚本总是会成功。