2

I'm hitting a very weird issue.

Edit: Adding full details:

virtualenv -p python3 testenv
cd testenv
source bin/activate
django-admin startproject blah
cd blah
mkdir modules
vi modules/stash.py
pip install django
pip install stashy
python manage.py shell < modules/stash.py

I have a script that sync data to populate a database:

$ cat modules/stash.py
import stashy
class SyncProject:
    def __init__(self, endpo, user, passw):
        import stashy
        self.stash = stashy.connect(endpo, user, passw)

access = SyncProject("http://localhost", "test", "test" )

I run my script with:

$ python  manage.py shell < modules/stash.py

The weirdness is that if I don't put the second import stashy, it doesn't work:

NameError: name 'stashy' is not defined

From the bit of Python I did a long time ago, that seems very unexpected and forces me to add import in every single method... Not sure if there is something wrong in how I import my dependencies or the way I run the script...

Edit: more details, the error message:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/[PATH]/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/[PATH]/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/[PATH]/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/[PATH]/python3.6/site-packages/django/core/management/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/[PATH]/python3.6/site-packages/django/core/management/commands/shell.py", line 92, in handle
    exec(sys.stdin.read())
  File "<string>", line 6, in <module>
  File "<string>", line 4, in __init__
NameError: name 'stashy' is not defined
parsley72
  • 8,449
  • 8
  • 65
  • 98
ffyns
  • 479
  • 5
  • 9

2 Answers2

1

I tracked down the behavior to line 92 in the Django project: exec(sys.stdin.read()).

This causes your first import stashy to be scoped to the Command class. If instead the line was exec(sys.stdin.read(),globals()) then you would not have this unexpected behavior. This change to Django would also remove the current bug/difference in behavior between code redirected to stdin and code manually typed into the Django shell/Python REPL.

XXXX
  • 161
  • 1
0

I have reproduce same issue at my end. I tried as per steps mentioned in question. I got the same issue.

After that I have install django==1.10. And it works. Check it works for you.

yogesh10
  • 319
  • 2
  • 12