我遇到了一个非常奇怪的问题。
编辑:添加完整的详细信息:
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
我有一个脚本可以同步数据来填充数据库:
$ 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" )
我用:
运行我的脚本$ python manage.py shell < modules/stash.py
奇怪的是,如果我不放第二个import stashy
,它就不起作用了:
NameError: name 'stashy' is not defined
从我很久以前做过的Python中,这看起来非常意外,并迫使我在每个方法中添加导入...不确定导入依赖关系或运行方式是否有问题脚本......
编辑:更多详细信息,错误消息:
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
答案 0 :(得分:1)
我在Django项目中追踪到line 92的行为:exec(sys.stdin.read())
。
这会导致您的第一个import stashy
范围限定为Command
类。如果该行是exec(sys.stdin.read(),globals())
,那么您将不会遇到此意外行为。对Django的这一更改还将消除重定向到stdin的代码与手动输入到Django shell / Python REPL中的代码之间的行为错误/差异。
答案 1 :(得分:0)
包中的connect
函数只是一个包装器(如下所示)
__version__ = "0.1"
from .client import Stash
def connect(url, username, password, verify=True):
"""Connect to a Stash instance given a username and password.
This is only recommended via SSL. If you need are using
self-signed certificates, you can use verify=False to ignore SSL
verifcation.
"""
return Stash(url, username, password, verify=verify)
__all__ = ['connect']
您可以尝试通过提取Stash对象本身来绕过错误:
from stashy.client import Stash
class SyncProject:
def __init__(self, endpo, user, passw):
self.stash = Stash(endpo, user, passw, verify=True)
答案 2 :(得分:0)
我在最后重现了同样的问题。我按照提到的步骤尝试了。我遇到了同样的问题。
之后我安装了django == 1.10。它有效。检查它是否适合你。