问题
I was wondering why I can't access the variable: "variable_for_raw_data" after the function ends. The code is like this:
def htmlfrom(Website_URL):
import urllib.request
response = urllib.request.urlopen(Website_URL)
variable_for_raw_data =(input("What will this data be saved as: "))
global variable_for_raw_data
variable_for_raw_data = response.read()
Now why can't I access the variable "variable_for_raw_data" after the functions ends?
Things to note:
Python 3.3 urllib NOT urllib2
回答1:
It looks like you're trying to dynamically create variables, I would imagine that your code looks something like this.
def htmlfrom(website_url):
import urllib.request
response = urllib.request.urlopen(website_url)
variable_for_raw_data =(input("What will this data be saved as: "))
global variable_for_raw_data
variable_for_raw_data = response.read()
if __name__ == "__main__":
htmlfrom("www.stackoverflow.com")
#html_stackoverflow is never created it is the value
#of variable_for_raw_data before variable_for_raw_data
#is overridden by response.read()
#entering information into input doesn't create a variable
print(html_stackoverflow)
Here's how I would do it:
import urllib.request
def htmlfrom(website_url):
'''
docstrings
'''
response = urllib.request.urlopen(website_url)
variable_for_raw_data = response.read()
return variable_for_raw_data
if __name__ == "__main__":
file_name = input("What will this data be saved as: ")
html_from_website = htmlfrom("www.stackoverflow.com")
with open(file_name, 'w') as f:
f.write(html_from_website)
Explanation
if you have your import statement inside the function it is only accessable inside the function (i.e. other functions can't access it)
import urllib.request
PEP 8 has guidelines on how things should be named in python CamelCase is usually reserved for class names
def htmlfrom(website_url):
'''
docstring
'''
Docstrings are usually a good idea.
Check out this question for more information on the proper use of globals. Based on what I know about your situation I don't think you need to use them.
response = urllib.request.urlopen(website_url)
variable_for_raw_data = response.read()
return variable_for_raw_data
If you don't know about `if name == 'main': you should read up on it.
if __name__ == "__main__":
Don't forget to use meaningful variable names and not override the builtins (i.e. file = "foo.txt" would override the file builtin)
file_name = input("What will this data be saved as: ")
html_from_website = htmlfrom("www.stackoverflow.com")
You can learn more about context managers here
with open(file_name, 'w') as f:
f.write(html_from_website)
An edit using globals()
, FOR WHICH NO USE CASE EXISTS AT ALL.
def htmlfrom(website_url):
import urllib.request
response = urllib.request.urlopen(website_url)
variable_for_raw_data =(input("What will this data be saved as: "))
globals()[variable_for_raw_data] = response.read()
来源:https://stackoverflow.com/questions/15552601/creating-global-variable-in-python-3-from-functions