微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – 在守护进程中失去与postgresql的连接

我正在重写一个python脚本来存储postgresql数据库中的arduino数据,希望使用python-daemon将其作为deamon运行.原始脚本工作正常,但在deamon中,我无法写入数据库.第一次尝试最终结果是:

<class 'psycopg2.DatabaseError'>, DatabaseError('SSL SYSCALL error: EOF detected\n'

然后:

<class 'psycopg2.InterfaceError'>, InterfaceError('cursor already closed',)

在工作脚本中,我做:

connstring="dbname='"+dbdatabase+"' user='"+dbusername+"' host='"+dbhost+"'password='"+dbpassword+"'"
try:
  conn = psycopg2.connect(connstring)
  cur=conn.cursor()
except:
  my_logger.critical(appname+": Unable to connect to the database")
  sys.exit(2)
sql="insert into measure (sensorid,typeid,value) VALUES(%s,%s,%s)"
< more to set up serialport, logging and so on>
while 1:
  < fetch a data set and split it to a list >
  for (i,val) in enumerate measures:
     try:
       cur.execute(sql,(sensors[i],typeid[i],val)) 
       conn.commit()
     except:
       self.logger.error(appname+": error 106 :"+str(sys.exc_info()))

我有一种感觉,这可能是我最初使用串行连接Serial port does not work in rewritten Python code的一些问题,所以我试图摆弄files_preserve,做:

self.files_preserve=range(daemon.daemon.get_maximum_file_descriptors()+1)

据我所知,应该保持打开所有文件句柄,但无济于事.

在守护进程中,我首先尝试将数据库连接设置为__init__中的属性,i. Ë:

self.conn = psycopg2.connect(connstring)
self.cur=conn.cursor()

然后在run方法中执行插入操作.我还尝试在run方法的顶部创建连接,甚至将其设置为全局对象,但在所有情况下,似乎都在扼杀数据库连接.有线索吗? (或者在哪里找到守护程序模块的某些文档(源代码除外)的线索?)

守护进程和数据库都在使用python 2.7和postgresql8.4`的debian linux系统上运行.

解决方法:

据我所知,daemon.runner在forking之前工作,然后执行你提供的守护进程应用程序的run方法.

这意味着您在一个进程中创建数据库连接,但随后尝试在分叉进程中使用它,psycopg2 doesn’t like

libpq connections shouldn’t be used by a forked processes, so […] make sure to create the connections after the fork.

在这种情况下,这意味着:将您对psycopg2.connect的调用移动到run方法中.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐