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

如何使用Java程序检索Python脚本的输出,java,python,raspberry-pi,Java,Python,Raspberry Pi,我的代码有问题。我有一个java类,它调用获取gps数据的python脚本。问题是我可以调用脚本,但我想将数据返回到java端的字符串,以便以后在数组中使用它。因此,基本上我只想从python脚本中获取数据,并将其作为字符串带到java中,然后将其放入数组中 python代码 #! /usr/bin/python import os from gps import * from time import * import time impo

我的代码有问题。我有一个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;
                         }

您可能需要检查
p4.exitCode()
以查看python脚本是否被成功调用,如果调用不成功,您可以检查
p4.getErrorStream()
以了解原因


不管怎样,通常情况下,代码应该处理不同的退出代码,因为您可能永远不会100%相信调用python脚本总是成功的。

请格式化您的代码。您收到了哪些特定的错误?我无法理解python代码的工作原理,但我似乎无法理解如何将数据保存在java中,并且代码似乎不正确跑而不跑