【问题标题】:Django: No such file or directoryDjango:没有这样的文件或目录
【发布时间】:2016-02-15 13:18:18
【问题描述】:

我有一个过程可以扫描磁带库并查找已过期的介质,以便在将磁带发送到异地保管库之前将其移除并重新使用。 (我们有一些 7 天的政策,永远不会离开现场。)这个过程大约需要 20 分钟才能运行,所以我不希望它在加载/刷新页面时按需运行。相反,我设置了一个 django-cron 作业(我知道我可以在 Linux cron 中完成此操作,但希望项目尽可能独立)来运行扫描,并在 /tmp 中创建一个文件。我已经验证这可行——从今天早上的执行开始,该文件存在于 /tmp 中。我遇到的问题是,现在我想在我的网页上显示那些过期(临时)媒体的列表,但脚本说它找不到文件。创建文件时,我使用绝对文件名“/tmp/scratch.2015-11-13.out”(例如),但这是我在浏览器中遇到的错误:

IOError at /
[Errno 2] No such file or directory: '/tmp/corpscratch.2015-11-13.out'

我的假设是这是一个“网络根”问题,但我就是想不通。我尝试将文件复制到 django 中配置的 /static/ 和 /media/ 目录,甚至复制到 django 根目录和项目根目录,但似乎没有任何效果。当它说找不到 /tmp/file 时,它​​到底在哪里寻找?

def sample():
    """ Just testing """
    today = datetime.date.today()   #format 2015-11-31
    inputfile = "/tmp/corpscratch.%s.out" % str(today)
    with open(inputfile) as fh:         # This is the line reporting the error
        lines = [line.strip('\n') for line in fh]
    print(lines)

print 语句用于在 shell 中进行测试(我可能会补充),但浏览器给出了错误。 该文件确实存在:

$ ls /tmp/corpscratch.2015-11-13.out
/tmp/corpscratch.2015-11-13.out

谢谢。

编辑:弄错了,在 python shell 中也不起作用。正在考虑以前的问题。

【问题讨论】:

    标签: django


    【解决方案1】:

    改用这个:

    today = datetime.datetime.today().date()
    inputfile = "/tmp/corpscratch.%s.out" % str(today)
    

    或者:

    today = datetime.datetime.today().strftime('%Y-%m-%d')
    inputfile = "/tmp/corpscratch.%s.out" % today # No need to use str()
    

    看看区别:

    >>> str(datetime.datetime.today().date())
    '2015-11-13'
    
    >>> str(datetime.datetime.today())
    '2015-11-13 15:56:19.578569'
    

    【讨论】:

    • 这并不能解决我的问题。我使用的是 datetime.date,而不是 datetime.datetime,所以生成的字符串匹配。 (2015-11-13)。
    【解决方案2】:

    我最终在别处找到了这个:

    today = datetime.date.today()    #format 2015-11-31
    inputfilename = "tmp/corpscratch.%s.out" % str(today)
    inputfile = os.path.join(settings.PROJECT_ROOT, inputfilename)
    

    使用 settings.py 包含以下内容:

    PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
    

    彻底解决了我的问题。

    【讨论】:

      猜你喜欢
      • 2014-11-17
      • 1970-01-01
      • 2021-06-24
      • 2014-01-08
      • 2019-01-22
      • 1970-01-01
      • 2015-02-20
      • 1970-01-01
      相关资源
      最近更新 更多