5

I have a file test.py with this code:

def getTrue():
    return True

def getSome():
    return getTrue()

somevar = getSome()
print(somevar)

When I run the script using

python manage.py shell < test.py

I get the error

NameError: name 'getTrue' is not defined

After adding

import unicodedata

To the top of the file and then try using some function from unicodedata I get this error:

NameError: name 'unicodedata' is not defined

I don't see how the answer to the question that my question is marked as a possible duplicate of is answering this part.

When I run the file normally with

python3 /path/to/file/test.py 

There is no problem and True is printed like expected.

Any idea what is going on?

DevB2F
  • 4,674
  • 4
  • 36
  • 60
  • When you do this, the script internally calls `exec()` on the code in `test.py`. This will fail in Python 3 - see [this answer](https://stackoverflow.com/questions/24733831/using-a-function-defined-in-an-execed-string-in-python-3) for a detailed explanation of why. – solarissmoke Jun 29 '18 at 03:11
  • 1
    Possible duplicate of [Using a function defined in an exec'ed string in Python 3](https://stackoverflow.com/questions/24733831/using-a-function-defined-in-an-execed-string-in-python-3) – solarissmoke Jun 29 '18 at 03:15

1 Answers1

0

Piping a script into a Django shell is like copying & pasting it into the shell. The "smart" auto-indentation logic of the shell often gets confused and over-ident the pasted code.

Try installing the latest iPython, which has this issue resolved. Django will use iPython as the shell if it's installed.

blhsing
  • 91,368
  • 6
  • 71
  • 106