为什么我的 python 不将当前工作目录添加到路径中?
我不断看到网站提到您执行“python”的目录被添加到 python 路径中。例如 http://www.stereoplex.com/blog/understand-imports- and-pythonpath,作者 cd 到 /tmp 文件夹,然后执行“print(sys.path)”,你瞧,/tmp 文件夹出现在路径列表中。这是我在我的系统上尝试这个(安装了 2.6.6):
示例结构:
app/
mymodule.py
inner_folder/
myscript.py
在 myscript.py 中包含以下行:
import mymodule.py
我做了什么:
cd app
python inner_folder/myscript.py # ImportError
由于我从 app/ 目录执行解释器,不应该 'app'添加到python路径中?这就是我读过的很多文档都指定的行为应该是这样的。
请赐教!
(我已经通过手动将我想要的文件夹添加到环境中来临时解决了这个问题,但不想永远依赖它。由于许多网站都说可以做到这一点,所以我想为自己重现它)
I keep seeing sites mentioning that the directory that you execute 'python ' get added to the python path. For example on http://www.stereoplex.com/blog/understanding-imports-and-pythonpath, the author cd's to the /tmp folder then does 'print(sys.path)' and lo and behold, the /tmp folder appears in the path list. Here is me trying this out on my system (with 2.6.6 installed):
example structure:
app/
mymodule.py
inner_folder/
myscript.py
in myscript.py contains the line:
import mymodule.py
what I did:
cd app
python inner_folder/myscript.py # ImportError
Since I am executing the interpreter from the app/ directory, shouldn't 'app' be added to the python path? This is how a lot of the docs I have been reading have specified the behaviour should be.
Please enlighten!
(I have temporarily solved this by manually adding the folder I want into the environment but don't want to rely on that forever. Since many sites say this can be done, I'd like to reproduce it for myself)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
添加的是脚本的目录,而不是当前目录。如果将
inner_folder/
转换为包,则可以使用python -m inner_folder.myscript
来运行脚本,同时添加app/
到sys.path
。It is the script's directory that is added, not the current directory. If you turn
inner_folder/
into a package then you can usepython -m inner_folder.myscript
in order to run the script while havingapp/
added tosys.path
.无论当前目录是否在 sys.path 中,导入语句通常如下所示:
您编写的代码如下所示:
Whether or not the current directory is in
sys.path
, import statements usually look like:The code you wrote looks like:
检查模块目录不为空。这可能听起来很愚蠢,但就我而言,我没有意识到它是一个 git 子模块并且没有递归克隆。
Check that the module directory is not empty. That may sound stupid, but in my case I hadn't realised that it was a git submodule and hadn't cloned recursively.
根据我的经验,最干净的解决方案是添加一个像这样的结构的
setup.py
:并且
setup.py
的内容如下所示:通过 python 安装后setup.pydevelop,在
myscript.py
中,你可以像这样导入mymodule:或者如果你想做
import mymodule
,你可以移动setup.py 里面
app/
,与mymodule.py
相同的目录,并将packages=['app']
更改为packages=[],< /代码>。
In my experience, the cleanest solution is to add a
setup.py
like this structure:And the content of
setup.py
looks like this:After installing via
python setup.py develop
, inmyscript.py
, you can import mymodule like this:Or if you want to do
import mymodule
, you can movesetup.py
insideapp/
, same directory asmymodule.py
, and changepackages=['app']
topackages=[],
.