虽然我在这样的函数中将变量指定为global
:
def SECdownload(year, month):
import os
from urllib.request import urlopen
root = None
feedFile = None
feedData = None
good_read = False
itemIndex = 0
edgarFilingsFeed = 'http://www.sec.gov/Archives/edgar/monthly/xbrlrss-' + str(year) + '-' + str(month).zfill(2) + '.xml'
return edgarFilingsFeed
#print( edgarFilingsFeed ) #from the slides
if not os.path.exists( "sec/" + str(year) ):
os.makedirs( "sec/" + str(year) )
if not os.path.exists( "sec/" + str(year) + '/' + str(month).zfill(2) ):
os.makedirs( "sec/" + str(year) + '/' + str(month).zfill(2) )
global target_dir
target_dir = "sec/" + str(year) + '/' + str(month).zfill(2) + '/'
然后我导入该函数,然后在Python UI(Windows)中运行它,如下所示:
>>> from df import SECdownload
>>> SECdownload(2012,4)
为什么当我在Shell中输入变量target_dir
时,我得到:
>>> target_dir
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
target_dir
NameError: name 'target_dir' is not defined
当我在variable
global
{{1}}的函数中清楚地说明时,这怎么可能?
答案 0 :(得分:1)
由于这一行,您无法访问处理全局变量的代码:
return edgarFilingsFeed
答案 1 :(得分:1)
函数在创建它们的上下文中起作用。也就是说,它们使用的任何全局变量都是创建函数的模块的本地变量。
例如:
m.py:
def a(val):
global x
x = val
main.py
from m import a
a(10)
import m
print(m.x)
生成10