Fabric, can't get default locale on django

2019-09-14 21:25发布

问题:

I have the following django management command:

fabrictest.py

from django.core.management.base import NoArgsCommand
import locale

class Command(NoArgsCommand):

    def handle_noargs(self, **options):
        print locale.getdefaultlocale()

Which I can run locally:

$ /home/user/env/bin/python manage.py fabrictest
('en_US', 'UTF-8')

However, when I run the command remotely using the following fabric task

@task
def test():
    # run manage.py using the python bin from the virtualenv

    with cd(env.project_root):
        run("/home/user/env/bin/python manage.py fabrictest")

I get the following output

[server] Executing task 'test'
[server] run: /home/user/env/bin/python manage.py fabrictest
[server] out: (None, None)

Why do I get (None, None) instead of ('en_US', 'UTF-8')?. This generates errors for some other management scritps (namely, syncdb when creating the superuser).

回答1:

Looking at this question it seems like those are picked up environment variables.

You could export them manually, either in the run() or with a prefix() context manager. You may also try setting pty to False in the run().



回答2:

From the docs:

According to POSIX, a program which has not called setlocale(LC_ALL, "") runs using the portable 'C' locale. Calling setlocale(LC_ALL, "") lets it use the default locale as defined by the LANG variable. Since we don't want to interfere with the current locale setting we thus emulate the behavior in the way described above...

...code and encoding can be None in case the values cannot be determined.

If you program can't run using the 'C' locale then call setlocale() and/or set appropriate environment variables e.g., LANG.