TypeError: makedirs() got an unexpected keyword argument 'exists_ok'

Question:

I am learning Django using the book “Lightweight Django”. I’m using Django 1.8. However, I can not run this code. Here is the error message:

enter image description here

The working tree:

enter image description here

build.py

import os
import shutil

from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from django.test.client import Client

def get_pages():
    for name in os.listdir(settings.SITE_PAGES_DIRECTORY):
        if name.endswith('.html'):
            yield name[:-5]

class Command(BaseCommand):
    help = 'Build static site output.'
    leave_locale_alone = True

    def handle(self, *args, **options):
        if os.path.exists(settings.SITE_OUTPUT_DIRECTORY):
            shutil.rmtree(settings.SITE_OUTPUT_DIRECTORY)
        os.mkdir(settings.SITE_OUTPUT_DIRECTORY)
        os.makedirs(settings.STATIC_ROOT, exists_ok=True)
        call_command('collectstatic', interactive=False, clear=True,verbosity=0)
        client = Client()
        for page in get_pages():
            url = reverse('page', kwargs={'slug': page})
            response = client.get(url)
            if page == 'index':
                output_dir = settings.SITE_OUTPUT_DIRECTORY
            else:
                output_dir = os.path.join(settings.SITE_OUTPUT_DIRECTORY, page)
                os.makedirs(output_dir)
            with open(os.path.join(output_dir, 'index.html'), 'wb') as f:
                f.write(response.content)

prototypes.py

import os
import sys
from django.conf import settings


BASE_DIR = os.path.dirname(__file__)


settings.configure(
    DEBUG = True,
    SECRET_KEY= 'qfzf!b1z^5dyk%syiokeg4*2xf%kj68g=o&e8qvd@@(1lj5z8)',
    ROOT_URLCONF='sitebuilder.urls',
    MIDDLEWARE_CLASSES=(),
    INSTALLED_APPS=(
        'django.contrib.staticfiles',
        'sitebuilder',
    ),

    TEMPLATES=(
        {
            'BACKEND':'django.template.backends.django.DjangoTemplates',
            'DIRS':[],
            'APP_DIRS':True,
        },
    ),
    STATIC_URL='/static/',
    SITE_PAGES_DIRECTORY=os.path.join(BASE_DIR,'pages'),
    SITE_OUTPUT_DIRECTORY=os.path.join(BASE_DIR,'_build'),
    STATIC_ROOT=os.path.join(BASE_DIR,'_build','static'),
)





if __name__ == "__main__":
    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)
Asked By: Joe Lin

||

Answers:

You have a typo, it is exist_ok, not exists_ok The correct code should be:

os.makedirs(settings.STATIC_ROOT, exist_ok=True)

However, that won’t work for you either, because exist_ok was added in Python 3.2. You are using Python 2.7, but the book is written for Python 3 (probably 3.4, I’m not certain)

In Python 2.7, you can catch the exception when the directory already exists:

try:
    os.makedirs(settings.STATIC_ROOT)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise

However, I strongly recommend that you switch to Python 3. You’ll come across other problems if you try to write Python 3 code in Python 2.

Answered By: Alasdair

In my case (python 3.9 as part of QGIS 3.20.3 installed with OSGeo4W) error was caused by the presence of two pathlib.py files in the folders:

  1. C:OSGeo4WappsPython39Libsite-packages
  2. C:OSGeo4WappsPython39Lib

After removing duplicate in the C:OSGeo4WappsPython39Libsite-packages the problem was solved.

Answered By: Comrade Che
python3 prototypes.py build

with python prototypes.py build command, it will run by python 2

Answered By: lam vu Nguyen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.