【问题标题】:python - IOError: [Errno 2] - Can permissions cause an IOError Errno 2 when using open()python - IOError: [Errno 2] - 使用 open() 时权限会导致 IOError Errno 2
【发布时间】:2014-08-08 15:05:56
【问题描述】:

我有一个 python 脚本,它创建一个 tar 文件,将文件移动到 tar 文件中,然后删除它们。

我可以毫无问题地手动运行脚本。但是当它从 cron 运行时,它会失败:

IOError: [Errno 2] No such file or directory: 'directory/filename_2014-08-08.tar.gz'

在这种情况下,文件权限问题是否可能引发 Errno 2?

以下是相关代码:

fname = directory + "_" + str(strftime("%Y-%m-%d_", localtime()))+".tar.gz"
tar = tarfile.open(archived_model_dir + fname.replace("/",""), "w:gz") # this line raises error
for input_file in os.listdir(directory):
    if os.path.isfile(directory + input_file):
        if not input_file.endswith('.pyc'):  
            tar.add(directory + input_file) # archive all but .pyc
        os.remove(directory + input_file)
    elif os.path.exists(directory + input_file): # delete subfolders 
        shutil.rmtree(directory + input_file)

tar 文件是使用 tarfile.open() 创建的。如果由我的用户运行,它再次成功,但从 cron 运行时失败并出现上述错误。我想知道运行 cron 的用户是否没有适当的权限来创建 tar 文件,这可能会引发 Errno 2?

我将使用用户权限进行一些测试,看看是否是这种情况,但也许某些 SO 用户可以提供更快的答案?

谢谢!

【问题讨论】:

    标签: python linux cron


    【解决方案1】:

    检查当前工作目录。这可能是错误的原因。

    import os
    print(os.getcwd())
    

    如果这是问题所在,请将所有路径设为绝对路径:

    fname = os.path.join('/path/to/directory/', directory + "_" + .... + ".tar.gz")
    

    或在运行脚本之前更改目录。 (在 Python 脚本或 crontab 条目中)

    import os
    os.chdir('/path/to/directory')
    

    【讨论】:

    • 这绝对是一个更有可能的解释。会看看
    • 就是这样。将 cd /script/dir/ 添加到 crontab 并且它可以工作。