簡體   English   中英

Python將變量從一個腳本發送到另一個腳本

[英]Python send variable from one script to another

嗨,大家好,我有關於將varable發送到另一個異常腳本的問題。 script1.py:

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()

但這不起作用,您能為我提供一些有關此問題的解決方案嗎?

您不會在腳本之間發送變量。 您將args傳遞給函數...
您可以按以下方式修改腳本:

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)
    ...

試試這個: 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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM