串口不重写Python的code工作 [英] Serial port does not work in rewritten Python code
问题描述
我有一个Python程序,在数据库中读取一个Arduino并将其存储一些参数。串行端口设置和使用这样的:
I have a Python program that reads some parameters from an Arduino and stores it in a database. The serial port is set up and used like this:
ser = serial.Serial(port=port, baudrate=9600)
ser.write('*')
while 1 :
ser.write('*')
out = ''
# Let's wait one second before reading output (let's give device time to answer).
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1)
if out != '':
etc ... handling data
(Arduino的设置,所以当它收到一个明星,它发回的数据串)。我想改写这个作为的守护,所以我使用Python守护进程库。在的init 双组分,我只是定义端口名称,然后:
(The Arduino is set up so when it receives a star, it sends back a data string.) I would like to rewrite this as a daemon, so I am using the python-daemon library. In the init-part, I just define the port name, and then:
def run(self):
self.ser = serial.Serial(port=self.port,baudrate=9600)
while True:
self.ser.write('*')
out = ''
# Let's wait one second before reading output (give device time to answer).
time.sleep(1)
while self.ser.inWaiting() > 0:
out += self.ser.read(1)
if out != '':
etc ...
一切都是平等的,但我现在在做一个App-对象中的串行处理。第一个版本运行正常,当我尝试运行后,我得到
Everything is equal, except that I am now doing the serial handling within an App-object. The first version runs fine, when I try to run the latter, I get
File "storedaemon.py", line 89, in run
while self.ser.inWaiting() > 0:
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 435, in inWaiting
s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
IOError: [Errno 9] Bad file descriptor
我不能看到发生了什么变化 - 除了我已经抛出一个新的对象内部的code。我曾经尝试都做初始化中的的init 并在运行,但我结束了相同的结果。
I am not able to see what has changed - except that I have tossed the code inside a new object. I have tried both to do the initialisation in init and in run, but I end up with the same result.
(完整的脚本可在 hhv3.sickel.net/b/storedata.py
和 hhv3.sickel.net/b/storedaemon的.py
)
推荐答案
在你的应用程序的系统守护进程,所有的文件处理程序关闭除标准输入,标准错误和标准输出。这包括的/ dev /日志
,然后失败与FD的错误(所以它看起来像这样无关与串行FD,而是和处理程序的连接插座)。
During the daemonization of your app, all file handlers are closed except stdin, stderr and stdout. This includes the connection to /dev/log
, which then fails with the fd error (so it looks like this has nothing to do with the serial fd, but instead with the handler's socket).
您需要或者本FD添加到排除列表:
You need either to add this FD to the exclusion list:
class App():
def __init__(self):
...
self.files_preserve = [handler.socket]
...
或者,设置处理程序的守护进程分叉后:
Or alternatively, set up the handler after the daemon process forked:
class App():
def run(self):
handler = logging.handlers.SysLogHandler(address = '/dev/log')
my_logger.addHandler(handler)
my_logger.debug(appname+': Starting up storedata')
...
这两个版本在我的测试中运行良好。
Both version ran fine during my tests.
这篇关于串口不重写Python的code工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!