0

I have searched the stackoverflow and wasn't able to find this. I have noticed something I can not wrap my head around. When run as normal python script import works ok, but when run from Django shell it behaves weird, needs to set import as global to be seen.

You can reproduce it like this. Make a file test.py in folder with manage.py. Code you can test with is this.

This doesn't work, code of test.py:

 #!/usr/bin/env python3
import chardet


class LoadList():

    def __init__(self):
        self.email_list_path = '/home/omer/test.csv'

    @staticmethod
    def check_file_encoding(file_to_check):
        encoding = chardet.detect(open(file_to_check, "rb").read())
        return encoding

    def get_encoding(self):
        return self.check_file_encoding(self.email_list_path)['encoding']


print(LoadList().get_encoding())

This works ok when chardet set as global inside test.py file:

#!/usr/bin/env python3
import chardet


class LoadList():

    def __init__(self):
        self.email_list_path = '/home/omer/test.csv'

    @staticmethod
    def check_file_encoding(file_to_check):
        global chardet
        encoding = chardet.detect(open(file_to_check, "rb").read())
        return encoding

    def get_encoding(self):
        return self.check_file_encoding(self.email_list_path)['encoding']


print(LoadList().get_encoding())

First run is without global chardet and you can see the error. Second run is with global chardet set and you can see it works ok. enter image description here

What is going on and can someone explain this to me? Why it isn't seen until set as global?

1 Answer 1

0

Piping a file into shell is the same as piping it into the python command. It's not the same as running the file with python test.py. I suspect it's something to do with the way the the newlines are interpreted as to how the file is really parsed, but don't have time to check.

Instead of this approach I'd recommend you write a custom management command.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.