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

Mor*_*kel 4 python linux postgresql daemon psycopg2

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

<class 'psycopg2.DatabaseError'>, DatabaseError('SSL SYSCALL error: EOF detected\n'
Run Code Online (Sandbox Code Playgroud)

然后:

<class 'psycopg2.InterfaceError'>, InterfaceError('cursor already closed',)
Run Code Online (Sandbox Code Playgroud)

在工作脚本中,我做:

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()))
Run Code Online (Sandbox Code Playgroud)

我有一种感觉,这可能是我最初使用串行连接时遇到的一些问题,串口在重写的Python代码中不起作用,所以我试图摆弄files_preserve,做:

self.files_preserve=range(daemon.daemon.get_maximum_file_descriptors()+1)
Run Code Online (Sandbox Code Playgroud)

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

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

self.conn = psycopg2.connect(connstring)
self.cur=conn.cursor()
Run Code Online (Sandbox Code Playgroud)

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

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

mat*_*ata 7

据我所知,它是源代码,daemon.runner通过分叉然后执行run你提供的守护程序应用程序的方法来工作.

这意味着你在一个进程中创建数据库连接,但是然后尝试在分叉进程中使用它,psycopg2 不喜欢:

分叉进程不应使用libpq连接,因此请确保在fork之后创建连接.

在这种情况下,这意味着:将您的呼叫转移psycopg2.connectrun方法中.