问题
I am using python 2.4 for a program which imports scripts from the internet and executes them so a script could be changed by the author and the user wouldn't have to re-download the script.
This is the part of the program that downloads the script:
def downloadScript(self,script):
myfile=open('#A file path/'+script['name']+'.txt','w')
try:
downloadedScript=urllib.urlopen(script['location']).read()
except:
#raise error
return
myfile.write(downloadedScript)
myfile.close()
def loadScript(self):
if not self.scriptCurrentlyLoaded:
script=self.scripts[self.scroller.listPos]
if script['location']=='None':
#raise error
return
self.downloadScript(script)
myfile=open('#A file path/'+script['name']+'.txt','r')
for line in myfile:
if line.startswith('from') or line.startswith('import'):
exec(line.strip()) #This was added because of the name errors
#being produced but to no affect
myfile.close()
execfile('#A file path/'+script['name']+'.txt')
self.scriptCurrentlyLoaded=True
self.scriptLoaded=script
else:
#raise error
The very odd thing is that when I run
execfile(script path)
outside of the function, after the script has been downloaded, the script is executed correctly. But trying to run the loadScript function raises name errors in the script even though the names have been imported in the script and before the execfile which I find very odd.
So my question is: Am I using a very bad method to download and execute these scripts?
Sorry if this question was answered before but I can't seem to find anyone else who is trying to run python scripts by downloading them from the internet.
Edit: adding globals
as another argument to the execfile
has seemed to fix the problem for now. I don't know if any other problems will occur later though.
回答1:
In R you can simply 'source(url)'. Here's the closest I have found so far in python:
import urllib
(fn,hd) = urllib.urlretrieve('http://host.com/file.py')
execfile(fn)
来源:https://stackoverflow.com/questions/17468616/how-do-i-execute-a-python-script-that-is-stored-on-the-internet