2014-01-07 143 views
1

嗨,大家好,我對將異步發送給其他腳本有疑問。 script1.py:Python將變量從一個腳本發送到另一個腳本

def main(): 

    conn = None 

    try: 
     logging.basicConfig(level=logging.DEBUG, filename='{}'.format(error_log)) 

     try: 
     #Define our connection string 
      conn_string = ("host=x.x.x.x dbname=xxx user=xxx password=xxx") 

      # Get a connection 
      conn = psycopg2.connect(conn_string) 

      # conn.cursor will return a cursor object 
      cursor = conn.cursor() 
      print "Connected to PostgreSQL!\n" 



      root = open('x','rb').read() 
      p = root 
      # Cursor insert into PostgreSQL XML as string 
      cursor.execute("SELECT epg_insert_doc_xml_3(%s)",[str(p)]) 
      conn.commit() 

     except psycopg2.DatabaseError, e: 

      if conn: 
       conn.rollback() 
       print 'Error %s' % e 
          var_x = 'Send some variable %s'% e 
       logging.exception("Failed to process Datatbase error! %s" % e) 
       sys.exit(1) 

    except: 

     logging.exception("Failed to process Datatbase error! %s"% current_time) 

    finally: 

      if conn: 
       conn.close() 

if __name__ == "__main__": 

    main() 

我想從這個腳本發送到var_x這個腳本: script2.py

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
import smtplib 
import time 
import pickle 
from script1 import * 

current_time = time.strftime("%Y/%m/%d %H:%M", time.localtime()) 

var = var_x 

f = '{} %s'.format(var_x) % current_time 

class sendMail: 

    def sendMessage(self): 
     self.server = smtplib.SMTP('x', 25) 
     self.server.login("x", "x") 
     msg = "Opis greške:\n %s" % f 
     self.server.sendmail("x", "x", msg) 

send = sendMail() 
send.sendMessage() 

但這不工作,你可以幫我對這個問題的一些解決方案。

+0

你想要做什麼做什麼,發送數據到一個正在運行的'script2'或者用參數執行'script2'? – luk32

+0

是如果腳本1中出現異常,則調用script2.py併發送參數var_x。 –

+0

哪個版本的python? 3好嗎? – luk32

回答

2

試試這個:execfile("script2.py", {"var_x": var_x})

>>> help(execfile) 
execfile(...) 
    execfile(filename[, globals[, locals]]) 

    Read and execute a Python script from a file. 
    The globals and locals are dictionaries, defaulting to the current 
    globals and locals. If only globals is given, locals defaults to it. 
+0

thx男人,它的工作原理:D –

3

你不從腳本變量發送到腳本。你傳遞參數傳遞給函數...
您可以修改腳本如下:

script2.py

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
import smtplib 
import time 

class Mail: 
    def send(self, var_x): 
     current_time = time.strftime("%Y/%m/%d %H:%M", time.localtime()) 
     f = '{} %s'.format(var_x) % current_time 
     self.server = smtplib.SMTP('x', 25) 
     self.server.login("x", "x") 
     msg = "Opis greške:\n %s" % f 
     self.server.sendmail("x", "x", msg) 

script1.py

from script1 import Mail 

def main(): 
    mail = Mail() 
    ... 
    mail.send(var_x) 
    ... 
+0

thx爲答案! –

相關問題