如何让我的脚本在后台运行

时间:2016-10-20 17:05:43

标签: python python-3.x arduino background-process

我正在制作一个python脚本,它从arduino发送的串口读取数据并将其插入数据库。我正在使用java制作一个绘制数据的gui。我想在打开java gui时让我的python脚本在后台运行,但是我想在java gui关闭后立即关闭python脚本。下面是我的python代码,我还没有实现java gui。

import serial, sqlite3

conn=sqlite3.connect("ProyectoFinal1.db")
c=conn.cursor()
ser = serial.Serial('COM5', 9600)

def tableCreate():
    c.execute("CREATE TABLE Temperatura(ID INT,valor INT,Fecha TIMESTAMP)")
    c.execute("CREATE TABLE Humedad(ID INT,valor INT,Fecha TIMESTAMP)")

def dataEntry(tabla,valor):
    c.execute("INSERT INTO %(tabla)s (Fecha,valor) VALUES(CURRENT_TIMESTAMP,%(valor)s)"%{"tabla":tabla,"valor":valor})
    conn.commit()


def serialRead():
   ser = serial.Serial("/dev/ttyUSB0")
   for data in ser.readline():
      if data:
        serial=data

   return serial

def parse(toParse):
    toParse=toParse.split(" ")
    humidity=toParse[0]
    temperature=toParse[1]
    toParse=[humidity,temperature]
    return toParse


while True:
  temperatura=parse(ser.readline())[1]
  humedad=parse(ser.readline())[0]

  dataEntry("Temperatura",temperatura)
  dataEntry("Humedad",humedad)

  print (humedad)

  print (temperatura)

1 个答案:

答案 0 :(得分:0)

One cross-platform way to figure out if a parent process as exited is to open a pipe between the processes and wait for it to close. The following example starts a thread in the child process that waits for stdin to close and then closes the serial port which then exits the main loop's readline.

For this to work, the parent java script needs to open a pipe and use that for the python process stdin. I don't know how to do that part but since you didn't show the java code I'll pretend that's the reason I didn't include it. This has an additional advantage in that the parent java code could gracefully close the child simply by sending a "\n" down the pipe.

import threading
import sys

# add everything before your while loop here

def parent_exit_detector(ser_to_close, pipe_to_wait):
    """Wait for any data or close on pipe and then close the
    serial port"""
    try:
        pipe_to_wait.read(1)
    finally:
        ser.close()

_exit_detector_thread = threading.Thread(target=parent_exit_detector,
    args=(ser, sys.stdin))
_exit_detector_thread.isDaemon = True


# add the while loop here