在这种情况下可以使用全局变量吗?

时间:2018-02-10 00:12:09

标签: python

所以我有一个连续运行的预定脚本。这是调度程序脚本:

import os
import schedule
import time

os.chdir("B:\Scheduled_Scripts")

def DSE():
    print("")
    print(colors.OK + '***DSE***')
    try:
        start = time.time()
        exec(open('B:/Scheduled_Scripts/DSE.py').read())
        print("")
        print(colors.OK + "DSE completed successfully in", round(time.time() - start, 2), 'seconds!')
    except Exception as e:
        logger.error(e)
        print(colors.WARNING + 'An error has occurred in DSE.py. It was a ' + type(e).__name__ + '-' + format(e))
        print('')
        pass

现在它将运行我的DSE.py脚本,在某一点上我最终使用pandas sql查询。然后我创建一个函数来开始映射一些值。

query = '''(my query)'''
price_levels = pd.read_sql_query(query, KORE, params={my_params})

def get_price_level(seat):
    pl = price_levels[price_levels['seatsid'] == seat]['priceleveldesc'].values()
    return str(pl)

DSE_avs['priceleveldesc'] = DSE_avs['seatsid'].map(get_price_level)

问题是现在它不会识别'price_levels'是在函数中定义的。如果我将price_levels设置为全局变量,那将是多么的不满?

1 个答案:

答案 0 :(得分:0)

使用lambdaprice_levels作为参数传递。

query = '''(my query)'''
price_levels = pd.read_sql_query(query, KORE, params={my_params})

def get_price_level(seat, price_levels):
    pl = price_levels[price_levels['seatsid'] == seat]['priceleveldesc'].values()
    return str(pl)

DSE_avs['priceleveldesc'] = DSE_avs['seatsid'].map(lambda s: get_price_level(s, price_levels))