【问题标题】:python - losing connection to postgresql in daemonpython - 在守护进程中失去与 postgresql 的连接
【发布时间】:2013-04-27 20:45:43
【问题描述】:

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

<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__ 中的属性,即。 e.:

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

然后在run 方法中进行插入。我还尝试在 run 方法的顶部创建连接,甚至将其设置为全局对象,但在所有情况下,似乎都在杀死数据库连接。有什么线索吗? (或者在哪里可以找到守护程序模块的一些文档(除了源代码)的任何线索?)

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

【问题讨论】:

  • 非常感谢您提出这个问题!

标签: python linux postgresql daemon psycopg2


【解决方案1】:

据我所知,daemon.runner 由forking 工作,然后执行您提供的守护程序应用程序的run 方法。

这意味着您在一个进程中创建数据库连接,然后尝试在一个分叉的进程中使用它,其中 psycopg2 doesn't like:

libpq 连接不应由分叉的进程使用,因此[...] 确保在分叉之后创建连接。

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

【讨论】:

  • 两年后你救了我。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2012-06-25
  • 1970-01-01
  • 1970-01-01
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-04
相关资源
最近更新 更多