1

我遇到了 web2py 的问题。我在 modules 文件夹中有一个名为 defVals.txt 的文本文件。open("defVals.txt")我尝试使用(在与 defVals.txt 相同的目录中的模块中)读取它,但我收到错误:

Traceback (most recent call last):
 File "/home/jordan/web2py/gluon/restricted.py", line 212, in restricted
   exec ccode in environment
File "/home/jordan/web2py/applications/randommotif/controllers/default.py", line 67,     in <module>
 File "/home/jordan/web2py/gluon/globals.py", line 188, in <lambda>
self._caller = lambda f: f()
File "/home/jordan/web2py/applications/randommotif/controllers/default.py", line 13, in index
  defaultData = parse('defVals.txt')
File "applications/randommotif/modules/defaultValParser.py", line 6, in parse
 lines = open(fileName)
IOError: [Errno 2] No such file or directory: 'defVals.txt'

我究竟做错了什么?我应该在哪里放置 defVals.txt

我正在使用 Ubuntu 12.10

谢谢,

约旦

更新:

这是 defaultValParser.py 的源代码:

import itertools
import string
import os
from gluon import *
from gluon.custom_import import track_changes; track_changes(True)

#this returns a dictionary with the variables in it.
def parse(fileName):
    moduleDir = os.path.dirname(os.path.abspath('defaultValParser.py'))
    filePath = os.path.join(moduleDir, fileName)
    lines = open(filePath, 'r')
    #remove lines that are comments. Be sure to remove whitespace in the beginning and end of line
    real = filter(lambda x: (x.strip())[0:2] != '//', lines)
    parts = (''.join(list(itertools.chain(*real)))).split("<>")
    names = map(lambda x: (x.split('=')[0]).strip(), parts)
    values = map(lambda x: eval(x.split('=')[1]), parts)
    return dict(zip(names, values))

如果我导入它并从终端调用它(假设我注释掉胶子导入)它工作正常,但如果我从 web2py 控制器调用它,它会完全失败:

Traceback (most recent call last):
  File "/home/jordan/web2py/gluon/restricted.py", line 212, in restricted
   exec ccode in environment
  File "/home/jordan/web2py/applications/randommotif/controllers/default.py", line 71, in <module>
  File "/home/jordan/web2py/gluon/globals.py", line 188, in <lambda>
  self._caller = lambda f: f()
  File "/home/jordan/web2py/applications/randommotif/controllers/default.py", line 17, in index
  defaultData = parse('defVals.txt')
  File "applications/randommotif/modules/defaultValParser.py", line 6, in parse
 IOError: [Errno 2] No such file or directory: 'defVals.txt'
4

1 回答 1

2

使用基于__file__模块路径的绝对路径:

moduledir = os.path.dirname(os.path.abspath('__file__'))

# ..
defaultData = parse(os.path.join(moduledir, 'defVals.txt'))

__file__是当前模块的文件名,使用.dirname()of 可以为您提供模块所在的目录。我曾经.abspath()确保您始终拥有模块文件的绝对路径,避免出现一些您可能遇到的边缘情况。

moduledir是您模块中的全局变量。

于 2012-12-23T22:17:18.283 回答