1

我正在将 python 2.4 用于从 Internet 导入脚本并执行它们的程序,以便作者可以更改脚本并且用户不必重新下载脚本。

这是下载脚本的程序部分:

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

非常奇怪的是,当我跑步时

execfile(script path)

在函数之外,下载脚本后,脚本会正确执行。但是尝试运行 loadScript 函数会在脚本中引发名称错误,即使名称已被导入脚本中并且在我觉得很奇怪的 execfile 之前。

所以我的问题是:我是否使用了一种非常糟糕的方法来下载和执行这些脚本?

抱歉,如果这个问题之前得到了回答,但我似乎找不到其他人试图通过从互联网下载它们来运行 python 脚本。

编辑:globals作为另一个参数添加到execfilehas 似乎现在可以解决问题。不过不知道以后会不会出现其他问题。

4

1 回答 1

3

在 R 中,您可以简单地使用 'source(url)'。这是迄今为止我在 python 中找到的最接近的:

import urllib
(fn,hd) = urllib.urlretrieve('http://host.com/file.py')
execfile(fn)
于 2015-09-03T11:26:17.490 回答