在python

时间:2016-02-03 12:30:51

标签: python python-3.x

我正在运行家庭作业中的代码,其中包含open。麻烦的是,学生被告知不要提交他们给出的数据,并假设我们已经拥有 - 并且open没有查看sys.path

幸运的是,我正在使用Spyder,它允许我选择在初始化控制台时执行的脚本。我想我可以覆盖open,所以我定义了一个新的open函数,它在文件的绝对路径上调用原始的open。但是当有人使用with open(...) as ...时,它就无效了。

我知道这可能不是一件好事,但是我无法查看每个提交的作业中的每个文件,并将调用替换为open ......

我的代码是:

old_open = open

def open(*args, **kwrdargs):
    try:
        res = old_open(*args,**kwrdargs)
        return res
    except:
        args= list(args)
        if ('DS1' in args[0]):
            args[0]=DS1
        elif ('DS2_X' in args[0]):
            args[0] = DS2_X
        elif ('DS2_Y' in args[0]):
            args[0] = DS2_Y
        args = tuple(args)
        res = old_open(*args,**kwrdargs)
        return res

DS1DS2_XDS2_Y包含文件的绝对路径。

执行时:

with open('DS1.data', 'r') as f:

我收到错误:

  

FileNotFoundError:[Errno 2]没有这样的文件或目录:'DS1.data'

使用时:

f=open('DS1.data','r')

作品。

我调试了代码,在使用with时,我的open未被调用,但在使用f=open(...)时,则调用了class Post(AnoterModelMixin, AANotherModelMixin, models.Model): 。为什么会这样?

1 个答案:

答案 0 :(得分:1)

__enter__应该返回一个类似文件的对象,它应该是__exit__和{{1}的那个对象(即下例中的with) }。例如,您可以将f = open(...) with f as ...: do_something() - 语句写为:

open

如果你没有返回open返回的对象,但是文件对象周围有一些自己的包装器,你也必须将它们包装起来。但是根据你的描述,你看起来更像是不需要它,而是你某个地方没有返回文件。您的def open(fname, *args, **kwds): for p in sys.path: fn = build_filename(p, fname) try: return _orig_open(fn, *args, **kwds) except IOerror as e: pass return _orig_open(fn, *args, **kwds) # must return file or rais exception 应该类似于:

$(document).ready(function(){
    var table1=$('.MessagingTable').DataTable({
    }); 

    setInterval(
        function(){
            table1.api().ajax.reload(); 
        }, 
        10000 
    ); 
}); 
相关问题