2017-08-24 43 views
0

這裏的函數訪問一個全局變量是代碼的頂部...我怎麼能在我進口

import sys 
import requests 
import datetime 
import json 
import user_functions 
from time import sleep 
now = datetime.datetime.now() 
import urllib3 
urllib3.disable_warnings() 
requests.packages.urllib3.disable_warnings() 

importgroups = ['staff'] 
key = "" 

在user_functions文件我有一個函數:

def TDactionuser(bcchangess): 
    global key 
    print key 
    global importgroups 
    if bcchangess['primary_affiliation'] not in importgroups: 
     return 

問題的癥結在於,我似乎無法訪問密鑰或導入組變量。我不知道如何解決這個問題。我使用全球性的,而不是全球性的,以及......它說它們沒有被定義。

Traceback (most recent call last): File "./userupload.py", line 66, in user_functions.TDactionuser(bcchangess) File "/TDPROXY/USERIMP/user_functions.py", line 12, in TDactionuser print key NameError: global name 'key' is not defined

任何幫助,這將不勝感激...

+2

「全球」 是指*模塊級*在Python中。 'TDactionuser'的全局作用域是'user_functions'中的頂級作用域,而不是你稱之爲'TDactionuser'的地方。無論如何,你都不應該使用全局變量。這是意大利麪代碼開始的一個很好的例子。 **只需傳遞並返回參數**。 –

+0

如果試圖從另一個文件訪問變量,則需要「導入」它 – Mangohero1

+0

但是,在將函數導入到file1 – BostonMacOSX

回答

1

你可以這樣做:

def TDactionuser(bcchangess): 
    from __main__ import key 
    from __main__ import importgroups 
    print key 
    if bcchangess['primary_affiliation'] not in importgroups: 
     return 

但通常這是一個糟糕的設計