[英]Python cannot see global variable
虽然我在这样的函数中指定一个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
variable
时,这怎么可能?
由于以下这一行,您无法处理全局变量的代码:
return edgarFilingsFeed
函数在创建它们的上下文中工作。 也就是说,他们使用的所有全局变量都在创建该函数的模块本地。
例如:
m.py:
def a(val):
global x
x = val
main.py
from m import a
a(10)
import m
print(m.x)
产生10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.