2012-07-13 126 views
2

我創建的程序將用於解析xml文件並將其解析數據放入數據庫中。雖然我的代碼現在很好,而且跑步,我的教練在我的代碼中的註釋,順便說一句,這是我的代碼:在python中聲明一個函數中的全局變量

import os 
import time 
import MySQLdb 
import ConfigParser 
import elementtree.ElementTree as ET 


def update_database(article_code, date_received, s100rsd, remark_text, db): 
    cur = db.cursor() 
    try: 
     cur_query = cur.execute("""INSERT INTO tblS100CurrentListing """ 
           """(article_Code, dateReceived, s100RSD, remarks) VALUES (%s, %s, %s, %s) """ 
           """ON DUPLICATE KEY UPDATE revisedRSD = %s, remarks = %s """, 
           (article_code, date_received, s100rsd, remark_text, s100rsd, remark_text)) 
     db.commit() 
    except MySQLdb.Error, e: 
     print "An error has been passed %s" %e 
     db.rollback 
    rows_affected = cur.rowcount 
    if rows_affected > 0: 
     print "Changes made in the database" 
    else: 
     print "Nothing is change in the database" 


def parse_xml(source_path, xml_file): 
    # Alvin: !!! globals? 
    global article_code 
    global date_received 
    global s100rsd 
    global remark_text 
    article_code = xml_file.split('.')[0] 
    tree = ET.parse(xml_file) 
    root = tree.getroot() 
    order = root.find('order') 
    order_time = order.find('time') 
    year = order_time.attrib['yr'] 
    month = order_time.attrib['month'] 
    day = order_time.attrib['day'] 
    hour = order_time.attrib['hr'] 
    min = order_time.attrib['min'] 
    sec = order_time.attrib['sec'] 
    date_received = year + month + day + hour + min + sec 
    due_date = order.find('due-date') 
    due_date_time = due_date.find('time') 
    yr = due_date_time.attrib['yr'] 
    month = due_date_time.attrib['month'] 
    day = due_date_time.attrib['day'] 
    s100rsd = "%s-%s-%s" %(yr, month, day) 
    item_info = order.find('item-info') 
    item_remarks = item_info.find('item-remarks') 
    item_remark_list = item_remarks.findall('item-remark') 
    item_remark_len = len(item_remark_list) - 1 
    item_remark = item_remark_list[item_remark_len] 
    remark = item_remark.find('remark') 
    remark_text = remark.text 


def main(): 
    config = ConfigParser.ConfigParser() 
    config.readfp(open('part4b.ini')) 
    server = config.get('main', 'Server') 
    port = config.get('main', 'Port') 
    port = int(port) 
    schema = config.get('main', 'Schema') 
    table = config.get('main', 'Table') 
    user = config.get('main', 'User') 
    password = config.get('main', 'Password') 
    source_path = config.get('main', 'filepath') 

    db = MySQLdb.connect(server, user, password, schema, port) 
    xml_list = os.listdir(source_path) 
    for xml_file in xml_list: 
     if xml_file.endswith('.xml'): 
      parse_xml(source_path, xml_file) 
      update_database(article_code, date_received, s100rsd, remark_text, db) 

    db.close() 

    print "This will close after 2 seconds . ." 
    time.sleep(2) 


if __name__ == '__main__': 
    main() 

在parse_xml功能,他不想讓我在它使用全局變量。我怎樣才能在我的主要使用這些變量沒有聲明它爲全局變量?

感謝您的幫助。

回答

4

從函數返回他們

return article_code, date_received, s100rsd, remark_text 

這是真的返回一個包含4項

你可以在另一端這樣

article_code, date_received, s100rsd, remark_text = parse_xml(...) 
提取它們一個元組
+2

進一步就此更換......如果你使用這些值作爲屬性返回一個對象可能是整潔。 – 2012-07-13 06:33:05

+0

謝謝你。有時我的問題非常明顯,對於新手而言很抱歉。再次感謝! – neo 2012-07-13 06:42:11

+1

@MichaelAnderson的確如此。一個'namedtuple'是製作這樣一個輕量級對象的好方法 – 2012-07-13 06:42:34

0

你通常會做的是返回一個「數據對象」,即一個對象包含寧相關數據:

class dto(object): 
    def __init__(self, **kw): 
    self.__dict__.update(kw) 

def parse_xml(source_path, xml_file): 
    data = dto(article_code = '1234', 
       date_received = 'abc', 
       s100rsd = '%s-%s-%s' % ('ab', 'cd', 'efgh'), 
       remark_text = 'eh5jhe5') 
    return data 

data = parse_xml('../', 'abc.xml') 

就用data.data_received如你所期望。

另外請注意,您的線條

os.listdir(source_path) 
... 
if xml_file.endswith('.xml'): 

是真正的好與

import glob 
xml_list = glob.glob(os.path.join(source_path, '*.xml'))