如何执行存储在互联网上的python脚本? [英] How do I execute a python script that is stored on the internet?

查看:127
本文介绍了如何执行存储在互联网上的python脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python 2.4编写一个程序,该程序可以从Internet导入脚本并执行它们,因此作者可以更改脚本,而用户不必重新下载脚本.

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)

在功能之外,下载脚本后,脚本将正确执行.但是,即使已经在脚本中以及在execfile之前导入了名称,尝试运行loadScript函数也会在脚本中出现名称错误.

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?

很抱歉,是否曾经回答过这个问题,但是我似乎找不到其他人试图通过从互联网下载python脚本来运行python脚本.

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.

编辑:暂时将globals作为另一个参数添加到execfile似乎已经解决了该问题.我不知道以后是否还会发生其他问题.

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.

推荐答案

在R中,您可以简单地"source(url)".这是到目前为止我在python中找到的最接近的东西:

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)

这篇关于如何执行存储在互联网上的python脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆