Although i am specyfing a variable as global
inside a function like this:
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) + '/'
And then i import the function and then run it in the Python UI (Windows) like this:
>>> from df import SECdownload
>>> SECdownload(2012,4)
Why when i type the variable target_dir
in the Shell i get:
>>> target_dir
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
target_dir
NameError: name 'target_dir' is not defined
How is this possible when i clearly state inside the function that the variable
is global
?
由于以下这一行,您无法处理全局变量的代码:
return edgarFilingsFeed
Functions work in the context in which they were created. That is, any globals they work with are local to the module that the function was created in.
For instance:
m.py:
def a(val):
global x
x = val
main.py
from m import a
a(10)
import m
print(m.x)
produces 10
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.